text
stringlengths
164
929k
(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_5__) { 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); /******/ }) /************************************************************************/ /******/ ((function(modules) { // Check all modules for deduplicated modules for(var i in modules) { if(Object.prototype.hasOwnProperty.call(modules, i)) { switch(typeof modules[i]) { case "function": break; case "object": // Module can be created from a template modules[i] = (function(_m) { var args = _m.slice(1), fn = modules[_m[0]]; return function (a,b,c) { fn.apply(this, [a,b,c].concat(args)); }; }(modules[i])); break; default: // Module is a copy of another module modules[i] = modules[modules[i]]; break; } } } return modules; }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.Utils = exports.Filters = exports.Draggable = exports.ToolsPanel = exports.Data = exports.Menu = exports.Toolbar = exports.Formatters = exports.Editors = undefined; var _draggable = __webpack_require__(134); var _draggable2 = _interopRequireDefault(_draggable); var _RowComparer = __webpack_require__(57); var _RowComparer2 = _interopRequireDefault(_RowComparer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Editors = __webpack_require__(139); var Formatters = __webpack_require__(142); var Toolbar = __webpack_require__(149); var ToolsPanel = __webpack_require__(150); var Data = __webpack_require__(129); var Menu = __webpack_require__(145); var Filters = __webpack_require__(124); var Utils = { rowComparer: _RowComparer2['default'] }; window.ReactDataGridPlugins = { Editors: Editors, Formatters: Formatters, Toolbar: Toolbar, Menu: Menu, Data: Data, ToolsPanel: ToolsPanel, Draggable: _draggable2['default'], Filters: Filters, Utils: Utils }; exports.Editors = Editors; exports.Formatters = Formatters; exports.Toolbar = Toolbar; exports.Menu = Menu; exports.Data = Data; exports.ToolsPanel = ToolsPanel; exports.Draggable = _draggable2['default']; exports.Filters = Filters; exports.Utils = Utils; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ 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. */ '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. */ var invariant = function(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; /***/ }, /* 3 */ /***/ 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; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(84); /** 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; /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), getPrototype = __webpack_require__(235), isObjectLike = __webpack_require__(9); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** 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 infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(211), getValue = __webpack_require__(238); /** * 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) { /** * 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; /***/ }, /* 9 */ /***/ 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; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), getRawTag = __webpack_require__(236), objectToString = __webpack_require__(264); /** `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; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(46), overRest = __webpack_require__(265), setToString = __webpack_require__(268); /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } module.exports = baseRest; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; } var _DragDropContext = __webpack_require__(307); exports.DragDropContext = _interopRequire(_DragDropContext); var _DragLayer = __webpack_require__(308); exports.DragLayer = _interopRequire(_DragLayer); var _DragSource = __webpack_require__(309); exports.DragSource = _interopRequire(_DragSource); var _DropTarget = __webpack_require__(310); exports.DropTarget = _interopRequire(_DropTarget); /***/ }, /* 13 */ /***/ 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; /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; module.exports = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(4); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 16 */ /***/ 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; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(91), isLength = __webpack_require__(48); /** * 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; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.beginDrag = beginDrag; exports.publishDragSource = publishDragSource; exports.hover = hover; exports.drop = drop; exports.endDrag = endDrag; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsMatchesType = __webpack_require__(67); var _utilsMatchesType2 = _interopRequireDefault(_utilsMatchesType); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); var _lodashIsObject = __webpack_require__(8); var _lodashIsObject2 = _interopRequireDefault(_lodashIsObject); var BEGIN_DRAG = 'dnd-core/BEGIN_DRAG'; exports.BEGIN_DRAG = BEGIN_DRAG; var PUBLISH_DRAG_SOURCE = 'dnd-core/PUBLISH_DRAG_SOURCE'; exports.PUBLISH_DRAG_SOURCE = PUBLISH_DRAG_SOURCE; var HOVER = 'dnd-core/HOVER'; exports.HOVER = HOVER; var DROP = 'dnd-core/DROP'; exports.DROP = DROP; var END_DRAG = 'dnd-core/END_DRAG'; exports.END_DRAG = END_DRAG; function beginDrag(sourceIds) { var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref$publishSource = _ref.publishSource; var publishSource = _ref$publishSource === undefined ? true : _ref$publishSource; var _ref$clientOffset = _ref.clientOffset; var clientOffset = _ref$clientOffset === undefined ? null : _ref$clientOffset; var getSourceClientOffset = _ref.getSourceClientOffset; _invariant2['default'](_lodashIsArray2['default'](sourceIds), 'Expected sourceIds to be an array.'); var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](!monitor.isDragging(), 'Cannot call beginDrag while dragging.'); for (var i = 0; i < sourceIds.length; i++) { _invariant2['default'](registry.getSource(sourceIds[i]), 'Expected sourceIds to be registered.'); } var sourceId = null; for (var i = sourceIds.length - 1; i >= 0; i--) { if (monitor.canDragSource(sourceIds[i])) { sourceId = sourceIds[i]; break; } } if (sourceId === null) { return; } var sourceClientOffset = null; if (clientOffset) { _invariant2['default'](typeof getSourceClientOffset === 'function', 'When clientOffset is provided, getSourceClientOffset must be a function.'); sourceClientOffset = getSourceClientOffset(sourceId); } var source = registry.getSource(sourceId); var item = source.beginDrag(monitor, sourceId); _invariant2['default'](_lodashIsObject2['default'](item), 'Item must be an object.'); registry.pinSource(sourceId); var itemType = registry.getSourceType(sourceId); return { type: BEGIN_DRAG, itemType: itemType, item: item, sourceId: sourceId, clientOffset: clientOffset, sourceClientOffset: sourceClientOffset, isSourcePublic: publishSource }; } function publishDragSource(manager) { var monitor = this.getMonitor(); if (!monitor.isDragging()) { return; } return { type: PUBLISH_DRAG_SOURCE }; } function hover(targetIds) { var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref2$clientOffset = _ref2.clientOffset; var clientOffset = _ref2$clientOffset === undefined ? null : _ref2$clientOffset; _invariant2['default'](_lodashIsArray2['default'](targetIds), 'Expected targetIds to be an array.'); targetIds = targetIds.slice(0); var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](monitor.isDragging(), 'Cannot call hover while not dragging.'); _invariant2['default'](!monitor.didDrop(), 'Cannot call hover after drop.'); // First check invariants. for (var i = 0; i < targetIds.length; i++) { var targetId = targetIds[i]; _invariant2['default'](targetIds.lastIndexOf(targetId) === i, 'Expected targetIds to be unique in the passed array.'); var target = registry.getTarget(targetId); _invariant2['default'](target, 'Expected targetIds to be registered.'); } var draggedItemType = monitor.getItemType(); // Remove those targetIds that don't match the targetType. This // fixes shallow isOver which would only be non-shallow because of // non-matching targets. for (var i = targetIds.length - 1; i >= 0; i--) { var targetId = targetIds[i]; var targetType = registry.getTargetType(targetId); if (!_utilsMatchesType2['default'](targetType, draggedItemType)) { targetIds.splice(i, 1); } } // Finally call hover on all matching targets. for (var i = 0; i < targetIds.length; i++) { var targetId = targetIds[i]; var target = registry.getTarget(targetId); target.hover(monitor, targetId); } return { type: HOVER, targetIds: targetIds, clientOffset: clientOffset }; } function drop() { var _this = this; var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](monitor.isDragging(), 'Cannot call drop while not dragging.'); _invariant2['default'](!monitor.didDrop(), 'Cannot call drop twice during one drag operation.'); var targetIds = monitor.getTargetIds().filter(monitor.canDropOnTarget, monitor); targetIds.reverse(); targetIds.forEach(function (targetId, index) { var target = registry.getTarget(targetId); var dropResult = target.drop(monitor, targetId); _invariant2['default'](typeof dropResult === 'undefined' || _lodashIsObject2['default'](dropResult), 'Drop result must either be an object or undefined.'); if (typeof dropResult === 'undefined') { dropResult = index === 0 ? {} : monitor.getDropResult(); } _this.store.dispatch({ type: DROP, dropResult: dropResult }); }); } function endDrag() { var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](monitor.isDragging(), 'Cannot call endDrag while not dragging.'); var sourceId = monitor.getSourceId(); var source = registry.getSource(sourceId, true); source.endDrag(monitor, sourceId); registry.unpinSource(); return { type: END_DRAG }; } /***/ }, /* 19 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.addSource = addSource; exports.addTarget = addTarget; exports.removeSource = removeSource; exports.removeTarget = removeTarget; var ADD_SOURCE = 'dnd-core/ADD_SOURCE'; exports.ADD_SOURCE = ADD_SOURCE; var ADD_TARGET = 'dnd-core/ADD_TARGET'; exports.ADD_TARGET = ADD_TARGET; var REMOVE_SOURCE = 'dnd-core/REMOVE_SOURCE'; exports.REMOVE_SOURCE = REMOVE_SOURCE; var REMOVE_TARGET = 'dnd-core/REMOVE_TARGET'; exports.REMOVE_TARGET = REMOVE_TARGET; function addSource(sourceId) { return { type: ADD_SOURCE, sourceId: sourceId }; } function addTarget(targetId) { return { type: ADD_TARGET, targetId: targetId }; } function removeSource(sourceId) { return { type: REMOVE_SOURCE, sourceId: sourceId }; } function removeTarget(targetId) { return { type: REMOVE_TARGET, targetId: targetId }; } /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(249), listCacheDelete = __webpack_require__(250), listCacheGet = __webpack_require__(251), listCacheHas = __webpack_require__(252), listCacheSet = __webpack_require__(253); /** * 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; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(38), setCacheAdd = __webpack_require__(266), setCacheHas = __webpack_require__(267); /** * * 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; /***/ }, /* 22 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(16); /** * 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; /***/ }, /* 24 */ /***/ 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; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(247); /** * 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; /***/ }, /* 26 */ /***/ 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; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(49); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(17), isObjectLike = __webpack_require__(9); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _redux = __webpack_require__(339); var _reducers = __webpack_require__(296); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _redux.createStore)(_reducers2.default); /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = checkDecoratorArguments; function checkDecoratorArguments(functionName, signature) { if (false) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (arg && arg.prototype && arg.prototype.render) { console.error( // eslint-disable-line no-console 'You seem to be applying the arguments in the wrong order. ' + ('It should be ' + functionName + '(' + signature + ')(Component), not the other way around. ') + 'Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#you-seem-to-be-applying-the-arguments-in-the-wrong-order'); return; } } } } module.exports = exports['default']; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/react-select */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); 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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _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; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactInputAutosize = __webpack_require__(320); var _reactInputAutosize2 = _interopRequireDefault(_reactInputAutosize); var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var _utilsDefaultArrowRenderer = __webpack_require__(334); var _utilsDefaultArrowRenderer2 = _interopRequireDefault(_utilsDefaultArrowRenderer); var _utilsDefaultFilterOptions = __webpack_require__(109); var _utilsDefaultFilterOptions2 = _interopRequireDefault(_utilsDefaultFilterOptions); var _utilsDefaultMenuRenderer = __webpack_require__(110); var _utilsDefaultMenuRenderer2 = _interopRequireDefault(_utilsDefaultMenuRenderer); var _Async = __webpack_require__(329); var _Async2 = _interopRequireDefault(_Async); var _AsyncCreatable = __webpack_require__(330); var _AsyncCreatable2 = _interopRequireDefault(_AsyncCreatable); var _Creatable = __webpack_require__(331); var _Creatable2 = _interopRequireDefault(_Creatable); var _Option = __webpack_require__(332); var _Option2 = _interopRequireDefault(_Option); var _Value = __webpack_require__(333); var _Value2 = _interopRequireDefault(_Value); function stringifyValue(value) { var valueType = typeof value; if (valueType === 'string') { return value; } else if (valueType === 'object') { return JSON.stringify(value); } else if (valueType === 'number' || valueType === 'boolean') { return String(value); } else { return ''; } } var stringOrNode = _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.node]); var instanceId = 1; var Select = _react2['default'].createClass({ displayName: 'Select', propTypes: { addLabelText: _react2['default'].PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input 'aria-label': _react2['default'].PropTypes.string, // Aria label (for assistive tech) 'aria-labelledby': _react2['default'].PropTypes.string, // HTML ID of an element that should be used as the label (for assistive tech) arrowRenderer: _react2['default'].PropTypes.func, // Create drop-down caret element autoBlur: _react2['default'].PropTypes.bool, // automatically blur the component when an option is selected autofocus: _react2['default'].PropTypes.bool, // autofocus the component on mount autosize: _react2['default'].PropTypes.bool, // whether to enable autosizing or not backspaceRemoves: _react2['default'].PropTypes.bool, // whether backspace removes an item if there is no text input backspaceToRemoveMessage: _react2['default'].PropTypes.string, // Message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label className: _react2['default'].PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearValueText: stringOrNode, // title for the "clear" control clearable: _react2['default'].PropTypes.bool, // should it be possible to reset value delimiter: _react2['default'].PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: _react2['default'].PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: _react2['default'].PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: _react2['default'].PropTypes.func, // method to filter a single option (option, filterString) filterOptions: _react2['default'].PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) ignoreAccents: _react2['default'].PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: _react2['default'].PropTypes.bool, // whether to perform case-insensitive filtering inputProps: _react2['default'].PropTypes.object, // custom attributes for the Input inputRenderer: _react2['default'].PropTypes.func, // returns a custom input component instanceId: _react2['default'].PropTypes.string, // set the components instanceId isLoading: _react2['default'].PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) joinValues: _react2['default'].PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode) labelKey: _react2['default'].PropTypes.string, // path of the label value in option objects matchPos: _react2['default'].PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: _react2['default'].PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: _react2['default'].PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: _react2['default'].PropTypes.object, // optional style to apply to the menu container menuRenderer: _react2['default'].PropTypes.func, // renders a custom menu with options menuStyle: _react2['default'].PropTypes.object, // optional style to apply to the menu multi: _react2['default'].PropTypes.bool, // multi-value input name: _react2['default'].PropTypes.string, // generates a hidden <input /> tag with this field name for html forms noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: _react2['default'].PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: _react2['default'].PropTypes.bool, // whether input is cleared on blur onChange: _react2['default'].PropTypes.func, // onChange handler: function (newValue) {} onClose: _react2['default'].PropTypes.func, // fires when the menu is closed onCloseResetsInput: _react2['default'].PropTypes.bool, // whether input is cleared when menu is closed through the arrow onFocus: _react2['default'].PropTypes.func, // onFocus handler: function (event) {} onInputChange: _react2['default'].PropTypes.func, // onInputChange handler: function (inputValue) {} onInputKeyDown: _react2['default'].PropTypes.func, // input keyDown handler: function (event) {} onMenuScrollToBottom: _react2['default'].PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: _react2['default'].PropTypes.func, // fires when the menu is opened onValueClick: _react2['default'].PropTypes.func, // onClick handler for value labels: function (value, event) {} openAfterFocus: _react2['default'].PropTypes.bool, // boolean to enable opening dropdown when focused openOnFocus: _react2['default'].PropTypes.bool, // always open options menu on focus optionClassName: _react2['default'].PropTypes.string, // additional class(es) to apply to the <Option /> elements optionComponent: _react2['default'].PropTypes.func, // option component to render in dropdown optionRenderer: _react2['default'].PropTypes.func, // optionRenderer: function (option) {} options: _react2['default'].PropTypes.array, // array of options pageSize: _react2['default'].PropTypes.number, // number of entries to page when using page up/down keys placeholder: stringOrNode, // field placeholder, displayed when there's no value required: _react2['default'].PropTypes.bool, // applies HTML5 required attribute when needed resetValue: _react2['default'].PropTypes.any, // value to use when you clear the control scrollMenuIntoView: _react2['default'].PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: _react2['default'].PropTypes.bool, // whether to enable searching feature or not simpleValue: _react2['default'].PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: _react2['default'].PropTypes.object, // optional style to apply to the control tabIndex: _react2['default'].PropTypes.string, // optional tab index of the control tabSelectsValue: _react2['default'].PropTypes.bool, // whether to treat tabbing out while focused to be value selection value: _react2['default'].PropTypes.any, // initial field value valueComponent: _react2['default'].PropTypes.func, // value component to render valueKey: _react2['default'].PropTypes.string, // path of the label value in option objects valueRenderer: _react2['default'].PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: _react2['default'].PropTypes.object }, // optional style to apply to the component wrapper statics: { Async: _Async2['default'], AsyncCreatable: _AsyncCreatable2['default'], Creatable: _Creatable2['default'] }, getDefaultProps: function getDefaultProps() { return { addLabelText: 'Add "{label}"?', arrowRenderer: _utilsDefaultArrowRenderer2['default'], autosize: true, backspaceRemoves: true, backspaceToRemoveMessage: 'Press backspace to remove {label}', clearable: true, clearAllText: 'Clear all', clearValueText: 'Clear value', delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: _utilsDefaultFilterOptions2['default'], ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, joinValues: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, menuRenderer: _utilsDefaultMenuRenderer2['default'], multi: false, noResultsText: 'No results found', onBlurResetsInput: true, onCloseResetsInput: true, openAfterFocus: false, optionComponent: _Option2['default'], pageSize: 5, placeholder: 'Select...', required: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, tabSelectsValue: true, valueComponent: _Value2['default'], valueKey: 'value' }; }, getInitialState: function getInitialState() { return { inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, required: false }; }, componentWillMount: function componentWillMount() { this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-'; var valueArray = this.getValueArray(this.props.value); if (this.props.required) { this.setState({ required: this.handleRequired(valueArray[0], this.props.multi) }); } }, componentDidMount: function componentDidMount() { if (this.props.autofocus) { this.focus(); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var valueArray = this.getValueArray(nextProps.value, nextProps); if (nextProps.required) { this.setState({ required: this.handleRequired(valueArray[0], nextProps.multi) }); } }, componentWillUpdate: function componentWillUpdate(nextProps, nextState) { if (nextState.isOpen !== this.state.isOpen) { this.toggleTouchOutsideEvent(nextState.isOpen); var handler = nextState.isOpen ? nextProps.onOpen : nextProps.onClose; handler && handler(); } }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { // focus to the selected option if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) { var focusedOptionNode = _reactDom2['default'].findDOMNode(this.focused); var menuNode = _reactDom2['default'].findDOMNode(this.menu); menuNode.scrollTop = focusedOptionNode.offsetTop; this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = _reactDom2['default'].findDOMNode(this.focused); var menuDOM = _reactDom2['default'].findDOMNode(this.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight; } } if (this.props.scrollMenuIntoView && this.menuContainer) { var menuContainerRect = this.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state this.closeMenu(); } }, componentWillUnmount: function componentWillUnmount() { document.removeEventListener('touchstart', this.handleTouchOutside); }, toggleTouchOutsideEvent: function toggleTouchOutsideEvent(enabled) { if (enabled) { document.addEventListener('touchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } }, handleTouchOutside: function handleTouchOutside(event) { // handle touch outside on ios to dismiss menu if (this.wrapper && !this.wrapper.contains(event.target)) { this.closeMenu(); } }, focus: function focus() { if (!this.input) return; this.input.focus(); if (this.props.openAfterFocus) { this.setState({ isOpen: true }); } }, blurInput: function blurInput() { if (!this.input) return; this.input.blur(); }, handleTouchMove: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; }, handleTouchEnd: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.handleMouseDown(event); }, handleTouchEndClearValue: function handleTouchEndClearValue(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Clear the value this.clearValue(event); }, handleMouseDown: function handleMouseDown(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (event.target.tagName === 'INPUT') { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { this.focus(); return this.setState({ isOpen: !this.state.isOpen }); } if (this.state.isFocused) { // On iOS, we can get into a state where we think the input is focused but it isn't really, // since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event. // Call focus() again here to be safe. this.focus(); var input = this.input; if (typeof input.getInput === 'function') { // Get the actual DOM input if the ref is an <AutosizeInput /> component input = input.getInput(); } // clears the value so that the cursor will be at the end of input when the component re-renders input.value = ''; // if the input is focused, ensure the menu is open this.setState({ isOpen: true, isPseudoFocused: false }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = true; this.focus(); } }, handleMouseDownOnArrow: function handleMouseDownOnArrow(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } // If the menu isn't open, let the event bubble to the main handleMouseDown if (!this.state.isOpen) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); }, handleMouseDownOnMenu: function handleMouseDownOnMenu(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); }, closeMenu: function closeMenu() { if (this.props.onCloseResetsInput) { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: '' }); } else { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: this.state.inputValue }); } this.hasScrolledToOption = false; }, handleInputFocus: function handleInputFocus(event) { if (this.props.disabled) return; var isOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus; if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: isOpen }); this._openAfterFocus = false; }, handleInputBlur: function handleInputBlur(event) { // The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts. if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) { this.focus(); return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = ''; } this.setState(onBlurredState); }, handleInputChange: function handleInputChange(event) { var newInputValue = event.target.value; if (this.state.inputValue !== event.target.value && this.props.onInputChange) { var nextState = this.props.onInputChange(newInputValue); // Note: != used deliberately here to catch undefined and null if (nextState != null && typeof nextState !== 'object') { newInputValue = '' + nextState; } } this.setState({ isOpen: true, isPseudoFocused: false, inputValue: newInputValue }); }, handleKeyDown: function handleKeyDown(event) { if (this.props.disabled) return; if (typeof this.props.onInputKeyDown === 'function') { this.props.onInputKeyDown(event); if (event.defaultPrevented) { return; } } switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) { return; } this.selectFocusedOption(); return; case 13: // enter if (!this.state.isOpen) return; event.stopPropagation(); this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.closeMenu(); event.stopPropagation(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); event.stopPropagation(); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; case 33: // page up this.focusPageUpOption(); break; case 34: // page down this.focusPageDownOption(); break; case 35: // end key if (event.shiftKey) { return; } this.focusEndOption(); break; case 36: // home key if (event.shiftKey) { return; } this.focusStartOption(); break; default: return; } event.preventDefault(); }, handleValueClick: function handleValueClick(option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); }, handleMenuScroll: function handleMenuScroll(event) { if (!this.props.onMenuScrollToBottom) return; var target = event.target; if (target.scrollHeight > target.offsetHeight && !(target.scrollHeight - target.offsetHeight - target.scrollTop)) { this.props.onMenuScrollToBottom(); } }, handleRequired: function handleRequired(value, multi) { if (!value) return true; return multi ? value.length === 0 : Object.keys(value).length === 0; }, getOptionLabel: function getOptionLabel(op) { return op[this.props.labelKey]; }, /** * Turns a value into an array from the given options * @param {String|Number|Array} value - the value of the select input * @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration * @returns {Array} the value of the select represented in an array */ getValueArray: function getValueArray(value, nextProps) { var _this = this; /** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */ var props = typeof nextProps === 'object' ? nextProps : this.props; if (props.multi) { if (typeof value === 'string') value = value.split(props.delimiter); if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(function (value) { return _this.expandValue(value, props); }).filter(function (i) { return i; }); } var expandedValue = this.expandValue(value, props); return expandedValue ? [expandedValue] : []; }, /** * Retrieve a value from the given options and valueKey * @param {String|Number|Array} value - the selected value(s) * @param {Object} props - the Select component's props (or nextProps) */ expandValue: function expandValue(value, props) { var valueType = typeof value; if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value; var options = props.options; var valueKey = props.valueKey; if (!options) return; for (var i = 0; i < options.length; i++) { if (options[i][valueKey] === value) return options[i]; } }, setValue: function setValue(value) { var _this2 = this; if (this.props.autoBlur) { this.blurInput(); } if (!this.props.onChange) return; if (this.props.required) { var required = this.handleRequired(value, this.props.multi); this.setState({ required: required }); } if (this.props.simpleValue && value) { value = this.props.multi ? value.map(function (i) { return i[_this2.props.valueKey]; }).join(this.props.delimiter) : value[this.props.valueKey]; } this.props.onChange(value); }, selectValue: function selectValue(value) { var _this3 = this; //NOTE: update value in the callback to make sure the input value is empty so that there are no styling issues (Chrome had issue otherwise) this.hasScrolledToOption = false; if (this.props.multi) { this.setState({ inputValue: '', focusedIndex: null }, function () { _this3.addValue(value); }); } else { this.setState({ isOpen: false, inputValue: '', isPseudoFocused: this.state.isFocused }, function () { _this3.setValue(value); }); } }, addValue: function addValue(value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.concat(value)); }, popValue: function popValue() { var valueArray = this.getValueArray(this.props.value); if (!valueArray.length) return; if (valueArray[valueArray.length - 1].clearableValue === false) return; this.setValue(valueArray.slice(0, valueArray.length - 1)); }, removeValue: function removeValue(value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.filter(function (i) { return i !== value; })); this.focus(); }, clearValue: function clearValue(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(this.getResetValue()); this.setState({ isOpen: false, inputValue: '' }, this.focus); }, getResetValue: function getResetValue() { if (this.props.resetValue !== undefined) { return this.props.resetValue; } else if (this.props.multi) { return []; } else { return null; } }, focusOption: function focusOption(option) { this.setState({ focusedOption: option }); }, focusNextOption: function focusNextOption() { this.focusAdjacentOption('next'); }, focusPreviousOption: function focusPreviousOption() { this.focusAdjacentOption('previous'); }, focusPageUpOption: function focusPageUpOption() { this.focusAdjacentOption('page_up'); }, focusPageDownOption: function focusPageDownOption() { this.focusAdjacentOption('page_down'); }, focusStartOption: function focusStartOption() { this.focusAdjacentOption('start'); }, focusEndOption: function focusEndOption() { this.focusAdjacentOption('end'); }, focusAdjacentOption: function focusAdjacentOption(dir) { var options = this._visibleOptions.map(function (option, index) { return { option: option, index: index }; }).filter(function (option) { return !option.option.disabled; }); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this._focusedOption || options[dir === 'next' ? 0 : options.length - 1].option }); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i].option) { focusedIndex = i; break; } } if (dir === 'next' && focusedIndex !== -1) { focusedIndex = (focusedIndex + 1) % options.length; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedIndex = focusedIndex - 1; } else { focusedIndex = options.length - 1; } } else if (dir === 'start') { focusedIndex = 0; } else if (dir === 'end') { focusedIndex = options.length - 1; } else if (dir === 'page_up') { var potentialIndex = focusedIndex - this.props.pageSize; if (potentialIndex < 0) { focusedIndex = 0; } else { focusedIndex = potentialIndex; } } else if (dir === 'page_down') { var potentialIndex = focusedIndex + this.props.pageSize; if (potentialIndex > options.length - 1) { focusedIndex = options.length - 1; } else { focusedIndex = potentialIndex; } } if (focusedIndex === -1) { focusedIndex = 0; } this.setState({ focusedIndex: options[focusedIndex].index, focusedOption: options[focusedIndex].option }); }, getFocusedOption: function getFocusedOption() { return this._focusedOption; }, getInputValue: function getInputValue() { return this.state.inputValue; }, selectFocusedOption: function selectFocusedOption() { if (this._focusedOption) { return this.selectValue(this._focusedOption); } }, renderLoading: function renderLoading() { if (!this.props.isLoading) return; return _react2['default'].createElement( 'span', { className: 'Select-loading-zone', 'aria-hidden': 'true' }, _react2['default'].createElement('span', { className: 'Select-loading' }) ); }, renderValue: function renderValue(valueArray, isOpen) { var _this4 = this; var renderLabel = this.props.valueRenderer || this.getOptionLabel; var ValueComponent = this.props.valueComponent; if (!valueArray.length) { return !this.state.inputValue ? _react2['default'].createElement( 'div', { className: 'Select-placeholder' }, this.props.placeholder ) : null; } var onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map(function (value, i) { return _react2['default'].createElement( ValueComponent, { id: _this4._instancePrefix + '-value-' + i, instancePrefix: _this4._instancePrefix, disabled: _this4.props.disabled || value.clearableValue === false, key: 'value-' + i + '-' + value[_this4.props.valueKey], onClick: onClick, onRemove: _this4.removeValue, value: value }, renderLabel(value, i), _react2['default'].createElement( 'span', { className: 'Select-aria-only' }, ' ' ) ); }); } else if (!this.state.inputValue) { if (isOpen) onClick = null; return _react2['default'].createElement( ValueComponent, { id: this._instancePrefix + '-value-item', disabled: this.props.disabled, instancePrefix: this._instancePrefix, onClick: onClick, value: valueArray[0] }, renderLabel(valueArray[0]) ); } }, renderInput: function renderInput(valueArray, focusedOptionIndex) { var _this5 = this; if (this.props.inputRenderer) { return this.props.inputRenderer(); } else { var _classNames; var className = (0, _classnames2['default'])('Select-input', this.props.inputProps.className); var isOpen = !!this.state.isOpen; var ariaOwns = (0, _classnames2['default'])((_classNames = {}, _defineProperty(_classNames, this._instancePrefix + '-list', isOpen), _defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames)); // TODO: Check how this project includes Object.assign() var inputProps = _extends({}, this.props.inputProps, { role: 'combobox', 'aria-expanded': '' + isOpen, 'aria-owns': ariaOwns, 'aria-haspopup': '' + isOpen, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-labelledby': this.props['aria-labelledby'], 'aria-label': this.props['aria-label'], className: className, tabIndex: this.props.tabIndex, onBlur: this.handleInputBlur, onChange: this.handleInputChange, onFocus: this.handleInputFocus, ref: function ref(_ref) { return _this5.input = _ref; }, required: this.state.required, value: this.state.inputValue }); if (this.props.disabled || !this.props.searchable) { var _props$inputProps = this.props.inputProps; var inputClassName = _props$inputProps.inputClassName; var divProps = _objectWithoutProperties(_props$inputProps, ['inputClassName']); return _react2['default'].createElement('div', _extends({}, divProps, { role: 'combobox', 'aria-expanded': isOpen, 'aria-owns': isOpen ? this._instancePrefix + '-list' : this._instancePrefix + '-value', 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', className: className, tabIndex: this.props.tabIndex || 0, onBlur: this.handleInputBlur, onFocus: this.handleInputFocus, ref: function (ref) { return _this5.input = ref; }, 'aria-readonly': '' + !!this.props.disabled, style: { border: 0, width: 1, display: 'inline-block' } })); } if (this.props.autosize) { return _react2['default'].createElement(_reactInputAutosize2['default'], _extends({}, inputProps, { minWidth: '5px' })); } return _react2['default'].createElement( 'div', { className: className }, _react2['default'].createElement('input', inputProps) ); } }, renderClear: function renderClear() { if (!this.props.clearable || !this.props.value || this.props.value === 0 || this.props.multi && !this.props.value.length || this.props.disabled || this.props.isLoading) return; return _react2['default'].createElement( 'span', { className: 'Select-clear-zone', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText, 'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText, onMouseDown: this.clearValue, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEndClearValue }, _react2['default'].createElement('span', { className: 'Select-clear', dangerouslySetInnerHTML: { __html: '&times;' } }) ); }, renderArrow: function renderArrow() { var onMouseDown = this.handleMouseDownOnArrow; var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown }); return _react2['default'].createElement( 'span', { className: 'Select-arrow-zone', onMouseDown: onMouseDown }, arrow ); }, filterOptions: function filterOptions(excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (this.props.filterOptions) { // Maintain backwards compatibility with boolean attribute var filterOptions = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : _utilsDefaultFilterOptions2['default']; return filterOptions(options, filterValue, excludeOptions, { filterOption: this.props.filterOption, ignoreAccents: this.props.ignoreAccents, ignoreCase: this.props.ignoreCase, labelKey: this.props.labelKey, matchPos: this.props.matchPos, matchProp: this.props.matchProp, valueKey: this.props.valueKey }); } else { return options; } }, onOptionRef: function onOptionRef(ref, isFocused) { if (isFocused) { this.focused = ref; } }, renderMenu: function renderMenu(options, valueArray, focusedOption) { if (options && options.length) { return this.props.menuRenderer({ focusedOption: focusedOption, focusOption: this.focusOption, instancePrefix: this._instancePrefix, labelKey: this.props.labelKey, onFocus: this.focusOption, onSelect: this.selectValue, optionClassName: this.props.optionClassName, optionComponent: this.props.optionComponent, optionRenderer: this.props.optionRenderer || this.getOptionLabel, options: options, selectValue: this.selectValue, valueArray: valueArray, valueKey: this.props.valueKey, onOptionRef: this.onOptionRef }); } else if (this.props.noResultsText) { return _react2['default'].createElement( 'div', { className: 'Select-noresults' }, this.props.noResultsText ); } else { return null; } }, renderHiddenField: function renderHiddenField(valueArray) { var _this6 = this; if (!this.props.name) return; if (this.props.joinValues) { var value = valueArray.map(function (i) { return stringifyValue(i[_this6.props.valueKey]); }).join(this.props.delimiter); return _react2['default'].createElement('input', { type: 'hidden', ref: function (ref) { return _this6.value = ref; }, name: this.props.name, value: value, disabled: this.props.disabled }); } return valueArray.map(function (item, index) { return _react2['default'].createElement('input', { key: 'hidden.' + index, type: 'hidden', ref: 'value' + index, name: _this6.props.name, value: stringifyValue(item[_this6.props.valueKey]), disabled: _this6.props.disabled }); }); }, getFocusableOptionIndex: function getFocusableOptionIndex(selectedOption) { var options = this._visibleOptions; if (!options.length) return null; var focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && !focusedOption.disabled) { var focusedOptionIndex = options.indexOf(focusedOption); if (focusedOptionIndex !== -1) { return focusedOptionIndex; } } for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return i; } return null; }, renderOuter: function renderOuter(options, valueArray, focusedOption) { var _this7 = this; var menu = this.renderMenu(options, valueArray, focusedOption); if (!menu) { return null; } return _react2['default'].createElement( 'div', { ref: function (ref) { return _this7.menuContainer = ref; }, className: 'Select-menu-outer', style: this.props.menuContainerStyle }, _react2['default'].createElement( 'div', { ref: function (ref) { return _this7.menu = ref; }, role: 'listbox', className: 'Select-menu', id: this._instancePrefix + '-list', style: this.props.menuStyle, onScroll: this.handleMenuScroll, onMouseDown: this.handleMouseDownOnMenu }, menu ) ); }, render: function render() { var _this8 = this; var valueArray = this.getValueArray(this.props.value); var options = this._visibleOptions = this.filterOptions(this.props.multi ? this.getValueArray(this.props.value) : null); var isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]); var focusedOption = null; if (focusedOptionIndex !== null) { focusedOption = this._focusedOption = options[focusedOptionIndex]; } else { focusedOption = this._focusedOption = null; } var className = (0, _classnames2['default'])('Select', this.props.className, { 'Select--multi': this.props.multi, 'Select--single': !this.props.multi, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'has-value': valueArray.length }); var removeMessage = null; if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) { removeMessage = _react2['default'].createElement( 'span', { id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' }, this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey]) ); } return _react2['default'].createElement( 'div', { ref: function (ref) { return _this8.wrapper = ref; }, className: className, style: this.props.wrapperStyle }, this.renderHiddenField(valueArray), _react2['default'].createElement( 'div', { ref: function (ref) { return _this8.control = ref; }, className: 'Select-control', style: this.props.style, onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleTouchEnd, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, _react2['default'].createElement( 'span', { className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' }, this.renderValue(valueArray, isOpen), this.renderInput(valueArray, focusedOptionIndex) ), removeMessage, this.renderLoading(), this.renderClear(), this.renderArrow() ), isOpen ? this.renderOuter(options, !this.props.multi ? valueArray : null, focusedOption) : null ); } }); exports['default'] = Select; module.exports = exports['default']; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__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__)); } else { window.classNames = classNames; } }()); /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _immutable = __webpack_require__(71); var isImmutableCollection = function isImmutableCollection(objToVerify) { return _immutable.Iterable.isIterable(objToVerify); }; exports['default'] = isImmutableCollection; /***/ }, /* 34 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; var getMixedTypeValueRetriever = function getMixedTypeValueRetriever(isImmutable) { var retObj = {}; var retriever = function retriever(item, key) { return item[key]; }; var immutableRetriever = function immutableRetriever(immutable, key) { return immutable.get(key); }; retObj.getValue = isImmutable ? immutableRetriever : retriever; return retObj; }; exports["default"] = getMixedTypeValueRetriever; /***/ }, /* 35 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = isDisposable; function isDisposable(obj) { return Boolean(obj && typeof obj.dispose === 'function'); } module.exports = exports['default']; /***/ }, /* 36 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = ownerDocument; function ownerDocument(node) { return node && node.ownerDocument || document; } module.exports = exports["default"]; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(254), mapCacheDelete = __webpack_require__(255), mapCacheGet = __webpack_require__(256), mapCacheHas = __webpack_require__(257), mapCacheSet = __webpack_require__(258); /** * 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; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(205); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }, /* 40 */ /***/ function(module, exports) { /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } module.exports = arrayIncludesWith; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(82); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }, /* 42 */ /***/ 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; /***/ }, /* 43 */ /***/ 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; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(3), isSymbol = __webpack_require__(49); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }, /* 45 */ /***/ 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; /***/ }, /* 46 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(207), isObjectLike = __webpack_require__(9); /** 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; /***/ }, /* 48 */ /***/ 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; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isObjectLike = __webpack_require__(9); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(75), baseKeys = __webpack_require__(214), isArrayLike = __webpack_require__(17); /** * 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; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { getItem: function getItem() { return _store2.default.getState().currentItem; }, getPosition: function getPosition() { var _store$getState = _store2.default.getState(); var x = _store$getState.x; var y = _store$getState.y; return { x: x, y: y }; }, hideMenu: function hideMenu() { _store2.default.dispatch({ type: "SET_PARAMS", data: { isVisible: false, currentItem: {} } }); } }; /* eslint-disable object-property-newline */ /***/ }, /* 52 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var FILE = '__NATIVE_FILE__'; exports.FILE = FILE; var URL = '__NATIVE_URL__'; exports.URL = URL; var TEXT = '__NATIVE_TEXT__'; exports.TEXT = TEXT; /***/ }, /* 53 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = shallowEqual; function shallowEqual(objA, objB) { if (objA === objB) { return true; } 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 hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } var valA = objA[keysA[i]]; var valB = objB[keysA[i]]; if (valA !== valB) { return false; } } return true; } module.exports = exports["default"]; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(6); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(342); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 55 */ /***/ 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; } /***/ }, /* 56 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var DragItemTypes = exports.DragItemTypes = { Column: 'column' }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.shouldRowUpdate = undefined; var _ColumnMetrics = __webpack_require__(117); var _ColumnMetrics2 = _interopRequireDefault(_ColumnMetrics); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function doesRowContainSelectedCell(props) { var selected = props.cellMetaData.selected; if (selected && selected.rowIdx === props.idx) { return true; } return false; } function willRowBeDraggedOver(props) { var dragged = props.cellMetaData.dragged; return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true); } function hasRowBeenCopied(props) { var copied = props.cellMetaData.copied; return copied != null && copied.rowIdx === props.idx; } var shouldRowUpdate = exports.shouldRowUpdate = function shouldRowUpdate(nextProps, currentProps) { return !_ColumnMetrics2['default'].sameColumns(currentProps.columns, nextProps.columns, _ColumnMetrics2['default'].sameColumn) || doesRowContainSelectedCell(currentProps) || doesRowContainSelectedCell(nextProps) || willRowBeDraggedOver(nextProps) || nextProps.row !== currentProps.row || currentProps.colDisplayStart !== nextProps.colDisplayStart || currentProps.colDisplayEnd !== nextProps.colDisplayEnd || currentProps.colVisibleStart !== nextProps.colVisibleStart || currentProps.colVisibleEnd !== nextProps.colVisibleEnd || hasRowBeenCopied(currentProps) || currentProps.isSelected !== nextProps.isSelected || nextProps.height !== currentProps.height || currentProps.isOver !== nextProps.isOver || currentProps.canDrop !== nextProps.canDrop || currentProps.forceUpdate === true; }; exports['default'] = shouldRowUpdate; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reselect = __webpack_require__(340); var _isEmptyObject = __webpack_require__(151); var _isEmptyObject2 = _interopRequireDefault(_isEmptyObject); var _isEmptyArray = __webpack_require__(62); var _isEmptyArray2 = _interopRequireDefault(_isEmptyArray); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var groupRows = __webpack_require__(126); var filterRows = __webpack_require__(125); var sortRows = __webpack_require__(128); var getInputRows = function getInputRows(state) { return state.rows; }; var getFilters = function getFilters(state) { return state.filters; }; var getFilteredRows = (0, _reselect.createSelector)([getFilters, getInputRows], function (filters) { var rows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (!filters || (0, _isEmptyObject2['default'])(filters)) { return rows; } return filterRows(filters, rows); }); var getSortColumn = function getSortColumn(state) { return state.sortColumn; }; var getSortDirection = function getSortDirection(state) { return state.sortDirection; }; var getSortedRows = (0, _reselect.createSelector)([getFilteredRows, getSortColumn, getSortDirection], function (rows, sortColumn, sortDirection) { if (!sortDirection && !sortColumn) { return rows; } return sortRows(rows, sortColumn, sortDirection); }); var getGroupedColumns = function getGroupedColumns(state) { return state.groupBy; }; var getExpandedRows = function getExpandedRows(state) { return state.expandedRows; }; var getFlattenedGroupedRows = (0, _reselect.createSelector)([getSortedRows, getGroupedColumns, getExpandedRows], function (rows, groupedColumns) { var expandedRows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (!groupedColumns || (0, _isEmptyObject2['default'])(groupedColumns) || (0, _isEmptyArray2['default'])(groupedColumns)) { return rows; } return groupRows(rows, groupedColumns, expandedRows); }); var getSelectedKeys = function getSelectedKeys(state) { return state.selectedKeys; }; var getRowKey = function getRowKey(state) { return state.rowKey; }; var getSelectedRowsByKey = (0, _reselect.createSelector)([getRowKey, getSelectedKeys, getInputRows], function (rowKey, selectedKeys) { var rows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; return selectedKeys.map(function (k) { return rows.filter(function (r) { return r[rowKey] === k; })[0]; }); }); var Selectors = { getRows: getFlattenedGroupedRows, getSelectedRowsByKey: getSelectedRowsByKey }; module.exports = Selectors; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _Constants = __webpack_require__(56); var _reactDnd = __webpack_require__(12); var _HeaderCell = __webpack_require__(120); var _HeaderCell2 = _interopRequireDefault(_HeaderCell); 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 DraggableHeaderCell = function (_Component) { _inherits(DraggableHeaderCell, _Component); function DraggableHeaderCell() { _classCallCheck(this, DraggableHeaderCell); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } DraggableHeaderCell.prototype.componentDidMount = function componentDidMount() { var connectDragPreview = this.props.connectDragPreview; var img = new Image(); img.src = './assets/images/drag_column_full.png'; img.onload = function () { connectDragPreview(img); }; }; DraggableHeaderCell.prototype.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)'; }; DraggableHeaderCell.prototype.render = function render() { var _props = this.props, connectDragSource = _props.connectDragSource, isDragging = _props.isDragging; if (isDragging) { return null; } return connectDragSource(_react2['default'].createElement( 'div', { style: { cursor: 'move' } }, _react2['default'].createElement(_HeaderCell2['default'], this.props) )); }; return DraggableHeaderCell; }(_react.Component); DraggableHeaderCell.propTypes = { connectDragSource: _react.PropTypes.func.isRequired, connectDragPreview: _react.PropTypes.func.isRequired, isDragging: _react.PropTypes.bool.isRequired }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview() }; } var headerCellSource = { beginDrag: function beginDrag(props) { return props.column; }, endDrag: function endDrag(props) { return props.column; } }; exports['default'] = (0, _reactDnd.DragSource)(_Constants.DragItemTypes.Column, headerCellSource, collect)(DraggableHeaderCell); /***/ }, /* 60 */ /***/ 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; /***/ }, /* 61 */ /***/ 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__(5); var ExcelColumn = __webpack_require__(13); 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; /***/ }, /* 62 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; var isEmptyArray = function isEmptyArray(obj) { return Array.isArray(obj) && obj.length === 0; }; exports["default"] = isEmptyArray; /***/ }, /* 63 */ /***/ function(module, exports) { 'use strict'; module.exports = function isColumnsImmutable(columns) { return typeof Immutable !== 'undefined' && columns instanceof Immutable.List; }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _typeof(obj) { return obj && obj.constructor === Symbol ? 'symbol' : typeof obj; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); var _utilsGetNextUniqueId = __webpack_require__(170); var _utilsGetNextUniqueId2 = _interopRequireDefault(_utilsGetNextUniqueId); var _actionsRegistry = __webpack_require__(19); var _asap = __webpack_require__(114); var _asap2 = _interopRequireDefault(_asap); var HandlerRoles = { SOURCE: 'SOURCE', TARGET: 'TARGET' }; function validateSourceContract(source) { _invariant2['default'](typeof source.canDrag === 'function', 'Expected canDrag to be a function.'); _invariant2['default'](typeof source.beginDrag === 'function', 'Expected beginDrag to be a function.'); _invariant2['default'](typeof source.endDrag === 'function', 'Expected endDrag to be a function.'); } function validateTargetContract(target) { _invariant2['default'](typeof target.canDrop === 'function', 'Expected canDrop to be a function.'); _invariant2['default'](typeof target.hover === 'function', 'Expected hover to be a function.'); _invariant2['default'](typeof target.drop === 'function', 'Expected beginDrag to be a function.'); } function validateType(type, allowArray) { if (allowArray && _lodashIsArray2['default'](type)) { type.forEach(function (t) { return validateType(t, false); }); return; } _invariant2['default'](typeof type === 'string' || (typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'symbol', allowArray ? 'Type can only be a string, a symbol, or an array of either.' : 'Type can only be a string or a symbol.'); } function getNextHandlerId(role) { var id = _utilsGetNextUniqueId2['default']().toString(); switch (role) { case HandlerRoles.SOURCE: return 'S' + id; case HandlerRoles.TARGET: return 'T' + id; default: _invariant2['default'](false, 'Unknown role: ' + role); } } function parseRoleFromHandlerId(handlerId) { switch (handlerId[0]) { case 'S': return HandlerRoles.SOURCE; case 'T': return HandlerRoles.TARGET; default: _invariant2['default'](false, 'Cannot parse handler ID: ' + handlerId); } } var HandlerRegistry = (function () { function HandlerRegistry(store) { _classCallCheck(this, HandlerRegistry); this.store = store; this.types = {}; this.handlers = {}; this.pinnedSourceId = null; this.pinnedSource = null; } HandlerRegistry.prototype.addSource = function addSource(type, source) { validateType(type); validateSourceContract(source); var sourceId = this.addHandler(HandlerRoles.SOURCE, type, source); this.store.dispatch(_actionsRegistry.addSource(sourceId)); return sourceId; }; HandlerRegistry.prototype.addTarget = function addTarget(type, target) { validateType(type, true); validateTargetContract(target); var targetId = this.addHandler(HandlerRoles.TARGET, type, target); this.store.dispatch(_actionsRegistry.addTarget(targetId)); return targetId; }; HandlerRegistry.prototype.addHandler = function addHandler(role, type, handler) { var id = getNextHandlerId(role); this.types[id] = type; this.handlers[id] = handler; return id; }; HandlerRegistry.prototype.containsHandler = function containsHandler(handler) { var _this = this; return Object.keys(this.handlers).some(function (key) { return _this.handlers[key] === handler; }); }; HandlerRegistry.prototype.getSource = function getSource(sourceId, includePinned) { _invariant2['default'](this.isSourceId(sourceId), 'Expected a valid source ID.'); var isPinned = includePinned && sourceId === this.pinnedSourceId; var source = isPinned ? this.pinnedSource : this.handlers[sourceId]; return source; }; HandlerRegistry.prototype.getTarget = function getTarget(targetId) { _invariant2['default'](this.isTargetId(targetId), 'Expected a valid target ID.'); return this.handlers[targetId]; }; HandlerRegistry.prototype.getSourceType = function getSourceType(sourceId) { _invariant2['default'](this.isSourceId(sourceId), 'Expected a valid source ID.'); return this.types[sourceId]; }; HandlerRegistry.prototype.getTargetType = function getTargetType(targetId) { _invariant2['default'](this.isTargetId(targetId), 'Expected a valid target ID.'); return this.types[targetId]; }; HandlerRegistry.prototype.isSourceId = function isSourceId(handlerId) { var role = parseRoleFromHandlerId(handlerId); return role === HandlerRoles.SOURCE; }; HandlerRegistry.prototype.isTargetId = function isTargetId(handlerId) { var role = parseRoleFromHandlerId(handlerId); return role === HandlerRoles.TARGET; }; HandlerRegistry.prototype.removeSource = function removeSource(sourceId) { var _this2 = this; _invariant2['default'](this.getSource(sourceId), 'Expected an existing source.'); this.store.dispatch(_actionsRegistry.removeSource(sourceId)); _asap2['default'](function () { delete _this2.handlers[sourceId]; delete _this2.types[sourceId]; }); }; HandlerRegistry.prototype.removeTarget = function removeTarget(targetId) { var _this3 = this; _invariant2['default'](this.getTarget(targetId), 'Expected an existing target.'); this.store.dispatch(_actionsRegistry.removeTarget(targetId)); _asap2['default'](function () { delete _this3.handlers[targetId]; delete _this3.types[targetId]; }); }; HandlerRegistry.prototype.pinSource = function pinSource(sourceId) { var source = this.getSource(sourceId); _invariant2['default'](source, 'Expected an existing source.'); this.pinnedSourceId = sourceId; this.pinnedSource = source; }; HandlerRegistry.prototype.unpinSource = function unpinSource() { _invariant2['default'](this.pinnedSource, 'No source is pinned at the time.'); this.pinnedSourceId = null; this.pinnedSource = null; }; return HandlerRegistry; })(); exports['default'] = HandlerRegistry; module.exports = exports['default']; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = dirtyHandlerIds; exports.areDirty = areDirty; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashXor = __webpack_require__(289); var _lodashXor2 = _interopRequireDefault(_lodashXor); var _lodashIntersection = __webpack_require__(283); var _lodashIntersection2 = _interopRequireDefault(_lodashIntersection); var _actionsDragDrop = __webpack_require__(18); var _actionsRegistry = __webpack_require__(19); var NONE = []; var ALL = []; function dirtyHandlerIds(state, action, dragOperation) { if (state === undefined) state = NONE; switch (action.type) { case _actionsDragDrop.HOVER: break; case _actionsRegistry.ADD_SOURCE: case _actionsRegistry.ADD_TARGET: case _actionsRegistry.REMOVE_TARGET: case _actionsRegistry.REMOVE_SOURCE: return NONE; case _actionsDragDrop.BEGIN_DRAG: case _actionsDragDrop.PUBLISH_DRAG_SOURCE: case _actionsDragDrop.END_DRAG: case _actionsDragDrop.DROP: default: return ALL; } var targetIds = action.targetIds; var prevTargetIds = dragOperation.targetIds; var dirtyHandlerIds = _lodashXor2['default'](targetIds, prevTargetIds); var didChange = false; if (dirtyHandlerIds.length === 0) { for (var i = 0; i < targetIds.length; i++) { if (targetIds[i] !== prevTargetIds[i]) { didChange = true; break; } } } else { didChange = true; } if (!didChange) { return NONE; } var prevInnermostTargetId = prevTargetIds[prevTargetIds.length - 1]; var innermostTargetId = targetIds[targetIds.length - 1]; if (prevInnermostTargetId !== innermostTargetId) { if (prevInnermostTargetId) { dirtyHandlerIds.push(prevInnermostTargetId); } if (innermostTargetId) { dirtyHandlerIds.push(innermostTargetId); } } return dirtyHandlerIds; } function areDirty(state, handlerIds) { if (state === NONE) { return false; } if (state === ALL || typeof handlerIds === 'undefined') { return true; } return _lodashIntersection2['default'](handlerIds, state).length > 0; } /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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; }; exports['default'] = dragOffset; exports.getSourceClientOffset = getSourceClientOffset; exports.getDifferenceFromInitialOffset = getDifferenceFromInitialOffset; var _actionsDragDrop = __webpack_require__(18); var initialState = { initialSourceClientOffset: null, initialClientOffset: null, clientOffset: null }; function areOffsetsEqual(offsetA, offsetB) { if (offsetA === offsetB) { return true; } return offsetA && offsetB && offsetA.x === offsetB.x && offsetA.y === offsetB.y; } function dragOffset(state, action) { if (state === undefined) state = initialState; switch (action.type) { case _actionsDragDrop.BEGIN_DRAG: return { initialSourceClientOffset: action.sourceClientOffset, initialClientOffset: action.clientOffset, clientOffset: action.clientOffset }; case _actionsDragDrop.HOVER: if (areOffsetsEqual(state.clientOffset, action.clientOffset)) { return state; } return _extends({}, state, { clientOffset: action.clientOffset }); case _actionsDragDrop.END_DRAG: case _actionsDragDrop.DROP: return initialState; default: return state; } } function getSourceClientOffset(state) { var clientOffset = state.clientOffset; var initialClientOffset = state.initialClientOffset; var initialSourceClientOffset = state.initialSourceClientOffset; if (!clientOffset || !initialClientOffset || !initialSourceClientOffset) { return null; } return { x: clientOffset.x + initialSourceClientOffset.x - initialClientOffset.x, y: clientOffset.y + initialSourceClientOffset.y - initialClientOffset.y }; } function getDifferenceFromInitialOffset(state) { var clientOffset = state.clientOffset; var initialClientOffset = state.initialClientOffset; if (!clientOffset || !initialClientOffset) { return null; } return { x: clientOffset.x - initialClientOffset.x, y: clientOffset.y - initialClientOffset.y }; } /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = matchesType; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); function matchesType(targetType, draggedItemType) { if (_lodashIsArray2['default'](targetType)) { return targetType.some(function (t) { return t === draggedItemType; }); } else { return targetType === draggedItemType; } } module.exports = exports['default']; /***/ }, /* 68 */ /***/ function(module, exports) { 'use strict'; module.exports = function hasClass(element, className) { if (element.classList) return !!className && element.classList.contains(className);else return (' ' + element.className + ' ').indexOf(' ' + className + ' ') !== -1; }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === "object") { factory(exports); } else { factory(root.babelHelpers = {}); } })(this, function (global) { var babelHelpers = global; babelHelpers.interopRequireDefault = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; babelHelpers._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; }; }) /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js */ 'use strict'; var camelize = __webpack_require__(182); var msPattern = /^-ms-/; module.exports = function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); }; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2014-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. */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Immutable = factory()); }(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice; function createClass(ctor, superClass) { if (superClass) { ctor.prototype = Object.create(superClass.prototype); } ctor.prototype.constructor = ctor; } function Iterable(value) { return isIterable(value) ? value : Seq(value); } createClass(KeyedIterable, Iterable); function KeyedIterable(value) { return isKeyed(value) ? value : KeyedSeq(value); } createClass(IndexedIterable, Iterable); function IndexedIterable(value) { return isIndexed(value) ? value : IndexedSeq(value); } createClass(SetIterable, Iterable); function SetIterable(value) { return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); } function isIterable(maybeIterable) { return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); } function isKeyed(maybeKeyed) { return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); } function isIndexed(maybeIndexed) { return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); } function isAssociative(maybeAssociative) { return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); } function isOrdered(maybeOrdered) { return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); } Iterable.isIterable = isIterable; Iterable.isKeyed = isKeyed; Iterable.isIndexed = isIndexed; Iterable.isAssociative = isAssociative; Iterable.isOrdered = isOrdered; Iterable.Keyed = KeyedIterable; Iterable.Indexed = IndexedIterable; Iterable.Set = SetIterable; var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; // Used for setting prototype methods that IE8 chokes on. var DELETE = 'delete'; // Constants describing the size of trie nodes. var SHIFT = 5; // Resulted in best performance after ______? var SIZE = 1 << SHIFT; var MASK = SIZE - 1; // A consistent shared value representing "not set" which equals nothing other // than itself, and nothing that could be provided externally. var NOT_SET = {}; // Boolean references, Rough equivalent of `bool &`. var CHANGE_LENGTH = { value: false }; var DID_ALTER = { value: false }; function MakeRef(ref) { ref.value = false; return ref; } function SetRef(ref) { ref && (ref.value = true); } // A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. function OwnerID() {} // http://jsperf.com/copy-array-inline function arrCopy(arr, offset) { offset = offset || 0; var len = Math.max(0, arr.length - offset); var newArr = new Array(len); for (var ii = 0; ii < len; ii++) { newArr[ii] = arr[ii + offset]; } return newArr; } function ensureSize(iter) { if (iter.size === undefined) { iter.size = iter.__iterate(returnTrue); } return iter.size; } function wrapIndex(iter, index) { // This implements "is array index" which the ECMAString spec defines as: // // A String property name P is an array index if and only if // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal // to 2^32−1. // // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects if (typeof index !== 'number') { var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 if ('' + uint32Index !== index || uint32Index === 4294967295) { return NaN; } index = uint32Index; } return index < 0 ? ensureSize(iter) + index : index; } function returnTrue() { return true; } function wholeSlice(begin, end, size) { return (begin === 0 || (size !== undefined && begin <= -size)) && (end === undefined || (size !== undefined && end >= size)); } function resolveBegin(begin, size) { return resolveIndex(begin, size, 0); } function resolveEnd(end, size) { return resolveIndex(end, size, size); } function resolveIndex(index, size, defaultIndex) { return index === undefined ? defaultIndex : index < 0 ? Math.max(0, size + index) : size === undefined ? index : Math.min(size, index); } /* global Symbol */ var ITERATE_KEYS = 0; var ITERATE_VALUES = 1; var ITERATE_ENTRIES = 2; var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; function Iterator(next) { this.next = next; } Iterator.prototype.toString = function() { return '[Iterator]'; }; Iterator.KEYS = ITERATE_KEYS; Iterator.VALUES = ITERATE_VALUES; Iterator.ENTRIES = ITERATE_ENTRIES; Iterator.prototype.inspect = Iterator.prototype.toSource = function () { return this.toString(); } Iterator.prototype[ITERATOR_SYMBOL] = function () { return this; }; function iteratorValue(type, k, v, iteratorResult) { var value = type === 0 ? k : type === 1 ? v : [k, v]; iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { value: value, done: false }); return iteratorResult; } function iteratorDone() { return { value: undefined, done: true }; } function hasIterator(maybeIterable) { return !!getIteratorFn(maybeIterable); } function isIterator(maybeIterator) { return maybeIterator && typeof maybeIterator.next === 'function'; } function getIterator(iterable) { var iteratorFn = getIteratorFn(iterable); return iteratorFn && iteratorFn.call(iterable); } function getIteratorFn(iterable) { var iteratorFn = iterable && ( (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || iterable[FAUX_ITERATOR_SYMBOL] ); if (typeof iteratorFn === 'function') { return iteratorFn; } } function isArrayLike(value) { return value && typeof value.length === 'number'; } createClass(Seq, Iterable); function Seq(value) { return value === null || value === undefined ? emptySequence() : isIterable(value) ? value.toSeq() : seqFromValue(value); } Seq.of = function(/*...values*/) { return Seq(arguments); }; Seq.prototype.toSeq = function() { return this; }; Seq.prototype.toString = function() { return this.__toString('Seq {', '}'); }; Seq.prototype.cacheResult = function() { if (!this._cache && this.__iterateUncached) { this._cache = this.entrySeq().toArray(); this.size = this._cache.length; } return this; }; // abstract __iterateUncached(fn, reverse) Seq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, true); }; // abstract __iteratorUncached(type, reverse) Seq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, true); }; createClass(KeyedSeq, Seq); function KeyedSeq(value) { return value === null || value === undefined ? emptySequence().toKeyedSeq() : isIterable(value) ? (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : keyedSeqFromValue(value); } KeyedSeq.prototype.toKeyedSeq = function() { return this; }; createClass(IndexedSeq, Seq); function IndexedSeq(value) { return value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); } IndexedSeq.of = function(/*...values*/) { return IndexedSeq(arguments); }; IndexedSeq.prototype.toIndexedSeq = function() { return this; }; IndexedSeq.prototype.toString = function() { return this.__toString('Seq [', ']'); }; IndexedSeq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, false); }; IndexedSeq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, false); }; createClass(SetSeq, Seq); function SetSeq(value) { return ( value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value ).toSetSeq(); } SetSeq.of = function(/*...values*/) { return SetSeq(arguments); }; SetSeq.prototype.toSetSeq = function() { return this; }; Seq.isSeq = isSeq; Seq.Keyed = KeyedSeq; Seq.Set = SetSeq; Seq.Indexed = IndexedSeq; var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; Seq.prototype[IS_SEQ_SENTINEL] = true; createClass(ArraySeq, IndexedSeq); function ArraySeq(array) { this._array = array; this.size = array.length; } ArraySeq.prototype.get = function(index, notSetValue) { return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; }; ArraySeq.prototype.__iterate = function(fn, reverse) { var array = this._array; var maxIndex = array.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { return ii + 1; } } return ii; }; ArraySeq.prototype.__iterator = function(type, reverse) { var array = this._array; var maxIndex = array.length - 1; var ii = 0; return new Iterator(function() {return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} ); }; createClass(ObjectSeq, KeyedSeq); function ObjectSeq(object) { var keys = Object.keys(object); this._object = object; this._keys = keys; this.size = keys.length; } ObjectSeq.prototype.get = function(key, notSetValue) { if (notSetValue !== undefined && !this.has(key)) { return notSetValue; } return this._object[key]; }; ObjectSeq.prototype.has = function(key) { return this._object.hasOwnProperty(key); }; ObjectSeq.prototype.__iterate = function(fn, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var key = keys[reverse ? maxIndex - ii : ii]; if (fn(object[key], key, this) === false) { return ii + 1; } } return ii; }; ObjectSeq.prototype.__iterator = function(type, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; var ii = 0; return new Iterator(function() { var key = keys[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, key, object[key]); }); }; ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; createClass(IterableSeq, IndexedSeq); function IterableSeq(iterable) { this._iterable = iterable; this.size = iterable.length || iterable.size; } IterableSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); var iterations = 0; if (isIterator(iterator)) { var step; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } } return iterations; }; IterableSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); if (!isIterator(iterator)) { return new Iterator(iteratorDone); } var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value); }); }; createClass(IteratorSeq, IndexedSeq); function IteratorSeq(iterator) { this._iterator = iterator; this._iteratorCache = []; } IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; while (iterations < cache.length) { if (fn(cache[iterations], iterations++, this) === false) { return iterations; } } var step; while (!(step = iterator.next()).done) { var val = step.value; cache[iterations] = val; if (fn(val, iterations++, this) === false) { break; } } return iterations; }; IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; return new Iterator(function() { if (iterations >= cache.length) { var step = iterator.next(); if (step.done) { return step; } cache[iterations] = step.value; } return iteratorValue(type, iterations, cache[iterations++]); }); }; // # pragma Helper functions function isSeq(maybeSeq) { return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); } var EMPTY_SEQ; function emptySequence() { return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); } function keyedSeqFromValue(value) { var seq = Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : typeof value === 'object' ? new ObjectSeq(value) : undefined; if (!seq) { throw new TypeError( 'Expected Array or iterable object of [k, v] entries, '+ 'or keyed object: ' + value ); } return seq; } function indexedSeqFromValue(value) { var seq = maybeIndexedSeqFromValue(value); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values: ' + value ); } return seq; } function seqFromValue(value) { var seq = maybeIndexedSeqFromValue(value) || (typeof value === 'object' && new ObjectSeq(value)); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values, or keyed object: ' + value ); } return seq; } function maybeIndexedSeqFromValue(value) { return ( isArrayLike(value) ? new ArraySeq(value) : isIterator(value) ? new IteratorSeq(value) : hasIterator(value) ? new IterableSeq(value) : undefined ); } function seqIterate(seq, fn, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var entry = cache[reverse ? maxIndex - ii : ii]; if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { return ii + 1; } } return ii; } return seq.__iterateUncached(fn, reverse); } function seqIterator(seq, type, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; var ii = 0; return new Iterator(function() { var entry = cache[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); }); } return seq.__iteratorUncached(type, reverse); } function fromJS(json, converter) { return converter ? fromJSWith(converter, json, '', {'': json}) : fromJSDefault(json); } function fromJSWith(converter, json, key, parentJSON) { if (Array.isArray(json)) { return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } if (isPlainObj(json)) { return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } return json; } function fromJSDefault(json) { if (Array.isArray(json)) { return IndexedSeq(json).map(fromJSDefault).toList(); } if (isPlainObj(json)) { return KeyedSeq(json).map(fromJSDefault).toMap(); } return json; } function isPlainObj(value) { return value && (value.constructor === Object || value.constructor === undefined); } /** * An extension of the "same-value" algorithm as [described for use by ES6 Map * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) * * NaN is considered the same as NaN, however -0 and 0 are considered the same * value, which is different from the algorithm described by * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * This is extended further to allow Objects to describe the values they * represent, by way of `valueOf` or `equals` (and `hashCode`). * * Note: because of this extension, the key equality of Immutable.Map and the * value equality of Immutable.Set will differ from ES6 Map and Set. * * ### Defining custom values * * The easiest way to describe the value an object represents is by implementing * `valueOf`. For example, `Date` represents a value by returning a unix * timestamp for `valueOf`: * * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... * var date2 = new Date(1234567890000); * date1.valueOf(); // 1234567890000 * assert( date1 !== date2 ); * assert( Immutable.is( date1, date2 ) ); * * Note: overriding `valueOf` may have other implications if you use this object * where JavaScript expects a primitive, such as implicit string coercion. * * For more complex types, especially collections, implementing `valueOf` may * not be performant. An alternative is to implement `equals` and `hashCode`. * * `equals` takes another object, presumably of similar type, and returns true * if the it is equal. Equality is symmetrical, so the same result should be * returned if this and the argument are flipped. * * assert( a.equals(b) === b.equals(a) ); * * `hashCode` returns a 32bit integer number representing the object which will * be used to determine how to store the value object in a Map or Set. You must * provide both or neither methods, one must not exist without the other. * * Also, an important relationship between these methods must be upheld: if two * values are equal, they *must* return the same hashCode. If the values are not * equal, they might have the same hashCode; this is called a hash collision, * and while undesirable for performance reasons, it is acceptable. * * if (a.equals(b)) { * assert( a.hashCode() === b.hashCode() ); * } * * All Immutable collections implement `equals` and `hashCode`. * */ function is(valueA, valueB) { if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } if (typeof valueA.valueOf === 'function' && typeof valueB.valueOf === 'function') { valueA = valueA.valueOf(); valueB = valueB.valueOf(); if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } } if (typeof valueA.equals === 'function' && typeof valueB.equals === 'function' && valueA.equals(valueB)) { return true; } return false; } function deepEqual(a, b) { if (a === b) { return true; } if ( !isIterable(b) || a.size !== undefined && b.size !== undefined && a.size !== b.size || a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || isKeyed(a) !== isKeyed(b) || isIndexed(a) !== isIndexed(b) || isOrdered(a) !== isOrdered(b) ) { return false; } if (a.size === 0 && b.size === 0) { return true; } var notAssociative = !isAssociative(a); if (isOrdered(a)) { var entries = a.entries(); return b.every(function(v, k) { var entry = entries.next().value; return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); }) && entries.next().done; } var flipped = false; if (a.size === undefined) { if (b.size === undefined) { if (typeof a.cacheResult === 'function') { a.cacheResult(); } } else { flipped = true; var _ = a; a = b; b = _; } } var allEqual = true; var bSize = b.__iterate(function(v, k) { if (notAssociative ? !a.has(v) : flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { allEqual = false; return false; } }); return allEqual && a.size === bSize; } createClass(Repeat, IndexedSeq); function Repeat(value, times) { if (!(this instanceof Repeat)) { return new Repeat(value, times); } this._value = value; this.size = times === undefined ? Infinity : Math.max(0, times); if (this.size === 0) { if (EMPTY_REPEAT) { return EMPTY_REPEAT; } EMPTY_REPEAT = this; } } Repeat.prototype.toString = function() { if (this.size === 0) { return 'Repeat []'; } return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; }; Repeat.prototype.get = function(index, notSetValue) { return this.has(index) ? this._value : notSetValue; }; Repeat.prototype.includes = function(searchValue) { return is(this._value, searchValue); }; Repeat.prototype.slice = function(begin, end) { var size = this.size; return wholeSlice(begin, end, size) ? this : new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); }; Repeat.prototype.reverse = function() { return this; }; Repeat.prototype.indexOf = function(searchValue) { if (is(this._value, searchValue)) { return 0; } return -1; }; Repeat.prototype.lastIndexOf = function(searchValue) { if (is(this._value, searchValue)) { return this.size; } return -1; }; Repeat.prototype.__iterate = function(fn, reverse) { for (var ii = 0; ii < this.size; ii++) { if (fn(this._value, ii, this) === false) { return ii + 1; } } return ii; }; Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; var ii = 0; return new Iterator(function() {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} ); }; Repeat.prototype.equals = function(other) { return other instanceof Repeat ? is(this._value, other._value) : deepEqual(other); }; var EMPTY_REPEAT; function invariant(condition, error) { if (!condition) throw new Error(error); } createClass(Range, IndexedSeq); function Range(start, end, step) { if (!(this instanceof Range)) { return new Range(start, end, step); } invariant(step !== 0, 'Cannot step a Range by 0'); start = start || 0; if (end === undefined) { end = Infinity; } step = step === undefined ? 1 : Math.abs(step); if (end < start) { step = -step; } this._start = start; this._end = end; this._step = step; this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); if (this.size === 0) { if (EMPTY_RANGE) { return EMPTY_RANGE; } EMPTY_RANGE = this; } } Range.prototype.toString = function() { if (this.size === 0) { return 'Range []'; } return 'Range [ ' + this._start + '...' + this._end + (this._step !== 1 ? ' by ' + this._step : '') + ' ]'; }; Range.prototype.get = function(index, notSetValue) { return this.has(index) ? this._start + wrapIndex(this, index) * this._step : notSetValue; }; Range.prototype.includes = function(searchValue) { var possibleIndex = (searchValue - this._start) / this._step; return possibleIndex >= 0 && possibleIndex < this.size && possibleIndex === Math.floor(possibleIndex); }; Range.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } begin = resolveBegin(begin, this.size); end = resolveEnd(end, this.size); if (end <= begin) { return new Range(0, 0); } return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); }; Range.prototype.indexOf = function(searchValue) { var offsetValue = searchValue - this._start; if (offsetValue % this._step === 0) { var index = offsetValue / this._step; if (index >= 0 && index < this.size) { return index } } return -1; }; Range.prototype.lastIndexOf = function(searchValue) { return this.indexOf(searchValue); }; Range.prototype.__iterate = function(fn, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(value, ii, this) === false) { return ii + 1; } value += reverse ? -step : step; } return ii; }; Range.prototype.__iterator = function(type, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; var ii = 0; return new Iterator(function() { var v = value; value += reverse ? -step : step; return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); }); }; Range.prototype.equals = function(other) { return other instanceof Range ? this._start === other._start && this._end === other._end && this._step === other._step : deepEqual(this, other); }; var EMPTY_RANGE; createClass(Collection, Iterable); function Collection() { throw TypeError('Abstract'); } createClass(KeyedCollection, Collection);function KeyedCollection() {} createClass(IndexedCollection, Collection);function IndexedCollection() {} createClass(SetCollection, Collection);function SetCollection() {} Collection.Keyed = KeyedCollection; Collection.Indexed = IndexedCollection; Collection.Set = SetCollection; var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? Math.imul : function imul(a, b) { a = a | 0; // int b = b | 0; // int var c = a & 0xffff; var d = b & 0xffff; // Shift by 0 fixes the sign on the high part. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int }; // v8 has an optimization for storing 31-bit signed numbers. // Values which have either 00 or 11 as the high order bits qualify. // This function drops the highest order bit in a signed number, maintaining // the sign bit. function smi(i32) { return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); } function hash(o) { if (o === false || o === null || o === undefined) { return 0; } if (typeof o.valueOf === 'function') { o = o.valueOf(); if (o === false || o === null || o === undefined) { return 0; } } if (o === true) { return 1; } var type = typeof o; if (type === 'number') { if (o !== o || o === Infinity) { return 0; } var h = o | 0; if (h !== o) { h ^= o * 0xFFFFFFFF; } while (o > 0xFFFFFFFF) { o /= 0xFFFFFFFF; h ^= o; } return smi(h); } if (type === 'string') { return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); } if (typeof o.hashCode === 'function') { return o.hashCode(); } if (type === 'object') { return hashJSObj(o); } if (typeof o.toString === 'function') { return hashString(o.toString()); } throw new Error('Value type ' + type + ' cannot be hashed.'); } function cachedHashString(string) { var hash = stringHashCache[string]; if (hash === undefined) { hash = hashString(string); if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { STRING_HASH_CACHE_SIZE = 0; stringHashCache = {}; } STRING_HASH_CACHE_SIZE++; stringHashCache[string] = hash; } return hash; } // http://jsperf.com/hashing-strings function hashString(string) { // This is the hash from JVM // The hash code for a string is computed as // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], // where s[i] is the ith character of the string and n is the length of // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 // (exclusive) by dropping high bits. var hash = 0; for (var ii = 0; ii < string.length; ii++) { hash = 31 * hash + string.charCodeAt(ii) | 0; } return smi(hash); } function hashJSObj(obj) { var hash; if (usingWeakMap) { hash = weakMap.get(obj); if (hash !== undefined) { return hash; } } hash = obj[UID_HASH_KEY]; if (hash !== undefined) { return hash; } if (!canDefineProperty) { hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; if (hash !== undefined) { return hash; } hash = getIENodeHash(obj); if (hash !== undefined) { return hash; } } hash = ++objHashUID; if (objHashUID & 0x40000000) { objHashUID = 0; } if (usingWeakMap) { weakMap.set(obj, hash); } else if (isExtensible !== undefined && isExtensible(obj) === false) { throw new Error('Non-extensible objects are not allowed as keys.'); } else if (canDefineProperty) { Object.defineProperty(obj, UID_HASH_KEY, { 'enumerable': false, 'configurable': false, 'writable': false, 'value': hash }); } else if (obj.propertyIsEnumerable !== undefined && obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { // Since we can't define a non-enumerable property on the object // we'll hijack one of the less-used non-enumerable properties to // save our hash on it. Since this is a function it will not show up in // `JSON.stringify` which is what we want. obj.propertyIsEnumerable = function() { return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); }; obj.propertyIsEnumerable[UID_HASH_KEY] = hash; } else if (obj.nodeType !== undefined) { // At this point we couldn't get the IE `uniqueID` to use as a hash // and we couldn't use a non-enumerable property to exploit the // dontEnum bug so we simply add the `UID_HASH_KEY` on the node // itself. obj[UID_HASH_KEY] = hash; } else { throw new Error('Unable to set a non-enumerable property on object.'); } return hash; } // Get references to ES5 object methods. var isExtensible = Object.isExtensible; // True if Object.defineProperty works as expected. IE8 fails this test. var canDefineProperty = (function() { try { Object.defineProperty({}, '@', {}); return true; } catch (e) { return false; } }()); // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it // and avoid memory leaks from the IE cloneNode bug. function getIENodeHash(node) { if (node && node.nodeType > 0) { switch (node.nodeType) { case 1: // Element return node.uniqueID; case 9: // Document return node.documentElement && node.documentElement.uniqueID; } } } // If possible, use a WeakMap. var usingWeakMap = typeof WeakMap === 'function'; var weakMap; if (usingWeakMap) { weakMap = new WeakMap(); } var objHashUID = 0; var UID_HASH_KEY = '__immutablehash__'; if (typeof Symbol === 'function') { UID_HASH_KEY = Symbol(UID_HASH_KEY); } var STRING_HASH_CACHE_MIN_STRLEN = 16; var STRING_HASH_CACHE_MAX_SIZE = 255; var STRING_HASH_CACHE_SIZE = 0; var stringHashCache = {}; function assertNotInfinite(size) { invariant( size !== Infinity, 'Cannot perform this action with an infinite size.' ); } createClass(Map, KeyedCollection); // @pragma Construction function Map(value) { return value === null || value === undefined ? emptyMap() : isMap(value) && !isOrdered(value) ? value : emptyMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } Map.of = function() {var keyValues = SLICE$0.call(arguments, 0); return emptyMap().withMutations(function(map ) { for (var i = 0; i < keyValues.length; i += 2) { if (i + 1 >= keyValues.length) { throw new Error('Missing value for key: ' + keyValues[i]); } map.set(keyValues[i], keyValues[i + 1]); } }); }; Map.prototype.toString = function() { return this.__toString('Map {', '}'); }; // @pragma Access Map.prototype.get = function(k, notSetValue) { return this._root ? this._root.get(0, undefined, k, notSetValue) : notSetValue; }; // @pragma Modification Map.prototype.set = function(k, v) { return updateMap(this, k, v); }; Map.prototype.setIn = function(keyPath, v) { return this.updateIn(keyPath, NOT_SET, function() {return v}); }; Map.prototype.remove = function(k) { return updateMap(this, k, NOT_SET); }; Map.prototype.deleteIn = function(keyPath) { return this.updateIn(keyPath, function() {return NOT_SET}); }; Map.prototype.update = function(k, notSetValue, updater) { return arguments.length === 1 ? k(this) : this.updateIn([k], notSetValue, updater); }; Map.prototype.updateIn = function(keyPath, notSetValue, updater) { if (!updater) { updater = notSetValue; notSetValue = undefined; } var updatedValue = updateInDeepMap( this, forceIterator(keyPath), notSetValue, updater ); return updatedValue === NOT_SET ? undefined : updatedValue; }; Map.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._root = null; this.__hash = undefined; this.__altered = true; return this; } return emptyMap(); }; // @pragma Composition Map.prototype.merge = function(/*...iters*/) { return mergeIntoMapWith(this, undefined, arguments); }; Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, merger, iters); }; Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.merge === 'function' ? m.merge.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoMapWith(this, deepMerger, arguments); }; Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, deepMergerWith(merger), iters); }; Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.mergeDeep === 'function' ? m.mergeDeep.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.sort = function(comparator) { // Late binding return OrderedMap(sortFactory(this, comparator)); }; Map.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedMap(sortFactory(this, comparator, mapper)); }; // @pragma Mutability Map.prototype.withMutations = function(fn) { var mutable = this.asMutable(); fn(mutable); return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; }; Map.prototype.asMutable = function() { return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); }; Map.prototype.asImmutable = function() { return this.__ensureOwner(); }; Map.prototype.wasAltered = function() { return this.__altered; }; Map.prototype.__iterator = function(type, reverse) { return new MapIterator(this, type, reverse); }; Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; this._root && this._root.iterate(function(entry ) { iterations++; return fn(entry[1], entry[0], this$0); }, reverse); return iterations; }; Map.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeMap(this.size, this._root, ownerID, this.__hash); }; function isMap(maybeMap) { return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); } Map.isMap = isMap; var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; var MapPrototype = Map.prototype; MapPrototype[IS_MAP_SENTINEL] = true; MapPrototype[DELETE] = MapPrototype.remove; MapPrototype.removeIn = MapPrototype.deleteIn; // #pragma Trie Nodes function ArrayMapNode(ownerID, entries) { this.ownerID = ownerID; this.entries = entries; } ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && entries.length === 1) { return; // undefined } if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { return createNodes(ownerID, entries, key, value); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new ArrayMapNode(ownerID, newEntries); }; function BitmapIndexedNode(ownerID, bitmap, nodes) { this.ownerID = ownerID; this.bitmap = bitmap; this.nodes = nodes; } BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); var bitmap = this.bitmap; return (bitmap & bit) === 0 ? notSetValue : this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); }; BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var bit = 1 << keyHashFrag; var bitmap = this.bitmap; var exists = (bitmap & bit) !== 0; if (!exists && value === NOT_SET) { return this; } var idx = popCount(bitmap & (bit - 1)); var nodes = this.nodes; var node = exists ? nodes[idx] : undefined; var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); } if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { return nodes[idx ^ 1]; } if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { return newNode; } var isEditable = ownerID && ownerID === this.ownerID; var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; var newNodes = exists ? newNode ? setIn(nodes, idx, newNode, isEditable) : spliceOut(nodes, idx, isEditable) : spliceIn(nodes, idx, newNode, isEditable); if (isEditable) { this.bitmap = newBitmap; this.nodes = newNodes; return this; } return new BitmapIndexedNode(ownerID, newBitmap, newNodes); }; function HashArrayMapNode(ownerID, count, nodes) { this.ownerID = ownerID; this.count = count; this.nodes = nodes; } HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var node = this.nodes[idx]; return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; }; HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var removed = value === NOT_SET; var nodes = this.nodes; var node = nodes[idx]; if (removed && !node) { return this; } var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } var newCount = this.count; if (!node) { newCount++; } else if (!newNode) { newCount--; if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { return packNodes(ownerID, nodes, newCount, idx); } } var isEditable = ownerID && ownerID === this.ownerID; var newNodes = setIn(nodes, idx, newNode, isEditable); if (isEditable) { this.count = newCount; this.nodes = newNodes; return this; } return new HashArrayMapNode(ownerID, newCount, newNodes); }; function HashCollisionNode(ownerID, keyHash, entries) { this.ownerID = ownerID; this.keyHash = keyHash; this.entries = entries; } HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var removed = value === NOT_SET; if (keyHash !== this.keyHash) { if (removed) { return this; } SetRef(didAlter); SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); } var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && len === 2) { return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new HashCollisionNode(ownerID, this.keyHash, newEntries); }; function ValueNode(ownerID, keyHash, entry) { this.ownerID = ownerID; this.keyHash = keyHash; this.entry = entry; } ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { return is(key, this.entry[0]) ? this.entry[1] : notSetValue; }; ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var keyMatch = is(key, this.entry[0]); if (keyMatch ? value === this.entry[1] : removed) { return this; } SetRef(didAlter); if (removed) { SetRef(didChangeSize); return; // undefined } if (keyMatch) { if (ownerID && ownerID === this.ownerID) { this.entry[1] = value; return this; } return new ValueNode(ownerID, this.keyHash, [key, value]); } SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); }; // #pragma Iterators ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function (fn, reverse) { var entries = this.entries; for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { return false; } } } BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function (fn, reverse) { var nodes = this.nodes; for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { var node = nodes[reverse ? maxIndex - ii : ii]; if (node && node.iterate(fn, reverse) === false) { return false; } } } ValueNode.prototype.iterate = function (fn, reverse) { return fn(this.entry); } createClass(MapIterator, Iterator); function MapIterator(map, type, reverse) { this._type = type; this._reverse = reverse; this._stack = map._root && mapIteratorFrame(map._root); } MapIterator.prototype.next = function() { var type = this._type; var stack = this._stack; while (stack) { var node = stack.node; var index = stack.index++; var maxIndex; if (node.entry) { if (index === 0) { return mapIteratorValue(type, node.entry); } } else if (node.entries) { maxIndex = node.entries.length - 1; if (index <= maxIndex) { return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); } } else { maxIndex = node.nodes.length - 1; if (index <= maxIndex) { var subNode = node.nodes[this._reverse ? maxIndex - index : index]; if (subNode) { if (subNode.entry) { return mapIteratorValue(type, subNode.entry); } stack = this._stack = mapIteratorFrame(subNode, stack); } continue; } } stack = this._stack = this._stack.__prev; } return iteratorDone(); }; function mapIteratorValue(type, entry) { return iteratorValue(type, entry[0], entry[1]); } function mapIteratorFrame(node, prev) { return { node: node, index: 0, __prev: prev }; } function makeMap(size, root, ownerID, hash) { var map = Object.create(MapPrototype); map.size = size; map._root = root; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_MAP; function emptyMap() { return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); } function updateMap(map, k, v) { var newRoot; var newSize; if (!map._root) { if (v === NOT_SET) { return map; } newSize = 1; newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); } else { var didChangeSize = MakeRef(CHANGE_LENGTH); var didAlter = MakeRef(DID_ALTER); newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); if (!didAlter.value) { return map; } newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); } if (map.__ownerID) { map.size = newSize; map._root = newRoot; map.__hash = undefined; map.__altered = true; return map; } return newRoot ? makeMap(newSize, newRoot) : emptyMap(); } function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (!node) { if (value === NOT_SET) { return node; } SetRef(didAlter); SetRef(didChangeSize); return new ValueNode(ownerID, keyHash, [key, value]); } return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); } function isLeafNode(node) { return node.constructor === ValueNode || node.constructor === HashCollisionNode; } function mergeIntoNode(node, ownerID, shift, keyHash, entry) { if (node.keyHash === keyHash) { return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); } var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var newNode; var nodes = idx1 === idx2 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); } function createNodes(ownerID, entries, key, value) { if (!ownerID) { ownerID = new OwnerID(); } var node = new ValueNode(ownerID, hash(key), [key, value]); for (var ii = 0; ii < entries.length; ii++) { var entry = entries[ii]; node = node.update(ownerID, 0, undefined, entry[0], entry[1]); } return node; } function packNodes(ownerID, nodes, count, excluding) { var bitmap = 0; var packedII = 0; var packedNodes = new Array(count); for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { var node = nodes[ii]; if (node !== undefined && ii !== excluding) { bitmap |= bit; packedNodes[packedII++] = node; } } return new BitmapIndexedNode(ownerID, bitmap, packedNodes); } function expandNodes(ownerID, nodes, bitmap, including, node) { var count = 0; var expandedNodes = new Array(SIZE); for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; } expandedNodes[including] = node; return new HashArrayMapNode(ownerID, count + 1, expandedNodes); } function mergeIntoMapWith(map, merger, iterables) { var iters = []; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = KeyedIterable(value); if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } return mergeIntoCollectionWith(map, merger, iters); } function deepMerger(existing, value, key) { return existing && existing.mergeDeep && isIterable(value) ? existing.mergeDeep(value) : is(existing, value) ? existing : value; } function deepMergerWith(merger) { return function(existing, value, key) { if (existing && existing.mergeDeepWith && isIterable(value)) { return existing.mergeDeepWith(merger, value); } var nextValue = merger(existing, value, key); return is(existing, nextValue) ? existing : nextValue; }; } function mergeIntoCollectionWith(collection, merger, iters) { iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return collection; } if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { return collection.constructor(iters[0]); } return collection.withMutations(function(collection ) { var mergeIntoMap = merger ? function(value, key) { collection.update(key, NOT_SET, function(existing ) {return existing === NOT_SET ? value : merger(existing, value, key)} ); } : function(value, key) { collection.set(key, value); } for (var ii = 0; ii < iters.length; ii++) { iters[ii].forEach(mergeIntoMap); } }); } function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { var isNotSet = existing === NOT_SET; var step = keyPathIter.next(); if (step.done) { var existingValue = isNotSet ? notSetValue : existing; var newValue = updater(existingValue); return newValue === existingValue ? existing : newValue; } invariant( isNotSet || (existing && existing.set), 'invalid keyPath' ); var key = step.value; var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); var nextUpdated = updateInDeepMap( nextExisting, keyPathIter, notSetValue, updater ); return nextUpdated === nextExisting ? existing : nextUpdated === NOT_SET ? existing.remove(key) : (isNotSet ? emptyMap() : existing).set(key, nextUpdated); } function popCount(x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0f0f0f0f; x = x + (x >> 8); x = x + (x >> 16); return x & 0x7f; } function setIn(array, idx, val, canEdit) { var newArray = canEdit ? array : arrCopy(array); newArray[idx] = val; return newArray; } function spliceIn(array, idx, val, canEdit) { var newLen = array.length + 1; if (canEdit && idx + 1 === newLen) { array[idx] = val; return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { newArray[ii] = val; after = -1; } else { newArray[ii] = array[ii + after]; } } return newArray; } function spliceOut(array, idx, canEdit) { var newLen = array.length - 1; if (canEdit && idx === newLen) { array.pop(); return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { after = 1; } newArray[ii] = array[ii + after]; } return newArray; } var MAX_ARRAY_MAP_SIZE = SIZE / 4; var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; createClass(List, IndexedCollection); // @pragma Construction function List(value) { var empty = emptyList(); if (value === null || value === undefined) { return empty; } if (isList(value)) { return value; } var iter = IndexedIterable(value); var size = iter.size; if (size === 0) { return empty; } assertNotInfinite(size); if (size > 0 && size < SIZE) { return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); } return empty.withMutations(function(list ) { list.setSize(size); iter.forEach(function(v, i) {return list.set(i, v)}); }); } List.of = function(/*...values*/) { return this(arguments); }; List.prototype.toString = function() { return this.__toString('List [', ']'); }; // @pragma Access List.prototype.get = function(index, notSetValue) { index = wrapIndex(this, index); if (index >= 0 && index < this.size) { index += this._origin; var node = listNodeFor(this, index); return node && node.array[index & MASK]; } return notSetValue; }; // @pragma Modification List.prototype.set = function(index, value) { return updateList(this, index, value); }; List.prototype.remove = function(index) { return !this.has(index) ? this : index === 0 ? this.shift() : index === this.size - 1 ? this.pop() : this.splice(index, 1); }; List.prototype.insert = function(index, value) { return this.splice(index, 0, value); }; List.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = this._origin = this._capacity = 0; this._level = SHIFT; this._root = this._tail = null; this.__hash = undefined; this.__altered = true; return this; } return emptyList(); }; List.prototype.push = function(/*...values*/) { var values = arguments; var oldSize = this.size; return this.withMutations(function(list ) { setListBounds(list, 0, oldSize + values.length); for (var ii = 0; ii < values.length; ii++) { list.set(oldSize + ii, values[ii]); } }); }; List.prototype.pop = function() { return setListBounds(this, 0, -1); }; List.prototype.unshift = function(/*...values*/) { var values = arguments; return this.withMutations(function(list ) { setListBounds(list, -values.length); for (var ii = 0; ii < values.length; ii++) { list.set(ii, values[ii]); } }); }; List.prototype.shift = function() { return setListBounds(this, 1); }; // @pragma Composition List.prototype.merge = function(/*...iters*/) { return mergeIntoListWith(this, undefined, arguments); }; List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, merger, iters); }; List.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoListWith(this, deepMerger, arguments); }; List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, deepMergerWith(merger), iters); }; List.prototype.setSize = function(size) { return setListBounds(this, 0, size); }; // @pragma Iteration List.prototype.slice = function(begin, end) { var size = this.size; if (wholeSlice(begin, end, size)) { return this; } return setListBounds( this, resolveBegin(begin, size), resolveEnd(end, size) ); }; List.prototype.__iterator = function(type, reverse) { var index = 0; var values = iterateList(this, reverse); return new Iterator(function() { var value = values(); return value === DONE ? iteratorDone() : iteratorValue(type, index++, value); }); }; List.prototype.__iterate = function(fn, reverse) { var index = 0; var values = iterateList(this, reverse); var value; while ((value = values()) !== DONE) { if (fn(value, index++, this) === false) { break; } } return index; }; List.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; return this; } return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); }; function isList(maybeList) { return !!(maybeList && maybeList[IS_LIST_SENTINEL]); } List.isList = isList; var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; var ListPrototype = List.prototype; ListPrototype[IS_LIST_SENTINEL] = true; ListPrototype[DELETE] = ListPrototype.remove; ListPrototype.setIn = MapPrototype.setIn; ListPrototype.deleteIn = ListPrototype.removeIn = MapPrototype.removeIn; ListPrototype.update = MapPrototype.update; ListPrototype.updateIn = MapPrototype.updateIn; ListPrototype.mergeIn = MapPrototype.mergeIn; ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; ListPrototype.withMutations = MapPrototype.withMutations; ListPrototype.asMutable = MapPrototype.asMutable; ListPrototype.asImmutable = MapPrototype.asImmutable; ListPrototype.wasAltered = MapPrototype.wasAltered; function VNode(array, ownerID) { this.array = array; this.ownerID = ownerID; } // TODO: seems like these methods are very similar VNode.prototype.removeBefore = function(ownerID, level, index) { if (index === level ? 1 << level : 0 || this.array.length === 0) { return this; } var originIndex = (index >>> level) & MASK; if (originIndex >= this.array.length) { return new VNode([], ownerID); } var removingFirst = originIndex === 0; var newChild; if (level > 0) { var oldChild = this.array[originIndex]; newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); if (newChild === oldChild && removingFirst) { return this; } } if (removingFirst && !newChild) { return this; } var editable = editableVNode(this, ownerID); if (!removingFirst) { for (var ii = 0; ii < originIndex; ii++) { editable.array[ii] = undefined; } } if (newChild) { editable.array[originIndex] = newChild; } return editable; }; VNode.prototype.removeAfter = function(ownerID, level, index) { if (index === (level ? 1 << level : 0) || this.array.length === 0) { return this; } var sizeIndex = ((index - 1) >>> level) & MASK; if (sizeIndex >= this.array.length) { return this; } var newChild; if (level > 0) { var oldChild = this.array[sizeIndex]; newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); if (newChild === oldChild && sizeIndex === this.array.length - 1) { return this; } } var editable = editableVNode(this, ownerID); editable.array.splice(sizeIndex + 1); if (newChild) { editable.array[sizeIndex] = newChild; } return editable; }; var DONE = {}; function iterateList(list, reverse) { var left = list._origin; var right = list._capacity; var tailPos = getTailOffset(right); var tail = list._tail; return iterateNodeOrLeaf(list._root, list._level, 0); function iterateNodeOrLeaf(node, level, offset) { return level === 0 ? iterateLeaf(node, offset) : iterateNode(node, level, offset); } function iterateLeaf(node, offset) { var array = offset === tailPos ? tail && tail.array : node && node.array; var from = offset > left ? 0 : left - offset; var to = right - offset; if (to > SIZE) { to = SIZE; } return function() { if (from === to) { return DONE; } var idx = reverse ? --to : from++; return array && array[idx]; }; } function iterateNode(node, level, offset) { var values; var array = node && node.array; var from = offset > left ? 0 : (left - offset) >> level; var to = ((right - offset) >> level) + 1; if (to > SIZE) { to = SIZE; } return function() { do { if (values) { var value = values(); if (value !== DONE) { return value; } values = null; } if (from === to) { return DONE; } var idx = reverse ? --to : from++; values = iterateNodeOrLeaf( array && array[idx], level - SHIFT, offset + (idx << level) ); } while (true); }; } } function makeList(origin, capacity, level, root, tail, ownerID, hash) { var list = Object.create(ListPrototype); list.size = capacity - origin; list._origin = origin; list._capacity = capacity; list._level = level; list._root = root; list._tail = tail; list.__ownerID = ownerID; list.__hash = hash; list.__altered = false; return list; } var EMPTY_LIST; function emptyList() { return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); } function updateList(list, index, value) { index = wrapIndex(list, index); if (index !== index) { return list; } if (index >= list.size || index < 0) { return list.withMutations(function(list ) { index < 0 ? setListBounds(list, index).set(0, value) : setListBounds(list, 0, index + 1).set(index, value) }); } index += list._origin; var newTail = list._tail; var newRoot = list._root; var didAlter = MakeRef(DID_ALTER); if (index >= getTailOffset(list._capacity)) { newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); } else { newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); } if (!didAlter.value) { return list; } if (list.__ownerID) { list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(list._origin, list._capacity, list._level, newRoot, newTail); } function updateVNode(node, ownerID, level, index, value, didAlter) { var idx = (index >>> level) & MASK; var nodeHas = node && idx < node.array.length; if (!nodeHas && value === undefined) { return node; } var newNode; if (level > 0) { var lowerNode = node && node.array[idx]; var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); if (newLowerNode === lowerNode) { return node; } newNode = editableVNode(node, ownerID); newNode.array[idx] = newLowerNode; return newNode; } if (nodeHas && node.array[idx] === value) { return node; } SetRef(didAlter); newNode = editableVNode(node, ownerID); if (value === undefined && idx === newNode.array.length - 1) { newNode.array.pop(); } else { newNode.array[idx] = value; } return newNode; } function editableVNode(node, ownerID) { if (ownerID && node && ownerID === node.ownerID) { return node; } return new VNode(node ? node.array.slice() : [], ownerID); } function listNodeFor(list, rawIndex) { if (rawIndex >= getTailOffset(list._capacity)) { return list._tail; } if (rawIndex < 1 << (list._level + SHIFT)) { var node = list._root; var level = list._level; while (node && level > 0) { node = node.array[(rawIndex >>> level) & MASK]; level -= SHIFT; } return node; } } function setListBounds(list, begin, end) { // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } var owner = list.__ownerID || new OwnerID(); var oldOrigin = list._origin; var oldCapacity = list._capacity; var newOrigin = oldOrigin + begin; var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; if (newOrigin === oldOrigin && newCapacity === oldCapacity) { return list; } // If it's going to end after it starts, it's empty. if (newOrigin >= newCapacity) { return list.clear(); } var newLevel = list._level; var newRoot = list._root; // New origin might need creating a higher root. var offsetShift = 0; while (newOrigin + offsetShift < 0) { newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); newLevel += SHIFT; offsetShift += 1 << newLevel; } if (offsetShift) { newOrigin += offsetShift; oldOrigin += offsetShift; newCapacity += offsetShift; oldCapacity += offsetShift; } var oldTailOffset = getTailOffset(oldCapacity); var newTailOffset = getTailOffset(newCapacity); // New size might need creating a higher root. while (newTailOffset >= 1 << (newLevel + SHIFT)) { newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); newLevel += SHIFT; } // Locate or create the new tail. var oldTail = list._tail; var newTail = newTailOffset < oldTailOffset ? listNodeFor(list, newCapacity - 1) : newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; // Merge Tail into tree. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { newRoot = editableVNode(newRoot, owner); var node = newRoot; for (var level = newLevel; level > SHIFT; level -= SHIFT) { var idx = (oldTailOffset >>> level) & MASK; node = node.array[idx] = editableVNode(node.array[idx], owner); } node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; } // If the size has been reduced, there's a chance the tail needs to be trimmed. if (newCapacity < oldCapacity) { newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); } // If the new origin is within the tail, then we do not need a root. if (newOrigin >= newTailOffset) { newOrigin -= newTailOffset; newCapacity -= newTailOffset; newLevel = SHIFT; newRoot = null; newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); // Otherwise, if the root has been trimmed, garbage collect. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { offsetShift = 0; // Identify the new top root node of the subtree of the old root. while (newRoot) { var beginIndex = (newOrigin >>> newLevel) & MASK; if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { break; } if (beginIndex) { offsetShift += (1 << newLevel) * beginIndex; } newLevel -= SHIFT; newRoot = newRoot.array[beginIndex]; } // Trim the new sides of the new root. if (newRoot && newOrigin > oldOrigin) { newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); } if (newRoot && newTailOffset < oldTailOffset) { newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); } if (offsetShift) { newOrigin -= offsetShift; newCapacity -= offsetShift; } } if (list.__ownerID) { list.size = newCapacity - newOrigin; list._origin = newOrigin; list._capacity = newCapacity; list._level = newLevel; list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); } function mergeIntoListWith(list, merger, iterables) { var iters = []; var maxSize = 0; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = IndexedIterable(value); if (iter.size > maxSize) { maxSize = iter.size; } if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } if (maxSize > list.size) { list = list.setSize(maxSize); } return mergeIntoCollectionWith(list, merger, iters); } function getTailOffset(size) { return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); } createClass(OrderedMap, Map); // @pragma Construction function OrderedMap(value) { return value === null || value === undefined ? emptyOrderedMap() : isOrderedMap(value) ? value : emptyOrderedMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } OrderedMap.of = function(/*...values*/) { return this(arguments); }; OrderedMap.prototype.toString = function() { return this.__toString('OrderedMap {', '}'); }; // @pragma Access OrderedMap.prototype.get = function(k, notSetValue) { var index = this._map.get(k); return index !== undefined ? this._list.get(index)[1] : notSetValue; }; // @pragma Modification OrderedMap.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._map.clear(); this._list.clear(); return this; } return emptyOrderedMap(); }; OrderedMap.prototype.set = function(k, v) { return updateOrderedMap(this, k, v); }; OrderedMap.prototype.remove = function(k) { return updateOrderedMap(this, k, NOT_SET); }; OrderedMap.prototype.wasAltered = function() { return this._map.wasAltered() || this._list.wasAltered(); }; OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._list.__iterate( function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, reverse ); }; OrderedMap.prototype.__iterator = function(type, reverse) { return this._list.fromEntrySeq().__iterator(type, reverse); }; OrderedMap.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); var newList = this._list.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; this._list = newList; return this; } return makeOrderedMap(newMap, newList, ownerID, this.__hash); }; function isOrderedMap(maybeOrderedMap) { return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); } OrderedMap.isOrderedMap = isOrderedMap; OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; function makeOrderedMap(map, list, ownerID, hash) { var omap = Object.create(OrderedMap.prototype); omap.size = map ? map.size : 0; omap._map = map; omap._list = list; omap.__ownerID = ownerID; omap.__hash = hash; return omap; } var EMPTY_ORDERED_MAP; function emptyOrderedMap() { return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); } function updateOrderedMap(omap, k, v) { var map = omap._map; var list = omap._list; var i = map.get(k); var has = i !== undefined; var newMap; var newList; if (v === NOT_SET) { // removed if (!has) { return omap; } if (list.size >= SIZE && list.size >= map.size * 2) { newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); if (omap.__ownerID) { newMap.__ownerID = newList.__ownerID = omap.__ownerID; } } else { newMap = map.remove(k); newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); } } else { if (has) { if (v === list.get(i)[1]) { return omap; } newMap = map; newList = list.set(i, [k, v]); } else { newMap = map.set(k, list.size); newList = list.set(list.size, [k, v]); } } if (omap.__ownerID) { omap.size = newMap.size; omap._map = newMap; omap._list = newList; omap.__hash = undefined; return omap; } return makeOrderedMap(newMap, newList); } createClass(ToKeyedSequence, KeyedSeq); function ToKeyedSequence(indexed, useKeys) { this._iter = indexed; this._useKeys = useKeys; this.size = indexed.size; } ToKeyedSequence.prototype.get = function(key, notSetValue) { return this._iter.get(key, notSetValue); }; ToKeyedSequence.prototype.has = function(key) { return this._iter.has(key); }; ToKeyedSequence.prototype.valueSeq = function() { return this._iter.valueSeq(); }; ToKeyedSequence.prototype.reverse = function() {var this$0 = this; var reversedSequence = reverseFactory(this, true); if (!this._useKeys) { reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; } return reversedSequence; }; ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; var mappedSequence = mapFactory(this, mapper, context); if (!this._useKeys) { mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; } return mappedSequence; }; ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var ii; return this._iter.__iterate( this._useKeys ? function(v, k) {return fn(v, k, this$0)} : ((ii = reverse ? resolveSize(this) : 0), function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), reverse ); }; ToKeyedSequence.prototype.__iterator = function(type, reverse) { if (this._useKeys) { return this._iter.__iterator(type, reverse); } var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var ii = reverse ? resolveSize(this) : 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, reverse ? --ii : ii++, step.value, step); }); }; ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; createClass(ToIndexedSequence, IndexedSeq); function ToIndexedSequence(iter) { this._iter = iter; this.size = iter.size; } ToIndexedSequence.prototype.includes = function(value) { return this._iter.includes(value); }; ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); }; ToIndexedSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value, step) }); }; createClass(ToSetSequence, SetSeq); function ToSetSequence(iter) { this._iter = iter; this.size = iter.size; } ToSetSequence.prototype.has = function(key) { return this._iter.includes(key); }; ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); }; ToSetSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, step.value, step.value, step); }); }; createClass(FromEntriesSequence, KeyedSeq); function FromEntriesSequence(entries) { this._iter = entries; this.size = entries.size; } FromEntriesSequence.prototype.entrySeq = function() { return this._iter.toSeq(); }; FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(entry ) { // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return fn( indexedIterable ? entry.get(1) : entry[1], indexedIterable ? entry.get(0) : entry[0], this$0 ); } }, reverse); }; FromEntriesSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return iteratorValue( type, indexedIterable ? entry.get(0) : entry[0], indexedIterable ? entry.get(1) : entry[1], step ); } } }); }; ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough; function flipFactory(iterable) { var flipSequence = makeSequence(iterable); flipSequence._iter = iterable; flipSequence.size = iterable.size; flipSequence.flip = function() {return iterable}; flipSequence.reverse = function () { var reversedSequence = iterable.reverse.apply(this); // super.reverse() reversedSequence.flip = function() {return iterable.reverse()}; return reversedSequence; }; flipSequence.has = function(key ) {return iterable.includes(key)}; flipSequence.includes = function(key ) {return iterable.has(key)}; flipSequence.cacheResult = cacheResultThrough; flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); } flipSequence.__iteratorUncached = function(type, reverse) { if (type === ITERATE_ENTRIES) { var iterator = iterable.__iterator(type, reverse); return new Iterator(function() { var step = iterator.next(); if (!step.done) { var k = step.value[0]; step.value[0] = step.value[1]; step.value[1] = k; } return step; }); } return iterable.__iterator( type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse ); } return flipSequence; } function mapFactory(iterable, mapper, context) { var mappedSequence = makeSequence(iterable); mappedSequence.size = iterable.size; mappedSequence.has = function(key ) {return iterable.has(key)}; mappedSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v === NOT_SET ? notSetValue : mapper.call(context, v, key, iterable); }; mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate( function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, reverse ); } mappedSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); return new Iterator(function() { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; return iteratorValue( type, key, mapper.call(context, entry[1], key, iterable), step ); }); } return mappedSequence; } function reverseFactory(iterable, useKeys) { var reversedSequence = makeSequence(iterable); reversedSequence._iter = iterable; reversedSequence.size = iterable.size; reversedSequence.reverse = function() {return iterable}; if (iterable.flip) { reversedSequence.flip = function () { var flipSequence = flipFactory(iterable); flipSequence.reverse = function() {return iterable.flip()}; return flipSequence; }; } reversedSequence.get = function(key, notSetValue) {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; reversedSequence.has = function(key ) {return iterable.has(useKeys ? key : -1 - key)}; reversedSequence.includes = function(value ) {return iterable.includes(value)}; reversedSequence.cacheResult = cacheResultThrough; reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); }; reversedSequence.__iterator = function(type, reverse) {return iterable.__iterator(type, !reverse)}; return reversedSequence; } function filterFactory(iterable, predicate, context, useKeys) { var filterSequence = makeSequence(iterable); if (useKeys) { filterSequence.has = function(key ) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && !!predicate.call(context, v, key, iterable); }; filterSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && predicate.call(context, v, key, iterable) ? v : notSetValue; }; } filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }, reverse); return iterations; }; filterSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterations = 0; return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; var value = entry[1]; if (predicate.call(context, value, key, iterable)) { return iteratorValue(type, useKeys ? key : iterations++, value, step); } } }); } return filterSequence; } function countByFactory(iterable, grouper, context) { var groups = Map().asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), 0, function(a ) {return a + 1} ); }); return groups.asImmutable(); } function groupByFactory(iterable, grouper, context) { var isKeyedIter = isKeyed(iterable); var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} ); }); var coerce = iterableClass(iterable); return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); } function sliceFactory(iterable, begin, end, useKeys) { var originalSize = iterable.size; // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { if (end === Infinity) { end = originalSize; } else { end = end | 0; } } if (wholeSlice(begin, end, originalSize)) { return iterable; } var resolvedBegin = resolveBegin(begin, originalSize); var resolvedEnd = resolveEnd(end, originalSize); // begin or end will be NaN if they were provided as negative numbers and // this iterable's size is unknown. In that case, cache first so there is // a known size and these do not resolve to NaN. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); } // Note: resolvedEnd is undefined when the original sequence's length is // unknown and this slice did not supply an end and should contain all // elements after resolvedBegin. // In that case, resolvedSize will be NaN and sliceSize will remain undefined. var resolvedSize = resolvedEnd - resolvedBegin; var sliceSize; if (resolvedSize === resolvedSize) { sliceSize = resolvedSize < 0 ? 0 : resolvedSize; } var sliceSeq = makeSequence(iterable); // If iterable.size is undefined, the size of the realized sliceSeq is // unknown at this point unless the number of items to slice is 0 sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; if (!useKeys && isSeq(iterable) && sliceSize >= 0) { sliceSeq.get = function (index, notSetValue) { index = wrapIndex(this, index); return index >= 0 && index < sliceSize ? iterable.get(index + resolvedBegin, notSetValue) : notSetValue; } } sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; if (sliceSize === 0) { return 0; } if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var skipped = 0; var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k) { if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0) !== false && iterations !== sliceSize; } }); return iterations; }; sliceSeq.__iteratorUncached = function(type, reverse) { if (sliceSize !== 0 && reverse) { return this.cacheResult().__iterator(type, reverse); } // Don't bother instantiating parent iterator if taking 0. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); var skipped = 0; var iterations = 0; return new Iterator(function() { while (skipped++ < resolvedBegin) { iterator.next(); } if (++iterations > sliceSize) { return iteratorDone(); } var step = iterator.next(); if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations - 1, undefined, step); } else { return iteratorValue(type, iterations - 1, step.value[1], step); } }); } return sliceSeq; } function takeWhileFactory(iterable, predicate, context) { var takeSequence = makeSequence(iterable); takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterations = 0; iterable.__iterate(function(v, k, c) {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} ); return iterations; }; takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterating = true; return new Iterator(function() { if (!iterating) { return iteratorDone(); } var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var k = entry[0]; var v = entry[1]; if (!predicate.call(context, v, k, this$0)) { iterating = false; return iteratorDone(); } return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return takeSequence; } function skipWhileFactory(iterable, predicate, context, useKeys) { var skipSequence = makeSequence(iterable); skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k, c) { if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }); return iterations; }; skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var skipping = true; var iterations = 0; return new Iterator(function() { var step, k, v; do { step = iterator.next(); if (step.done) { if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations++, undefined, step); } else { return iteratorValue(type, iterations++, step.value[1], step); } } var entry = step.value; k = entry[0]; v = entry[1]; skipping && (skipping = predicate.call(context, v, k, this$0)); } while (skipping); return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return skipSequence; } function concatFactory(iterable, values) { var isKeyedIterable = isKeyed(iterable); var iters = [iterable].concat(values).map(function(v ) { if (!isIterable(v)) { v = isKeyedIterable ? keyedSeqFromValue(v) : indexedSeqFromValue(Array.isArray(v) ? v : [v]); } else if (isKeyedIterable) { v = KeyedIterable(v); } return v; }).filter(function(v ) {return v.size !== 0}); if (iters.length === 0) { return iterable; } if (iters.length === 1) { var singleton = iters[0]; if (singleton === iterable || isKeyedIterable && isKeyed(singleton) || isIndexed(iterable) && isIndexed(singleton)) { return singleton; } } var concatSeq = new ArraySeq(iters); if (isKeyedIterable) { concatSeq = concatSeq.toKeyedSeq(); } else if (!isIndexed(iterable)) { concatSeq = concatSeq.toSetSeq(); } concatSeq = concatSeq.flatten(true); concatSeq.size = iters.reduce( function(sum, seq) { if (sum !== undefined) { var size = seq.size; if (size !== undefined) { return sum + size; } } }, 0 ); return concatSeq; } function flattenFactory(iterable, depth, useKeys) { var flatSequence = makeSequence(iterable); flatSequence.__iterateUncached = function(fn, reverse) { var iterations = 0; var stopped = false; function flatDeep(iter, currentDepth) {var this$0 = this; iter.__iterate(function(v, k) { if ((!depth || currentDepth < depth) && isIterable(v)) { flatDeep(v, currentDepth + 1); } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { stopped = true; } return !stopped; }, reverse); } flatDeep(iterable, 0); return iterations; } flatSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(type, reverse); var stack = []; var iterations = 0; return new Iterator(function() { while (iterator) { var step = iterator.next(); if (step.done !== false) { iterator = stack.pop(); continue; } var v = step.value; if (type === ITERATE_ENTRIES) { v = v[1]; } if ((!depth || stack.length < depth) && isIterable(v)) { stack.push(iterator); iterator = v.__iterator(type, reverse); } else { return useKeys ? step : iteratorValue(type, iterations++, v, step); } } return iteratorDone(); }); } return flatSequence; } function flatMapFactory(iterable, mapper, context) { var coerce = iterableClass(iterable); return iterable.toSeq().map( function(v, k) {return coerce(mapper.call(context, v, k, iterable))} ).flatten(true); } function interposeFactory(iterable, separator) { var interposedSequence = makeSequence(iterable); interposedSequence.size = iterable.size && iterable.size * 2 -1; interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k) {return (!iterations || fn(separator, iterations++, this$0) !== false) && fn(v, iterations++, this$0) !== false}, reverse ); return iterations; }; interposedSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(ITERATE_VALUES, reverse); var iterations = 0; var step; return new Iterator(function() { if (!step || iterations % 2) { step = iterator.next(); if (step.done) { return step; } } return iterations % 2 ? iteratorValue(type, iterations++, separator) : iteratorValue(type, iterations++, step.value, step); }); }; return interposedSequence; } function sortFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } var isKeyedIterable = isKeyed(iterable); var index = 0; var entries = iterable.toSeq().map( function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} ).toArray(); entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( isKeyedIterable ? function(v, i) { entries[i].length = 2; } : function(v, i) { entries[i] = v[1]; } ); return isKeyedIterable ? KeyedSeq(entries) : isIndexed(iterable) ? IndexedSeq(entries) : SetSeq(entries); } function maxFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } if (mapper) { var entry = iterable.toSeq() .map(function(v, k) {return [v, mapper(v, k, iterable)]}) .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); return entry && entry[0]; } else { return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); } } function maxCompare(comparator, a, b) { var comp = comparator(b, a); // b is considered the new max if the comparator declares them equal, but // they are not equal and b is in fact a nullish value. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; } function zipWithFactory(keyIter, zipper, iters) { var zipSequence = makeSequence(keyIter); zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); // Note: this a generic base implementation of __iterate in terms of // __iterator which may be more generically useful in the future. zipSequence.__iterate = function(fn, reverse) { /* generic: var iterator = this.__iterator(ITERATE_ENTRIES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { iterations++; if (fn(step.value[1], step.value[0], this) === false) { break; } } return iterations; */ // indexed: var iterator = this.__iterator(ITERATE_VALUES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } return iterations; }; zipSequence.__iteratorUncached = function(type, reverse) { var iterators = iters.map(function(i ) {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} ); var iterations = 0; var isDone = false; return new Iterator(function() { var steps; if (!isDone) { steps = iterators.map(function(i ) {return i.next()}); isDone = steps.some(function(s ) {return s.done}); } if (isDone) { return iteratorDone(); } return iteratorValue( type, iterations++, zipper.apply(null, steps.map(function(s ) {return s.value})) ); }); }; return zipSequence } // #pragma Helper Functions function reify(iter, seq) { return isSeq(iter) ? seq : iter.constructor(seq); } function validateEntry(entry) { if (entry !== Object(entry)) { throw new TypeError('Expected [K, V] tuple: ' + entry); } } function resolveSize(iter) { assertNotInfinite(iter.size); return ensureSize(iter); } function iterableClass(iterable) { return isKeyed(iterable) ? KeyedIterable : isIndexed(iterable) ? IndexedIterable : SetIterable; } function makeSequence(iterable) { return Object.create( ( isKeyed(iterable) ? KeyedSeq : isIndexed(iterable) ? IndexedSeq : SetSeq ).prototype ); } function cacheResultThrough() { if (this._iter.cacheResult) { this._iter.cacheResult(); this.size = this._iter.size; return this; } else { return Seq.prototype.cacheResult.call(this); } } function defaultComparator(a, b) { return a > b ? 1 : a < b ? -1 : 0; } function forceIterator(keyPath) { var iter = getIterator(keyPath); if (!iter) { // Array might not be iterable in this environment, so we need a fallback // to our wrapped type. if (!isArrayLike(keyPath)) { throw new TypeError('Expected iterable or array-like: ' + keyPath); } iter = getIterator(Iterable(keyPath)); } return iter; } createClass(Record, KeyedCollection); function Record(defaultValues, name) { var hasInitialized; var RecordType = function Record(values) { if (values instanceof RecordType) { return values; } if (!(this instanceof RecordType)) { return new RecordType(values); } if (!hasInitialized) { hasInitialized = true; var keys = Object.keys(defaultValues); setProps(RecordTypePrototype, keys); RecordTypePrototype.size = keys.length; RecordTypePrototype._name = name; RecordTypePrototype._keys = keys; RecordTypePrototype._defaultValues = defaultValues; } this._map = Map(values); }; var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); RecordTypePrototype.constructor = RecordType; return RecordType; } Record.prototype.toString = function() { return this.__toString(recordName(this) + ' {', '}'); }; // @pragma Access Record.prototype.has = function(k) { return this._defaultValues.hasOwnProperty(k); }; Record.prototype.get = function(k, notSetValue) { if (!this.has(k)) { return notSetValue; } var defaultVal = this._defaultValues[k]; return this._map ? this._map.get(k, defaultVal) : defaultVal; }; // @pragma Modification Record.prototype.clear = function() { if (this.__ownerID) { this._map && this._map.clear(); return this; } var RecordType = this.constructor; return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); }; Record.prototype.set = function(k, v) { if (!this.has(k)) { throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); } if (this._map && !this._map.has(k)) { var defaultVal = this._defaultValues[k]; if (v === defaultVal) { return this; } } var newMap = this._map && this._map.set(k, v); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.remove = function(k) { if (!this.has(k)) { return this; } var newMap = this._map && this._map.remove(k); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.wasAltered = function() { return this._map.wasAltered(); }; Record.prototype.__iterator = function(type, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); }; Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); }; Record.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map && this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return makeRecord(this, newMap, ownerID); }; var RecordPrototype = Record.prototype; RecordPrototype[DELETE] = RecordPrototype.remove; RecordPrototype.deleteIn = RecordPrototype.removeIn = MapPrototype.removeIn; RecordPrototype.merge = MapPrototype.merge; RecordPrototype.mergeWith = MapPrototype.mergeWith; RecordPrototype.mergeIn = MapPrototype.mergeIn; RecordPrototype.mergeDeep = MapPrototype.mergeDeep; RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; RecordPrototype.setIn = MapPrototype.setIn; RecordPrototype.update = MapPrototype.update; RecordPrototype.updateIn = MapPrototype.updateIn; RecordPrototype.withMutations = MapPrototype.withMutations; RecordPrototype.asMutable = MapPrototype.asMutable; RecordPrototype.asImmutable = MapPrototype.asImmutable; function makeRecord(likeRecord, map, ownerID) { var record = Object.create(Object.getPrototypeOf(likeRecord)); record._map = map; record.__ownerID = ownerID; return record; } function recordName(record) { return record._name || record.constructor.name || 'Record'; } function setProps(prototype, names) { try { names.forEach(setProp.bind(undefined, prototype)); } catch (error) { // Object.defineProperty failed. Probably IE8. } } function setProp(prototype, name) { Object.defineProperty(prototype, name, { get: function() { return this.get(name); }, set: function(value) { invariant(this.__ownerID, 'Cannot set on an immutable record.'); this.set(name, value); } }); } createClass(Set, SetCollection); // @pragma Construction function Set(value) { return value === null || value === undefined ? emptySet() : isSet(value) && !isOrdered(value) ? value : emptySet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } Set.of = function(/*...values*/) { return this(arguments); }; Set.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; Set.prototype.toString = function() { return this.__toString('Set {', '}'); }; // @pragma Access Set.prototype.has = function(value) { return this._map.has(value); }; // @pragma Modification Set.prototype.add = function(value) { return updateSet(this, this._map.set(value, true)); }; Set.prototype.remove = function(value) { return updateSet(this, this._map.remove(value)); }; Set.prototype.clear = function() { return updateSet(this, this._map.clear()); }; // @pragma Composition Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return this; } if (this.size === 0 && !this.__ownerID && iters.length === 1) { return this.constructor(iters[0]); } return this.withMutations(function(set ) { for (var ii = 0; ii < iters.length; ii++) { SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); } }); }; Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (!iters.every(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (iters.some(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.merge = function() { return this.union.apply(this, arguments); }; Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return this.union.apply(this, iters); }; Set.prototype.sort = function(comparator) { // Late binding return OrderedSet(sortFactory(this, comparator)); }; Set.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedSet(sortFactory(this, comparator, mapper)); }; Set.prototype.wasAltered = function() { return this._map.wasAltered(); }; Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); }; Set.prototype.__iterator = function(type, reverse) { return this._map.map(function(_, k) {return k}).__iterator(type, reverse); }; Set.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return this.__make(newMap, ownerID); }; function isSet(maybeSet) { return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); } Set.isSet = isSet; var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; var SetPrototype = Set.prototype; SetPrototype[IS_SET_SENTINEL] = true; SetPrototype[DELETE] = SetPrototype.remove; SetPrototype.mergeDeep = SetPrototype.merge; SetPrototype.mergeDeepWith = SetPrototype.mergeWith; SetPrototype.withMutations = MapPrototype.withMutations; SetPrototype.asMutable = MapPrototype.asMutable; SetPrototype.asImmutable = MapPrototype.asImmutable; SetPrototype.__empty = emptySet; SetPrototype.__make = makeSet; function updateSet(set, newMap) { if (set.__ownerID) { set.size = newMap.size; set._map = newMap; return set; } return newMap === set._map ? set : newMap.size === 0 ? set.__empty() : set.__make(newMap); } function makeSet(map, ownerID) { var set = Object.create(SetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_SET; function emptySet() { return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); } createClass(OrderedSet, Set); // @pragma Construction function OrderedSet(value) { return value === null || value === undefined ? emptyOrderedSet() : isOrderedSet(value) ? value : emptyOrderedSet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } OrderedSet.of = function(/*...values*/) { return this(arguments); }; OrderedSet.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; OrderedSet.prototype.toString = function() { return this.__toString('OrderedSet {', '}'); }; function isOrderedSet(maybeOrderedSet) { return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); } OrderedSet.isOrderedSet = isOrderedSet; var OrderedSetPrototype = OrderedSet.prototype; OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; OrderedSetPrototype.__empty = emptyOrderedSet; OrderedSetPrototype.__make = makeOrderedSet; function makeOrderedSet(map, ownerID) { var set = Object.create(OrderedSetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_ORDERED_SET; function emptyOrderedSet() { return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); } createClass(Stack, IndexedCollection); // @pragma Construction function Stack(value) { return value === null || value === undefined ? emptyStack() : isStack(value) ? value : emptyStack().unshiftAll(value); } Stack.of = function(/*...values*/) { return this(arguments); }; Stack.prototype.toString = function() { return this.__toString('Stack [', ']'); }; // @pragma Access Stack.prototype.get = function(index, notSetValue) { var head = this._head; index = wrapIndex(this, index); while (head && index--) { head = head.next; } return head ? head.value : notSetValue; }; Stack.prototype.peek = function() { return this._head && this._head.value; }; // @pragma Modification Stack.prototype.push = function(/*...values*/) { if (arguments.length === 0) { return this; } var newSize = this.size + arguments.length; var head = this._head; for (var ii = arguments.length - 1; ii >= 0; ii--) { head = { value: arguments[ii], next: head }; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pushAll = function(iter) { iter = IndexedIterable(iter); if (iter.size === 0) { return this; } assertNotInfinite(iter.size); var newSize = this.size; var head = this._head; iter.reverse().forEach(function(value ) { newSize++; head = { value: value, next: head }; }); if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pop = function() { return this.slice(1); }; Stack.prototype.unshift = function(/*...values*/) { return this.push.apply(this, arguments); }; Stack.prototype.unshiftAll = function(iter) { return this.pushAll(iter); }; Stack.prototype.shift = function() { return this.pop.apply(this, arguments); }; Stack.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._head = undefined; this.__hash = undefined; this.__altered = true; return this; } return emptyStack(); }; Stack.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } var resolvedBegin = resolveBegin(begin, this.size); var resolvedEnd = resolveEnd(end, this.size); if (resolvedEnd !== this.size) { // super.slice(begin, end); return IndexedCollection.prototype.slice.call(this, begin, end); } var newSize = this.size - resolvedBegin; var head = this._head; while (resolvedBegin--) { head = head.next; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; // @pragma Mutability Stack.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeStack(this.size, this._head, ownerID, this.__hash); }; // @pragma Iteration Stack.prototype.__iterate = function(fn, reverse) { if (reverse) { return this.reverse().__iterate(fn); } var iterations = 0; var node = this._head; while (node) { if (fn(node.value, iterations++, this) === false) { break; } node = node.next; } return iterations; }; Stack.prototype.__iterator = function(type, reverse) { if (reverse) { return this.reverse().__iterator(type); } var iterations = 0; var node = this._head; return new Iterator(function() { if (node) { var value = node.value; node = node.next; return iteratorValue(type, iterations++, value); } return iteratorDone(); }); }; function isStack(maybeStack) { return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); } Stack.isStack = isStack; var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; var StackPrototype = Stack.prototype; StackPrototype[IS_STACK_SENTINEL] = true; StackPrototype.withMutations = MapPrototype.withMutations; StackPrototype.asMutable = MapPrototype.asMutable; StackPrototype.asImmutable = MapPrototype.asImmutable; StackPrototype.wasAltered = MapPrototype.wasAltered; function makeStack(size, head, ownerID, hash) { var map = Object.create(StackPrototype); map.size = size; map._head = head; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_STACK; function emptyStack() { return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); } /** * Contributes additional methods to a constructor */ function mixin(ctor, methods) { var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; Object.keys(methods).forEach(keyCopier); Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(methods).forEach(keyCopier); return ctor; } Iterable.Iterator = Iterator; mixin(Iterable, { // ### Conversion to other types toArray: function() { assertNotInfinite(this.size); var array = new Array(this.size || 0); this.valueSeq().__iterate(function(v, i) { array[i] = v; }); return array; }, toIndexedSeq: function() { return new ToIndexedSequence(this); }, toJS: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} ).__toJS(); }, toJSON: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} ).__toJS(); }, toKeyedSeq: function() { return new ToKeyedSequence(this, true); }, toMap: function() { // Use Late Binding here to solve the circular dependency. return Map(this.toKeyedSeq()); }, toObject: function() { assertNotInfinite(this.size); var object = {}; this.__iterate(function(v, k) { object[k] = v; }); return object; }, toOrderedMap: function() { // Use Late Binding here to solve the circular dependency. return OrderedMap(this.toKeyedSeq()); }, toOrderedSet: function() { // Use Late Binding here to solve the circular dependency. return OrderedSet(isKeyed(this) ? this.valueSeq() : this); }, toSet: function() { // Use Late Binding here to solve the circular dependency. return Set(isKeyed(this) ? this.valueSeq() : this); }, toSetSeq: function() { return new ToSetSequence(this); }, toSeq: function() { return isIndexed(this) ? this.toIndexedSeq() : isKeyed(this) ? this.toKeyedSeq() : this.toSetSeq(); }, toStack: function() { // Use Late Binding here to solve the circular dependency. return Stack(isKeyed(this) ? this.valueSeq() : this); }, toList: function() { // Use Late Binding here to solve the circular dependency. return List(isKeyed(this) ? this.valueSeq() : this); }, // ### Common JavaScript methods and properties toString: function() { return '[Iterable]'; }, __toString: function(head, tail) { if (this.size === 0) { return head + tail; } return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; }, // ### ES6 Collection methods (ES6 Array and Map) concat: function() {var values = SLICE$0.call(arguments, 0); return reify(this, concatFactory(this, values)); }, includes: function(searchValue) { return this.some(function(value ) {return is(value, searchValue)}); }, entries: function() { return this.__iterator(ITERATE_ENTRIES); }, every: function(predicate, context) { assertNotInfinite(this.size); var returnValue = true; this.__iterate(function(v, k, c) { if (!predicate.call(context, v, k, c)) { returnValue = false; return false; } }); return returnValue; }, filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, true)); }, find: function(predicate, context, notSetValue) { var entry = this.findEntry(predicate, context); return entry ? entry[1] : notSetValue; }, forEach: function(sideEffect, context) { assertNotInfinite(this.size); return this.__iterate(context ? sideEffect.bind(context) : sideEffect); }, join: function(separator) { assertNotInfinite(this.size); separator = separator !== undefined ? '' + separator : ','; var joined = ''; var isFirst = true; this.__iterate(function(v ) { isFirst ? (isFirst = false) : (joined += separator); joined += v !== null && v !== undefined ? v.toString() : ''; }); return joined; }, keys: function() { return this.__iterator(ITERATE_KEYS); }, map: function(mapper, context) { return reify(this, mapFactory(this, mapper, context)); }, reduce: function(reducer, initialReduction, context) { assertNotInfinite(this.size); var reduction; var useFirst; if (arguments.length < 2) { useFirst = true; } else { reduction = initialReduction; } this.__iterate(function(v, k, c) { if (useFirst) { useFirst = false; reduction = v; } else { reduction = reducer.call(context, reduction, v, k, c); } }); return reduction; }, reduceRight: function(reducer, initialReduction, context) { var reversed = this.toKeyedSeq().reverse(); return reversed.reduce.apply(reversed, arguments); }, reverse: function() { return reify(this, reverseFactory(this, true)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, true)); }, some: function(predicate, context) { return !this.every(not(predicate), context); }, sort: function(comparator) { return reify(this, sortFactory(this, comparator)); }, values: function() { return this.__iterator(ITERATE_VALUES); }, // ### More sequential methods butLast: function() { return this.slice(0, -1); }, isEmpty: function() { return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); }, count: function(predicate, context) { return ensureSize( predicate ? this.toSeq().filter(predicate, context) : this ); }, countBy: function(grouper, context) { return countByFactory(this, grouper, context); }, equals: function(other) { return deepEqual(this, other); }, entrySeq: function() { var iterable = this; if (iterable._cache) { // We cache as an entries array, so we can just return the cache! return new ArraySeq(iterable._cache); } var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; return entriesSequence; }, filterNot: function(predicate, context) { return this.filter(not(predicate), context); }, findEntry: function(predicate, context, notSetValue) { var found = notSetValue; this.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { found = [k, v]; return false; } }); return found; }, findKey: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry && entry[0]; }, findLast: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); }, findLastEntry: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue); }, findLastKey: function(predicate, context) { return this.toKeyedSeq().reverse().findKey(predicate, context); }, first: function() { return this.find(returnTrue); }, flatMap: function(mapper, context) { return reify(this, flatMapFactory(this, mapper, context)); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, true)); }, fromEntrySeq: function() { return new FromEntriesSequence(this); }, get: function(searchKey, notSetValue) { return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); }, getIn: function(searchKeyPath, notSetValue) { var nested = this; // Note: in an ES6 environment, we would prefer: // for (var key of searchKeyPath) { var iter = forceIterator(searchKeyPath); var step; while (!(step = iter.next()).done) { var key = step.value; nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; if (nested === NOT_SET) { return notSetValue; } } return nested; }, groupBy: function(grouper, context) { return groupByFactory(this, grouper, context); }, has: function(searchKey) { return this.get(searchKey, NOT_SET) !== NOT_SET; }, hasIn: function(searchKeyPath) { return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; }, isSubset: function(iter) { iter = typeof iter.includes === 'function' ? iter : Iterable(iter); return this.every(function(value ) {return iter.includes(value)}); }, isSuperset: function(iter) { iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); return iter.isSubset(this); }, keyOf: function(searchValue) { return this.findKey(function(value ) {return is(value, searchValue)}); }, keySeq: function() { return this.toSeq().map(keyMapper).toIndexedSeq(); }, last: function() { return this.toSeq().reverse().first(); }, lastKeyOf: function(searchValue) { return this.toKeyedSeq().reverse().keyOf(searchValue); }, max: function(comparator) { return maxFactory(this, comparator); }, maxBy: function(mapper, comparator) { return maxFactory(this, comparator, mapper); }, min: function(comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); }, minBy: function(mapper, comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); }, rest: function() { return this.slice(1); }, skip: function(amount) { return this.slice(Math.max(0, amount)); }, skipLast: function(amount) { return reify(this, this.toSeq().reverse().skip(amount).reverse()); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, true)); }, skipUntil: function(predicate, context) { return this.skipWhile(not(predicate), context); }, sortBy: function(mapper, comparator) { return reify(this, sortFactory(this, comparator, mapper)); }, take: function(amount) { return this.slice(0, Math.max(0, amount)); }, takeLast: function(amount) { return reify(this, this.toSeq().reverse().take(amount).reverse()); }, takeWhile: function(predicate, context) { return reify(this, takeWhileFactory(this, predicate, context)); }, takeUntil: function(predicate, context) { return this.takeWhile(not(predicate), context); }, valueSeq: function() { return this.toIndexedSeq(); }, // ### Hashable Object hashCode: function() { return this.__hash || (this.__hash = hashIterable(this)); } // ### Internal // abstract __iterate(fn, reverse) // abstract __iterator(type, reverse) }); // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; var IterablePrototype = Iterable.prototype; IterablePrototype[IS_ITERABLE_SENTINEL] = true; IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; IterablePrototype.__toJS = IterablePrototype.toArray; IterablePrototype.__toStringMapper = quoteString; IterablePrototype.inspect = IterablePrototype.toSource = function() { return this.toString(); }; IterablePrototype.chain = IterablePrototype.flatMap; IterablePrototype.contains = IterablePrototype.includes; mixin(KeyedIterable, { // ### More sequential methods flip: function() { return reify(this, flipFactory(this)); }, mapEntries: function(mapper, context) {var this$0 = this; var iterations = 0; return reify(this, this.toSeq().map( function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} ).fromEntrySeq() ); }, mapKeys: function(mapper, context) {var this$0 = this; return reify(this, this.toSeq().flip().map( function(k, v) {return mapper.call(context, k, v, this$0)} ).flip() ); } }); var KeyedIterablePrototype = KeyedIterable.prototype; KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; KeyedIterablePrototype.__toJS = IterablePrototype.toObject; KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; mixin(IndexedIterable, { // ### Conversion to other types toKeyedSeq: function() { return new ToKeyedSequence(this, false); }, // ### ES6 Collection methods (ES6 Array and Map) filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, false)); }, findIndex: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry ? entry[0] : -1; }, indexOf: function(searchValue) { var key = this.keyOf(searchValue); return key === undefined ? -1 : key; }, lastIndexOf: function(searchValue) { var key = this.lastKeyOf(searchValue); return key === undefined ? -1 : key; }, reverse: function() { return reify(this, reverseFactory(this, false)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, false)); }, splice: function(index, removeNum /*, ...values*/) { var numArgs = arguments.length; removeNum = Math.max(removeNum | 0, 0); if (numArgs === 0 || (numArgs === 2 && !removeNum)) { return this; } // If index is negative, it should resolve relative to the size of the // collection. However size may be expensive to compute if not cached, so // only call count() if the number is in fact negative. index = resolveBegin(index, index < 0 ? this.count() : this.size); var spliced = this.slice(0, index); return reify( this, numArgs === 1 ? spliced : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) ); }, // ### More collection methods findLastIndex: function(predicate, context) { var entry = this.findLastEntry(predicate, context); return entry ? entry[0] : -1; }, first: function() { return this.get(0); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, false)); }, get: function(index, notSetValue) { index = wrapIndex(this, index); return (index < 0 || (this.size === Infinity || (this.size !== undefined && index > this.size))) ? notSetValue : this.find(function(_, key) {return key === index}, undefined, notSetValue); }, has: function(index) { index = wrapIndex(this, index); return index >= 0 && (this.size !== undefined ? this.size === Infinity || index < this.size : this.indexOf(index) !== -1 ); }, interpose: function(separator) { return reify(this, interposeFactory(this, separator)); }, interleave: function(/*...iterables*/) { var iterables = [this].concat(arrCopy(arguments)); var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); var interleaved = zipped.flatten(true); if (zipped.size) { interleaved.size = zipped.size * iterables.length; } return reify(this, interleaved); }, keySeq: function() { return Range(0, this.size); }, last: function() { return this.get(-1); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, false)); }, zip: function(/*, ...iterables */) { var iterables = [this].concat(arrCopy(arguments)); return reify(this, zipWithFactory(this, defaultZipper, iterables)); }, zipWith: function(zipper/*, ...iterables */) { var iterables = arrCopy(arguments); iterables[0] = this; return reify(this, zipWithFactory(this, zipper, iterables)); } }); IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; mixin(SetIterable, { // ### ES6 Collection methods (ES6 Array and Map) get: function(value, notSetValue) { return this.has(value) ? value : notSetValue; }, includes: function(value) { return this.has(value); }, // ### More sequential methods keySeq: function() { return this.valueSeq(); } }); SetIterable.prototype.has = IterablePrototype.includes; SetIterable.prototype.contains = SetIterable.prototype.includes; // Mixin subclasses mixin(KeyedSeq, KeyedIterable.prototype); mixin(IndexedSeq, IndexedIterable.prototype); mixin(SetSeq, SetIterable.prototype); mixin(KeyedCollection, KeyedIterable.prototype); mixin(IndexedCollection, IndexedIterable.prototype); mixin(SetCollection, SetIterable.prototype); // #pragma Helper functions function keyMapper(v, k) { return k; } function entryMapper(v, k) { return [k, v]; } function not(predicate) { return function() { return !predicate.apply(this, arguments); } } function neg(predicate) { return function() { return -predicate.apply(this, arguments); } } function quoteString(value) { return typeof value === 'string' ? JSON.stringify(value) : String(value); } function defaultZipper() { return arrCopy(arguments); } function defaultNegComparator(a, b) { return a < b ? 1 : a > b ? -1 : 0; } function hashIterable(iterable) { if (iterable.size === Infinity) { return 0; } var ordered = isOrdered(iterable); var keyed = isKeyed(iterable); var h = ordered ? 1 : 0; var size = iterable.__iterate( keyed ? ordered ? function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : ordered ? function(v ) { h = 31 * h + hash(v) | 0; } : function(v ) { h = h + hash(v) | 0; } ); return murmurHashOfSize(size, h); } function murmurHashOfSize(size, h) { h = imul(h, 0xCC9E2D51); h = imul(h << 15 | h >>> -15, 0x1B873593); h = imul(h << 13 | h >>> -13, 5); h = (h + 0xE6546B64 | 0) ^ size; h = imul(h ^ h >>> 16, 0x85EBCA6B); h = imul(h ^ h >>> 13, 0xC2B2AE35); h = smi(h ^ h >>> 16); return h; } function hashMerge(a, b) { return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int } var Immutable = { Iterable: Iterable, Seq: Seq, Collection: Collection, Map: Map, OrderedMap: OrderedMap, List: List, Stack: Stack, Set: Set, OrderedSet: OrderedSet, Record: Record, Range: Range, Repeat: Repeat, is: is, fromJS: fromJS }; return Immutable; })); /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* 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 ListCache = __webpack_require__(20), stackClear = __webpack_require__(270), stackDelete = __webpack_require__(271), stackGet = __webpack_require__(272), stackHas = __webpack_require__(273), stackSet = __webpack_require__(274); /** * 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; /***/ }, /* 74 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(221), isArguments = __webpack_require__(47), isArray = __webpack_require__(3), isBuffer = __webpack_require__(90), isIndex = __webpack_require__(43), isTypedArray = __webpack_require__(92); /** 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; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arrayIncludes = __webpack_require__(39), arrayIncludesWith = __webpack_require__(40), arrayMap = __webpack_require__(22), baseUnary = __webpack_require__(42), cacheHas = __webpack_require__(24); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } module.exports = baseDifference; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(195), isFlattenable = __webpack_require__(245); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(81), toKey = __webpack_require__(27); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(208), isObject = __webpack_require__(8), isObjectLike = __webpack_require__(9); /** * 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 {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arrayIncludes = __webpack_require__(39), arrayIncludesWith = __webpack_require__(40), cacheHas = __webpack_require__(24), createSet = __webpack_require__(231), setToArray = __webpack_require__(45); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseUniq; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(3), isKey = __webpack_require__(44), stringToPath = __webpack_require__(276), toString = __webpack_require__(287); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arraySome = __webpack_require__(196), cacheHas = __webpack_require__(24); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_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 & COMPARE_UNORDERED_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, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }, /* 84 */ /***/ 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; /***/ }, /* 85 */ /***/ 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; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }, /* 87 */ /***/ function(module, exports) { /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; /***/ }, /* 88 */ /***/ 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; /***/ }, /* 89 */ /***/ 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; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(4), stubFalse = __webpack_require__(286); /** 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__(55)(module))) /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isObject = __webpack_require__(8); /** `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; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(212), baseUnary = __webpack_require__(42), nodeUtil = __webpack_require__(263); /* 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; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(38); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }, /* 94 */ /***/ function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(76), baseRest = __webpack_require__(11), isArrayLikeObject = __webpack_require__(28); /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); module.exports = without; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _contextMenu = __webpack_require__(292); Object.defineProperty(exports, "ContextMenu", { enumerable: true, get: function get() { return _interopRequireDefault(_contextMenu).default; } }); var _contextmenuLayer = __webpack_require__(294); Object.defineProperty(exports, "ContextMenuLayer", { enumerable: true, get: function get() { return _interopRequireDefault(_contextmenuLayer).default; } }); var _menuItem = __webpack_require__(295); Object.defineProperty(exports, "MenuItem", { enumerable: true, get: function get() { return _interopRequireDefault(_menuItem).default; } }); var _monitor = __webpack_require__(51); Object.defineProperty(exports, "monitor", { enumerable: true, get: function get() { return _interopRequireDefault(_monitor).default; } }); var _submenu = __webpack_require__(297); Object.defineProperty(exports, "SubMenu", { enumerable: true, get: function get() { return _interopRequireDefault(_submenu).default; } }); var _connect = __webpack_require__(291); Object.defineProperty(exports, "connect", { enumerable: true, get: function get() { return _interopRequireDefault(_connect).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }, /* 97 */ 32, /* 98 */ /***/ function(module, exports) { 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashMemoize = __webpack_require__(93); var _lodashMemoize2 = _interopRequireDefault(_lodashMemoize); var isFirefox = _lodashMemoize2['default'](function () { return (/firefox/i.test(navigator.userAgent) ); }); exports.isFirefox = isFirefox; var isSafari = _lodashMemoize2['default'](function () { return Boolean(window.safari); }); exports.isSafari = isSafari; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = areOptionsEqual; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsShallowEqual = __webpack_require__(53); var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual); function areOptionsEqual(nextOptions, currentOptions) { if (currentOptions === nextOptions) { return true; } return currentOptions !== null && nextOptions !== null && _utilsShallowEqual2['default'](currentOptions, nextOptions); } module.exports = exports['default']; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _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; }; })(); exports['default'] = decorateHandler; 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 _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 _react2 = _interopRequireDefault(_react); var _disposables = __webpack_require__(159); var _utilsShallowEqual = __webpack_require__(53); var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual); var _utilsShallowEqualScalar = __webpack_require__(103); var _utilsShallowEqualScalar2 = _interopRequireDefault(_utilsShallowEqualScalar); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); function decorateHandler(_ref) { var DecoratedComponent = _ref.DecoratedComponent; var createHandler = _ref.createHandler; var createMonitor = _ref.createMonitor; var createConnector = _ref.createConnector; var registerHandler = _ref.registerHandler; var containerDisplayName = _ref.containerDisplayName; var getType = _ref.getType; var collect = _ref.collect; var options = _ref.options; var _options$arePropsEqual = options.arePropsEqual; var arePropsEqual = _options$arePropsEqual === undefined ? _utilsShallowEqualScalar2['default'] : _options$arePropsEqual; var displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'; return (function (_Component) { _inherits(DragDropContainer, _Component); DragDropContainer.prototype.getHandlerId = function getHandlerId() { return this.handlerId; }; DragDropContainer.prototype.getDecoratedComponentInstance = function getDecoratedComponentInstance() { return this.decoratedComponentInstance; }; DragDropContainer.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { return !arePropsEqual(nextProps, this.props) || !_utilsShallowEqual2['default'](nextState, this.state); }; _createClass(DragDropContainer, null, [{ key: 'DecoratedComponent', value: DecoratedComponent, enumerable: true }, { key: 'displayName', value: containerDisplayName + '(' + displayName + ')', enumerable: true }, { key: 'contextTypes', value: { dragDropManager: _react.PropTypes.object.isRequired }, enumerable: true }]); function DragDropContainer(props, context) { _classCallCheck(this, DragDropContainer); _Component.call(this, props, context); this.handleChange = this.handleChange.bind(this); this.handleChildRef = this.handleChildRef.bind(this); _invariant2['default'](typeof this.context.dragDropManager === 'object', 'Could not find the drag and drop manager in the context of %s. ' + 'Make sure to wrap the top-level component of your app with DragDropContext. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context', displayName, displayName); this.manager = this.context.dragDropManager; this.handlerMonitor = createMonitor(this.manager); this.handlerConnector = createConnector(this.manager.getBackend()); this.handler = createHandler(this.handlerMonitor); this.disposable = new _disposables.SerialDisposable(); this.receiveProps(props); this.state = this.getCurrentState(); this.dispose(); } DragDropContainer.prototype.componentDidMount = function componentDidMount() { this.isCurrentlyMounted = true; this.disposable = new _disposables.SerialDisposable(); this.currentType = null; this.receiveProps(this.props); this.handleChange(); }; DragDropContainer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (!arePropsEqual(nextProps, this.props)) { this.receiveProps(nextProps); this.handleChange(); } }; DragDropContainer.prototype.componentWillUnmount = function componentWillUnmount() { this.dispose(); this.isCurrentlyMounted = false; }; DragDropContainer.prototype.receiveProps = function receiveProps(props) { this.handler.receiveProps(props); this.receiveType(getType(props)); }; DragDropContainer.prototype.receiveType = function receiveType(type) { if (type === this.currentType) { return; } this.currentType = type; var _registerHandler = registerHandler(type, this.handler, this.manager); var handlerId = _registerHandler.handlerId; var unregister = _registerHandler.unregister; this.handlerId = handlerId; this.handlerMonitor.receiveHandlerId(handlerId); this.handlerConnector.receiveHandlerId(handlerId); var globalMonitor = this.manager.getMonitor(); var unsubscribe = globalMonitor.subscribeToStateChange(this.handleChange, { handlerIds: [handlerId] }); this.disposable.setDisposable(new _disposables.CompositeDisposable(new _disposables.Disposable(unsubscribe), new _disposables.Disposable(unregister))); }; DragDropContainer.prototype.handleChange = function handleChange() { if (!this.isCurrentlyMounted) { return; } var nextState = this.getCurrentState(); if (!_utilsShallowEqual2['default'](nextState, this.state)) { this.setState(nextState); } }; DragDropContainer.prototype.dispose = function dispose() { this.disposable.dispose(); this.handlerConnector.receiveHandlerId(null); }; DragDropContainer.prototype.handleChildRef = function handleChildRef(component) { this.decoratedComponentInstance = component; this.handler.receiveComponent(component); }; DragDropContainer.prototype.getCurrentState = function getCurrentState() { var nextState = collect(this.handlerConnector.hooks, this.handlerMonitor); if (false) { _invariant2['default'](_lodashIsPlainObject2['default'](nextState), 'Expected `collect` specified as the second argument to ' + '%s for %s to return a plain object of props to inject. ' + 'Instead, received %s.', containerDisplayName, displayName, nextState); } return nextState; }; DragDropContainer.prototype.render = function render() { return _react2['default'].createElement(DecoratedComponent, _extends({}, this.props, this.state, { ref: this.handleChildRef })); }; return DragDropContainer; })(_react.Component); } module.exports = exports['default']; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = isValidType; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); function isValidType(type, allowArray) { return typeof type === 'string' || typeof type === 'symbol' || allowArray && _lodashIsArray2['default'](type) && type.every(function (t) { return isValidType(t, false); }); } module.exports = exports['default']; /***/ }, /* 103 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = shallowEqualScalar; function shallowEqualScalar(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 hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i])) { return false; } var valA = objA[keysA[i]]; var valB = objB[keysA[i]]; if (valA !== valB || typeof valA === 'object' || typeof valB === 'object') { return false; } } return true; } module.exports = exports['default']; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = wrapConnectorHooks; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsCloneWithRef = __webpack_require__(319); var _utilsCloneWithRef2 = _interopRequireDefault(_utilsCloneWithRef); var _react = __webpack_require__(1); function throwIfCompositeComponentElement(element) { // Custom components can no longer be wrapped directly in React DnD 2.0 // so that we don't need to depend on findDOMNode() from react-dom. if (typeof element.type === 'string') { return; } var displayName = element.type.displayName || element.type.name || 'the component'; throw new Error('Only native element nodes can now be passed to React DnD connectors. ' + ('You can either wrap ' + displayName + ' into a <div>, or turn it into a ') + 'drag source or a drop target itself.'); } function wrapHookToRecognizeElement(hook) { return function () { var elementOrNode = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0]; var options = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; // When passed a node, call the hook straight away. if (!_react.isValidElement(elementOrNode)) { var node = elementOrNode; hook(node, options); return; } // If passed a ReactElement, clone it and attach this function as a ref. // This helps us achieve a neat API where user doesn't even know that refs // are being used under the hood. var element = elementOrNode; throwIfCompositeComponentElement(element); // When no options are passed, use the hook directly var ref = options ? function (node) { return hook(node, options); } : hook; return _utilsCloneWithRef2['default'](element, ref); }; } function wrapConnectorHooks(hooks) { var wrappedHooks = {}; Object.keys(hooks).forEach(function (key) { var hook = hooks[key]; var wrappedHook = wrapHookToRecognizeElement(hook); wrappedHooks[key] = function () { return wrappedHook; }; }); return wrappedHooks; } module.exports = exports['default']; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getContainer; var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getContainer(container, defaultContainer) { container = typeof container === 'function' ? container() : container; return _reactDom2.default.findDOMNode(container) || defaultContainer; } module.exports = exports['default']; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (componentOrElement) { return (0, _ownerDocument2.default)(_reactDom2.default.findDOMNode(componentOrElement)); }; var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _ownerDocument = __webpack_require__(36); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(108); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement. You can usually obtain a ReactComponent or DOMElement ' + 'from a ReactElement by attaching a ref to it.'); } if ((propType !== 'object' || typeof propValue.render !== 'function') && propValue.nodeType !== 1) { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement.'); } return null; } exports.default = (0, _createChainableTypeChecker2.default)(validate); /***/ }, /* 108 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.default = createChainableTypeChecker; /** * Copyright 2013-present, 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. */ // Mostly taken from ReactPropTypes. function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] == null) { if (isRequired) { return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.')); } return null; } for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) { args[_key - 6] = arguments[_key]; } return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args)); } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _stripDiacritics = __webpack_require__(111); var _stripDiacritics2 = _interopRequireDefault(_stripDiacritics); function filterOptions(options, filterValue, excludeOptions, props) { var _this = this; if (props.ignoreAccents) { filterValue = (0, _stripDiacritics2['default'])(filterValue); } if (props.ignoreCase) { filterValue = filterValue.toLowerCase(); } if (excludeOptions) excludeOptions = excludeOptions.map(function (i) { return i[props.valueKey]; }); return options.filter(function (option) { if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false; if (props.filterOption) return props.filterOption.call(_this, option, filterValue); if (!filterValue) return true; var valueTest = String(option[props.valueKey]); var labelTest = String(option[props.labelKey]); if (props.ignoreAccents) { if (props.matchProp !== 'label') valueTest = (0, _stripDiacritics2['default'])(valueTest); if (props.matchProp !== 'value') labelTest = (0, _stripDiacritics2['default'])(labelTest); } if (props.ignoreCase) { if (props.matchProp !== 'label') valueTest = valueTest.toLowerCase(); if (props.matchProp !== 'value') labelTest = labelTest.toLowerCase(); } return props.matchPos === 'start' ? props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0; }); } module.exports = filterOptions; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function menuRenderer(_ref) { var focusedOption = _ref.focusedOption; var instancePrefix = _ref.instancePrefix; var labelKey = _ref.labelKey; var onFocus = _ref.onFocus; var onSelect = _ref.onSelect; var optionClassName = _ref.optionClassName; var optionComponent = _ref.optionComponent; var optionRenderer = _ref.optionRenderer; var options = _ref.options; var valueArray = _ref.valueArray; var valueKey = _ref.valueKey; var onOptionRef = _ref.onOptionRef; var Option = optionComponent; return options.map(function (option, i) { var isSelected = valueArray && valueArray.indexOf(option) > -1; var isFocused = option === focusedOption; var optionClass = (0, _classnames2['default'])(optionClassName, { 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled }); return _react2['default'].createElement( Option, { className: optionClass, instancePrefix: instancePrefix, isDisabled: option.disabled, isFocused: isFocused, isSelected: isSelected, key: 'option-' + i + '-' + option[valueKey], onFocus: onFocus, onSelect: onSelect, option: option, optionIndex: i, ref: function (ref) { onOptionRef(ref, isFocused); } }, optionRenderer(option, i) ); }); } module.exports = menuRenderer; /***/ }, /* 111 */ /***/ function(module, exports) { 'use strict'; var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }]; module.exports = function stripDiacritics(str) { for (var i = 0; i < map.length; i++) { str = str.replace(map[i].letters, map[i].base); } return str; }; /***/ }, /* 112 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 113 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { "use strict"; // rawAsap provides everything we need except exception management. var rawAsap = __webpack_require__(115); // RawTasks are recycled to reduce GC churn. var freeTasks = []; // We queue errors to ensure they are thrown in right order (FIFO). // Array-as-queue is good enough here, since we are just dealing with exceptions. var pendingErrors = []; var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); function throwFirstError() { if (pendingErrors.length) { throw pendingErrors.shift(); } } /** * Calls a task as soon as possible after returning, in its own event, with priority * over other events like animation, reflow, and repaint. An error thrown from an * event will not interrupt, nor even substantially slow down the processing of * other events, but will be rather postponed to a lower priority event. * @param {{call}} task A callable object, typically a function that takes no * arguments. */ module.exports = asap; function asap(task) { var rawTask; if (freeTasks.length) { rawTask = freeTasks.pop(); } else { rawTask = new RawTask(); } rawTask.task = task; rawAsap(rawTask); } // We wrap tasks with recyclable task objects. A task object implements // `call`, just like a function. function RawTask() { this.task = null; } // The sole purpose of wrapping the task is to catch the exception and recycle // the task object after its single use. RawTask.prototype.call = function () { try { this.task.call(); } catch (error) { if (asap.onerror) { // This hook exists purely for testing purposes. // Its name will be periodically randomized to break any code that // depends on its existence. asap.onerror(error); } else { // In a web browser, exceptions are not fatal. However, to avoid // slowing down the queue of pending tasks, we rethrow the error in a // lower priority turn. pendingErrors.push(error); requestErrorThrow(); } } finally { this.task = null; freeTasks[freeTasks.length] = this; } }; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { "use strict"; // Use the fastest means possible to execute a task in its own turn, with // priority over other events including IO, animation, reflow, and redraw // events in browsers. // // An exception thrown by a task will permanently interrupt the processing of // subsequent tasks. The higher level `asap` function ensures that if an // exception is thrown by a task, that the task queue will continue flushing as // soon as possible, but if you use `rawAsap` directly, you are responsible to // either ensure that no exceptions are thrown from your task, or to manually // call `rawAsap.requestFlush` if an exception is thrown. module.exports = rawAsap; function rawAsap(task) { if (!queue.length) { requestFlush(); flushing = true; } // Equivalent to push, but avoids a function call. queue[queue.length] = task; } var queue = []; // Once a flush has been requested, no further calls to `requestFlush` are // necessary until the next `flush` completes. var flushing = false; // `requestFlush` is an implementation-specific method that attempts to kick // off a `flush` event as quickly as possible. `flush` will attempt to exhaust // the event queue before yielding to the browser's own event loop. var requestFlush; // The position of the next task to execute in the task queue. This is // preserved between calls to `flush` so that it can be resumed if // a task throws an exception. var index = 0; // If a task schedules additional tasks recursively, the task queue can grow // unbounded. To prevent memory exhaustion, the task queue will periodically // truncate already-completed tasks. var capacity = 1024; // The flush function processes all tasks that have been scheduled with // `rawAsap` unless and until one of those tasks throws an exception. // If a task throws an exception, `flush` ensures that its state will remain // consistent and will resume where it left off when called again. // However, `flush` does not make any arrangements to be called again if an // exception is thrown. function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; } // `requestFlush` is implemented using a strategy based on data collected from // every available SauceLabs Selenium web driver worker at time of writing. // https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 // Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that // have WebKitMutationObserver but not un-prefixed MutationObserver. // Must use `global` or `self` instead of `window` to work in both frames and web // workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. /* globals self */ var scope = typeof (window) !== "undefined" ? (window) : self; var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; // MutationObservers are desirable because they have high priority and work // reliably everywhere they are implemented. // They are implemented in all modern browsers. // // - Android 4-4.3 // - Chrome 26-34 // - Firefox 14-29 // - Internet Explorer 11 // - iPad Safari 6-7.1 // - iPhone Safari 7-7.1 // - Safari 6-7 if (typeof BrowserMutationObserver === "function") { requestFlush = makeRequestCallFromMutationObserver(flush); // MessageChannels are desirable because they give direct access to the HTML // task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera // 11-12, and in web workers in many engines. // Although message channels yield to any queued rendering and IO tasks, they // would be better than imposing the 4ms delay of timers. // However, they do not work reliably in Internet Explorer or Safari. // Internet Explorer 10 is the only browser that has setImmediate but does // not have MutationObservers. // Although setImmediate yields to the browser's renderer, it would be // preferrable to falling back to setTimeout since it does not have // the minimum 4ms penalty. // Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and // Desktop to a lesser extent) that renders both setImmediate and // MessageChannel useless for the purposes of ASAP. // https://github.com/kriskowal/q/issues/396 // Timers are implemented universally. // We fall back to timers in workers in most engines, and in foreground // contexts in the following browsers. // However, note that even this simple case requires nuances to operate in a // broad spectrum of browsers. // // - Firefox 3-13 // - Internet Explorer 6-9 // - iPad Safari 4.3 // - Lynx 2.8.7 } else { requestFlush = makeRequestCallFromTimer(flush); } // `requestFlush` requests that the high priority event queue be flushed as // soon as possible. // This is useful to prevent an error thrown in a task from stalling the event // queue if the exception handled by Node.js’s // `process.on("uncaughtException")` or by a domain. rawAsap.requestFlush = requestFlush; // To request a high priority event, we induce a mutation observer by toggling // the text of a text node between "1" and "-1". function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; } // The message channel technique was discovered by Malte Ubl and was the // original foundation for this library. // http://www.nonblocking.io/2011/06/windownexttick.html // Safari 6.0.5 (at least) intermittently fails to create message ports on a // page's first load. Thankfully, this version of Safari supports // MutationObservers, so we don't need to fall back in that case. // function makeRequestCallFromMessageChannel(callback) { // var channel = new MessageChannel(); // channel.port1.onmessage = callback; // return function requestCall() { // channel.port2.postMessage(0); // }; // } // For reasons explained above, we are also unable to use `setImmediate` // under any circumstances. // Even if we were, there is another bug in Internet Explorer 10. // It is not sufficient to assign `setImmediate` to `requestFlush` because // `setImmediate` must be called *by name* and therefore must be wrapped in a // closure. // Never forget. // function makeRequestCallFromSetImmediate(callback) { // return function requestCall() { // setImmediate(callback); // }; // } // Safari 6.0 has a problem where timers will get lost while the user is // scrolling. This problem does not impact ASAP because Safari 6.0 supports // mutation observers, so that implementation is used instead. // However, if we ever elect to use timers in Safari, the prevalent work-around // is to add a scroll event listener that calls for a flush. // `setTimeout` does not call the passed callback if the delay is less than // approximately 7 in web workers in Firefox 8 through 18, and sometimes not // even then. function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; } // This is for `asap.js` only. // Its name will be periodically randomized to break any code that depends on // its existence. rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; // ASAP was originally a nextTick shim included in Q. This was factored out // into this ASAP package. It was later adapted to RSVP which made further // amendments. These decisions, particularly to marginalize MessageChannel and // to capture the MutationObserver implementation in a closure, were integrated // back into ASAP proper. // https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js /***/ }, /* 116 */ /***/ 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; }; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var shallowCloneObject = __webpack_require__(154); var sameColumn = __webpack_require__(116); var ColumnUtils = __webpack_require__(118); var getScrollbarSize = __webpack_require__(153); var isColumnsImmutable = __webpack_require__(63); 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 }; /***/ }, /* 118 */ /***/ 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); } }; /***/ }, /* 119 */ /***/ 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 createObjectWithProperties = __webpack_require__(152); // The list of the propTypes that we want to include in the Draggable div var knownDivPropertyKeys = ['onDragStart', 'onDragEnd', 'onDrag', 'style']; var Draggable = React.createClass({ displayName: 'Draggable', propTypes: { onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrag: PropTypes.func, component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]), style: PropTypes.object }, 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); }, getKnownDivProps: function getKnownDivProps() { return createObjectWithProperties(this.props, knownDivPropertyKeys); }, render: function render() { return React.createElement('div', _extends({}, this.getKnownDivProps(), { onMouseDown: this.onMouseDown, onTouchStart: this.onMouseDown, className: 'react-grid-HeaderCell__draggable' })); } }); module.exports = Draggable; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reactAddonsShallowCompare = __webpack_require__(290); var _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var React = __webpack_require__(1); var ReactDOM = __webpack_require__(5); var joinClasses = __webpack_require__(155); var ExcelColumn = __webpack_require__(13); var ResizeHandle = __webpack_require__(121); 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 }; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return (0, _reactAddonsShallowCompare2['default'])(this, nextProps, nextState) && (this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.column.name !== nextProps.column.name || this.props.column.cellClass !== nextProps.column.cellClass); }, 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)) { // if it is a string, it's an HTML element, and column is not a valid property, so only pass height if (typeof this.props.renderer.type === 'string') { return React.cloneElement(this.props.renderer, { height: this.props.height }); } 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; /***/ }, /* 121 */ /***/ 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__(119); 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; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _ExcelColumn = __webpack_require__(13); var _ExcelColumn2 = _interopRequireDefault(_ExcelColumn); var _reactSelect = __webpack_require__(31); var _reactSelect2 = _interopRequireDefault(_reactSelect); var _isEmptyArray = __webpack_require__(62); var _isEmptyArray2 = _interopRequireDefault(_isEmptyArray); 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 AutoCompleteFilter = function (_React$Component) { _inherits(AutoCompleteFilter, _React$Component); function AutoCompleteFilter(props) { _classCallCheck(this, AutoCompleteFilter); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.getOptions = _this.getOptions.bind(_this); _this.handleChange = _this.handleChange.bind(_this); _this.filterValues = _this.filterValues.bind(_this); _this.state = { options: _this.getOptions(), rawValue: '', placeholder: 'Search...' }; return _this; } AutoCompleteFilter.prototype.componentWillReceiveProps = function componentWillReceiveProps(newProps) { this.setState({ options: this.getOptions(newProps) }); }; AutoCompleteFilter.prototype.getOptions = function getOptions(newProps) { var props = newProps || this.props; var options = props.getValidFilterValues(props.column.key); options = options.map(function (o) { if (typeof o === 'string') { return { value: o, label: o }; } return o; }); return options; }; AutoCompleteFilter.prototype.columnValueContainsSearchTerms = function columnValueContainsSearchTerms(columnValue, filterTerms) { var columnValueContainsSearchTerms = false; for (var key in filterTerms) { if (!filterTerms.hasOwnProperty(key)) { continue; } var filterTermValue = filterTerms[key].value; var checkValueIndex = columnValue.trim().toLowerCase().indexOf(filterTermValue.trim().toLowerCase()); var columnMatchesSearch = checkValueIndex !== -1 && (checkValueIndex !== 0 || columnValue === filterTermValue); if (columnMatchesSearch) { columnValueContainsSearchTerms = true; break; } } return columnValueContainsSearchTerms; }; AutoCompleteFilter.prototype.filterValues = function filterValues(row, columnFilter, columnKey) { var include = true; if (columnFilter === null) { include = false; } else if (!(0, _isEmptyArray2['default'])(columnFilter.filterTerm)) { include = this.columnValueContainsSearchTerms(row[columnKey], columnFilter.filterTerm); } return include; }; AutoCompleteFilter.prototype.handleChange = function handleChange(value) { var filters = value; this.setState({ filters: filters }); this.props.onChange({ filterTerm: filters, column: this.props.column, rawValue: value, filterValues: this.filterValues }); }; AutoCompleteFilter.prototype.render = function render() { var filterName = 'filter-' + this.props.column.key; return _react2['default'].createElement( 'div', { style: { width: this.props.column.width * 0.9 } }, _react2['default'].createElement(_reactSelect2['default'], { name: filterName, options: this.state.options, placeholder: this.state.placeholder, onChange: this.handleChange, escapeClearsValue: true, multi: true, value: this.state.filters }) ); }; return AutoCompleteFilter; }(_react2['default'].Component); AutoCompleteFilter.propTypes = { onChange: _react.PropTypes.func.isRequired, column: _react2['default'].PropTypes.shape(_ExcelColumn2['default']), getValidFilterValues: _react.PropTypes.func }; exports['default'] = AutoCompleteFilter; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _ExcelColumn = __webpack_require__(13); var _ExcelColumn2 = _interopRequireDefault(_ExcelColumn); 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 RuleType = { Number: 1, Range: 2, GreaterThen: 3, LessThen: 4 }; var NumericFilter = function (_React$Component) { _inherits(NumericFilter, _React$Component); function NumericFilter(props) { _classCallCheck(this, NumericFilter); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.handleChange = _this.handleChange.bind(_this); _this.handleKeyPress = _this.handleKeyPress.bind(_this); _this.getRules = _this.getRules.bind(_this); return _this; } NumericFilter.prototype.filterValues = function filterValues(row, columnFilter, columnKey) { if (columnFilter.filterTerm == null) { return true; } var result = false; // implement default filter logic var value = parseInt(row[columnKey], 10); for (var ruleKey in columnFilter.filterTerm) { if (!columnFilter.filterTerm.hasOwnProperty(ruleKey)) { continue; } var rule = columnFilter.filterTerm[ruleKey]; switch (rule.type) { case RuleType.Number: if (rule.value === value) { result = true; } break; case RuleType.GreaterThen: if (rule.value <= value) { result = true; } break; case RuleType.LessThen: if (rule.value >= value) { result = true; } break; case RuleType.Range: if (rule.begin <= value && rule.end >= value) { result = true; } break; default: // do nothing break; } } return result; }; NumericFilter.prototype.getRules = function getRules(value) { var rules = []; if (value === '') { return rules; } // check comma var list = value.split(','); if (list.length > 0) { // handle each value with comma for (var key in list) { if (!list.hasOwnProperty(key)) { continue; } var obj = list[key]; if (obj.indexOf('-') > 0) { // handle dash var begin = parseInt(obj.split('-')[0], 10); var end = parseInt(obj.split('-')[1], 10); rules.push({ type: RuleType.Range, begin: begin, end: end }); } else if (obj.indexOf('>') > -1) { // handle greater then var _begin = parseInt(obj.split('>')[1], 10); rules.push({ type: RuleType.GreaterThen, value: _begin }); } else if (obj.indexOf('<') > -1) { // handle less then var _end = parseInt(obj.split('<')[1], 10); rules.push({ type: RuleType.LessThen, value: _end }); } else { // handle normal values var numericValue = parseInt(obj, 10); rules.push({ type: RuleType.Number, value: numericValue }); } } } return rules; }; NumericFilter.prototype.handleKeyPress = function handleKeyPress(e) { // Validate the input var regex = '>|<|-|,|([0-9])'; var result = RegExp(regex).test(e.key); if (result === false) { e.preventDefault(); } }; NumericFilter.prototype.handleChange = function handleChange(e) { var value = e.target.value; var filters = this.getRules(value); this.props.onChange({ filterTerm: filters.length > 0 ? filters : null, column: this.props.column, rawValue: value, filterValues: this.filterValues }); }; NumericFilter.prototype.render = function render() { var inputKey = 'header-filter-' + this.props.column.key; var columnStyle = { float: 'left', marginRight: 5, maxWidth: '80%' }; var badgeStyle = { cursor: 'help' }; var tooltipText = 'Input Methods: Range (x-y), Greater Then (>x), Less Then (<y)'; return _react2['default'].createElement( 'div', null, _react2['default'].createElement( 'div', { style: columnStyle }, _react2['default'].createElement('input', { key: inputKey, type: 'text', placeholder: 'e.g. 3,10-15,>20', className: 'form-control input-sm', onChange: this.handleChange, onKeyPress: this.handleKeyPress }) ), _react2['default'].createElement( 'div', { className: 'input-sm' }, _react2['default'].createElement( 'span', { className: 'badge', style: badgeStyle, title: tooltipText }, '?' ) ) ); }; return NumericFilter; }(_react2['default'].Component); NumericFilter.propTypes = { onChange: _react2['default'].PropTypes.func.isRequired, column: _react2['default'].PropTypes.shape(_ExcelColumn2['default']) }; module.exports = NumericFilter; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _NumericFilter = __webpack_require__(123); var _NumericFilter2 = _interopRequireDefault(_NumericFilter); var _AutoCompleteFilter = __webpack_require__(122); var _AutoCompleteFilter2 = _interopRequireDefault(_AutoCompleteFilter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Filters = { NumericFilter: _NumericFilter2['default'], AutoCompleteFilter: _AutoCompleteFilter2['default'] }; module.exports = Filters; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _mixedTypeValueRetriever = __webpack_require__(34); var _mixedTypeValueRetriever2 = _interopRequireDefault(_mixedTypeValueRetriever); var _isImmutableCollection = __webpack_require__(33); var _isImmutableCollection2 = _interopRequireDefault(_isImmutableCollection); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var filterRows = function filterRows(filters) { var rows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var retriever = (0, _mixedTypeValueRetriever2['default'])((0, _isImmutableCollection2['default'])(rows)); return rows.filter(function (r) { var include = true; for (var columnKey in filters) { if (filters.hasOwnProperty(columnKey)) { var colFilter = filters[columnKey]; // check if custom filter function exists if (colFilter.filterValues && typeof colFilter.filterValues === 'function' && !colFilter.filterValues(r, colFilter, columnKey)) { include = false; } else if (typeof colFilter.filterTerm === 'string') { // default filter action var rowValue = retriever.getValue(r, columnKey); if (rowValue) { if (rowValue.toString().toLowerCase().indexOf(colFilter.filterTerm.toLowerCase()) === -1) { include = false; } } else { include = false; } } } } return include; }); }; module.exports = filterRows; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _isImmutableCollection = __webpack_require__(33); var _isImmutableCollection2 = _interopRequireDefault(_isImmutableCollection); var _RowGrouperResolver = __webpack_require__(127); var _RowGrouperResolver2 = _interopRequireDefault(_RowGrouperResolver); 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 RowGrouper = function () { function RowGrouper(columns, expandedRows) { var isImmutable = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; _classCallCheck(this, RowGrouper); this.columns = columns.slice(0); this.expandedRows = expandedRows; this.resolver = new _RowGrouperResolver2['default'](isImmutable); } RowGrouper.prototype.isRowExpanded = function isRowExpanded(columnName, name) { var isExpanded = true; var expandedRowGroup = this.expandedRows[columnName]; if (expandedRowGroup && expandedRowGroup[name]) { isExpanded = expandedRowGroup[name].isExpanded; } return isExpanded; }; RowGrouper.prototype.groupRowsByColumn = function groupRowsByColumn(rows) { var columnIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var nextColumnIndex = columnIndex; var columnName = this.columns[columnIndex]; var groupedRows = this.resolver.getGroupedRows(rows, columnName); var keys = this.resolver.getGroupKeys(groupedRows); var dataviewRows = this.resolver.initRowsCollection(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var isExpanded = this.isRowExpanded(columnName, key); var rowGroupHeader = { name: key, __metaData: { isGroup: true, treeDepth: columnIndex, isExpanded: isExpanded, columnGroupName: columnName } }; dataviewRows = this.resolver.addHeaderRow(rowGroupHeader, dataviewRows); if (isExpanded) { nextColumnIndex = columnIndex + 1; if (this.columns.length > nextColumnIndex) { dataviewRows = dataviewRows.concat(this.groupRowsByColumn(this.resolver.getRowObj(groupedRows, key), nextColumnIndex)); nextColumnIndex = columnIndex - 1; } else { dataviewRows = dataviewRows.concat(this.resolver.getRowObj(groupedRows, key)); } } } return dataviewRows; }; return RowGrouper; }(); var groupRows = function groupRows(rows, groupedColumns, expandedRows) { var rowGrouper = new RowGrouper(groupedColumns, expandedRows, (0, _isImmutableCollection2['default'])(rows)); return rowGrouper.groupRowsByColumn(rows, 0); }; module.exports = groupRows; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _immutable = __webpack_require__(71); var _groupBy = __webpack_require__(281); var _groupBy2 = _interopRequireDefault(_groupBy); var _mixedTypeValueRetriever = __webpack_require__(34); var _mixedTypeValueRetriever2 = _interopRequireDefault(_mixedTypeValueRetriever); 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 RowGrouperResolver = function () { function RowGrouperResolver(isImmutable) { _classCallCheck(this, RowGrouperResolver); this.isImmutable = isImmutable; this.getRowObj = (0, _mixedTypeValueRetriever2['default'])(isImmutable).getValue; } RowGrouperResolver.prototype.initRowsCollection = function initRowsCollection() { return this.isImmutable ? new _immutable.List() : []; }; RowGrouperResolver.prototype.getGroupedRows = function getGroupedRows(rows, columnName) { return this.isImmutable ? rows.groupBy(function (x) { return x.get(columnName); }) : (0, _groupBy2['default'])(rows, columnName); }; RowGrouperResolver.prototype.getGroupKeys = function getGroupKeys(groupedRows) { var getKeys = Object.keys; if (this.isImmutable) { getKeys = function getKeys(col) { var keys = []; var iterator = col.keys(); var item = iterator.next(); while (!item.done) { keys.push(item.value); item = iterator.next(); } return keys; }; } return getKeys(groupedRows); }; RowGrouperResolver.prototype.addHeaderRow = function addHeaderRow(rowGroupHeader, dataviewRows) { var rows = dataviewRows; var dvRows = rows.push(rowGroupHeader); if (this.isImmutable) { return dvRows; } return rows; }; return RowGrouperResolver; }(); exports['default'] = RowGrouperResolver; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _mixedTypeValueRetriever = __webpack_require__(34); var _mixedTypeValueRetriever2 = _interopRequireDefault(_mixedTypeValueRetriever); var _isImmutableCollection = __webpack_require__(33); var _isImmutableCollection2 = _interopRequireDefault(_isImmutableCollection); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var comparer = function comparer(a, b) { if (a > b) { return 1; } else if (a < b) { return -1; } return 0; }; var sortRows = function sortRows(rows, sortColumn, sortDirection) { var retriever = (0, _mixedTypeValueRetriever2['default'])((0, _isImmutableCollection2['default'])(rows)); var sortDirectionSign = sortDirection === 'ASC' ? 1 : -1; var rowComparer = function rowComparer(a, b) { return sortDirectionSign * comparer(retriever.getValue(a, sortColumn), retriever.getValue(b, sortColumn)); }; if (sortDirection === 'NONE') { return rows; } return rows.sort(rowComparer); }; module.exports = sortRows; module.exports.comparer = comparer; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = { Selectors: __webpack_require__(58) }; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDndHtml5Backend = __webpack_require__(305); var _reactDndHtml5Backend2 = _interopRequireDefault(_reactDndHtml5Backend); var _reactDnd = __webpack_require__(12); var _DraggableHeaderCell = __webpack_require__(59); var _DraggableHeaderCell2 = _interopRequireDefault(_DraggableHeaderCell); var _RowDragLayer = __webpack_require__(133); var _RowDragLayer2 = _interopRequireDefault(_RowDragLayer); var _isColumnsImmutable = __webpack_require__(63); var _isColumnsImmutable2 = _interopRequireDefault(_isColumnsImmutable); 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 DraggableContainer = function (_Component) { _inherits(DraggableContainer, _Component); function DraggableContainer() { _classCallCheck(this, DraggableContainer); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } DraggableContainer.prototype.getRows = function getRows(rowsCount, rowGetter) { var rows = []; for (var j = 0; j < rowsCount; j++) { rows.push(rowGetter(j)); } return rows; }; DraggableContainer.prototype.renderGrid = function renderGrid() { return _react2['default'].Children.map(this.props.children, function (child) { return _react2['default'].cloneElement(child, { draggableHeaderCell: _DraggableHeaderCell2['default'] }); })[0]; }; DraggableContainer.prototype.render = function render() { var grid = this.renderGrid(); var rowGetter = this.props.getDragPreviewRow || grid.props.rowGetter; var rowsCount = grid.props.rowsCount; var columns = grid.props.columns; var rows = this.getRows(rowsCount, rowGetter); return _react2['default'].createElement( 'div', null, grid, _react2['default'].createElement(_RowDragLayer2['default'], { rowSelection: grid.props.rowSelection, rows: rows, columns: (0, _isColumnsImmutable2['default'])(columns) ? columns.toArray() : columns }) ); }; return DraggableContainer; }(_react.Component); DraggableContainer.propTypes = { children: _react2['default'].PropTypes.element.isRequired, getDragPreviewRow: _react2['default'].PropTypes.func }; exports['default'] = (0, _reactDnd.DragDropContext)(_reactDndHtml5Backend2['default'])(DraggableContainer); /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactDnd = __webpack_require__(12); var _RowComparer = __webpack_require__(57); var _RowComparer2 = _interopRequireDefault(_RowComparer); 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 rowDropTarget = function rowDropTarget(Row) { return function (_React$Component) { _inherits(_class, _React$Component); function _class() { _classCallCheck(this, _class); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } _class.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { return (0, _RowComparer2['default'])(nextProps, this.props); }; _class.prototype.moveRow = function moveRow() { _reactDom2['default'].findDOMNode(this).classList.add('slideUp'); }; _class.prototype.render = function render() { var _props = this.props, connectDropTarget = _props.connectDropTarget, isOver = _props.isOver, canDrop = _props.canDrop; var overlayTop = this.props.idx * this.props.height; return connectDropTarget(_react2['default'].createElement( 'div', null, _react2['default'].createElement(Row, _extends({ ref: 'row' }, this.props)), isOver && canDrop && _react2['default'].createElement('div', { style: { position: 'absolute', top: overlayTop, left: 0, height: this.props.height, width: '100%', zIndex: 1, borderBottom: '1px solid black' } }) )); }; return _class; }(_react2['default'].Component); }; var target = { drop: function drop(props, monitor, component) { // Obtain the dragged item component.moveRow(); var rowSource = monitor.getItem(); var rowTarget = { idx: props.idx, data: props.row }; props.onRowDrop({ rowSource: rowSource, rowTarget: rowTarget }); } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop(), draggedRow: monitor.getItem() }; } exports['default'] = function (Row) { return (0, _reactDnd.DropTarget)('Row', target, collect, { arePropsEqual: function arePropsEqual(nextProps, currentProps) { return !(0, _RowComparer2['default'])(nextProps, currentProps); } })(rowDropTarget(Row)); }; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDnd = __webpack_require__(12); var _CheckboxEditor = __webpack_require__(60); var _CheckboxEditor2 = _interopRequireDefault(_CheckboxEditor); 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 RowActionsCell = function (_React$Component) { _inherits(RowActionsCell, _React$Component); function RowActionsCell() { _classCallCheck(this, RowActionsCell); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } RowActionsCell.prototype.renderRowIndex = function renderRowIndex() { return _react2['default'].createElement( 'div', { className: 'rdg-row-index' }, this.props.rowIdx + 1 ); }; RowActionsCell.prototype.render = function render() { var _props = this.props, connectDragSource = _props.connectDragSource, rowSelection = _props.rowSelection; var rowHandleStyle = rowSelection != null ? { position: 'absolute', marginTop: '5px' } : {}; var isSelected = this.props.value; var editorClass = isSelected ? 'rdg-actions-checkbox selected' : 'rdg-actions-checkbox'; return connectDragSource(_react2['default'].createElement( 'div', null, _react2['default'].createElement('div', { className: 'rdg-drag-row-handle', style: rowHandleStyle }), !isSelected ? this.renderRowIndex() : null, rowSelection != null && _react2['default'].createElement( 'div', { className: editorClass }, _react2['default'].createElement(_CheckboxEditor2['default'], { column: this.props.column, rowIdx: this.props.rowIdx, dependentValues: this.props.dependentValues, value: this.props.value }) ) )); }; return RowActionsCell; }(_react2['default'].Component); RowActionsCell.propTypes = { rowIdx: _react.PropTypes.number.isRequired, connectDragSource: _react.PropTypes.func.isRequired, connectDragPreview: _react.PropTypes.func.isRequired, isDragging: _react.PropTypes.bool.isRequired, isRowHovered: _react.PropTypes.bool, column: _react.PropTypes.object, dependentValues: _react.PropTypes.object, value: _react.PropTypes.bool, rowSelection: _react.PropTypes.object.isRequired }; RowActionsCell.defaultProps = { rowIdx: 0 }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview() }; } var rowIndexSource = { beginDrag: function beginDrag(props) { return { idx: props.rowIdx, data: props.dependentValues }; }, endDrag: function endDrag(props) { return { idx: props.rowIdx, data: props.dependentValues }; } }; exports['default'] = (0, _reactDnd.DragSource)('Row', rowIndexSource, collect)(RowActionsCell); /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDnd = __webpack_require__(12); var _Selectors = __webpack_require__(58); var _Selectors2 = _interopRequireDefault(_Selectors); 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 layerStyles = { cursor: '-webkit-grabbing', position: 'fixed', pointerEvents: 'none', zIndex: 100, left: 0, top: 0, width: '100%', height: '100%' }; function getItemStyles(props) { var currentOffset = props.currentOffset; if (!currentOffset) { return { display: 'none' }; } var x = currentOffset.x, y = currentOffset.y; var transform = 'translate(' + x + 'px, ' + y + 'px)'; return { transform: transform, WebkitTransform: transform }; } var CustomDragLayer = function (_Component) { _inherits(CustomDragLayer, _Component); function CustomDragLayer() { _classCallCheck(this, CustomDragLayer); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } CustomDragLayer.prototype.isDraggedRowSelected = function isDraggedRowSelected(selectedRows) { var _props = this.props, item = _props.item, rowSelection = _props.rowSelection; if (selectedRows && selectedRows.length > 0) { var _ret = function () { var key = rowSelection.selectBy.keys.rowKey; return { v: selectedRows.filter(function (r) { return r[key] === item.data[key]; }).length > 0 }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } return false; }; CustomDragLayer.prototype.getDraggedRows = function getDraggedRows() { var draggedRows = void 0; var rowSelection = this.props.rowSelection; if (rowSelection && rowSelection.selectBy.keys) { var rows = this.props.rows; var _rowSelection$selectB = rowSelection.selectBy.keys, rowKey = _rowSelection$selectB.rowKey, values = _rowSelection$selectB.values; var selectedRows = _Selectors2['default'].getSelectedRowsByKey({ rowKey: rowKey, selectedKeys: values, rows: rows }); draggedRows = this.isDraggedRowSelected(selectedRows) ? selectedRows : [this.props.rows[this.props.item.idx]]; } else { draggedRows = [this.props.rows[this.props.item.idx]]; } return draggedRows; }; CustomDragLayer.prototype.renderDraggedRows = function renderDraggedRows() { var _this2 = this; var columns = this.props.columns; return this.getDraggedRows().map(function (r, i) { return _react2['default'].createElement( 'tr', { key: 'dragged-row-' + i }, _this2.renderDraggedCells(r, i, columns) ); }); }; CustomDragLayer.prototype.renderDraggedCells = function renderDraggedCells(item, rowIdx, columns) { var cells = []; if (item != null) { columns.forEach(function (c) { if (item.hasOwnProperty(c.key)) { if (c.formatter) { var Formatter = c.formatter; cells.push(_react2['default'].createElement( 'td', { key: 'dragged-cell-' + rowIdx + '-' + c.key, className: 'react-grid-Cell', style: { padding: '5px' } }, _react2['default'].createElement(Formatter, { value: item[c.key] }) )); } else { cells.push(_react2['default'].createElement( 'td', { key: 'dragged-cell-' + rowIdx + '-' + c.key, className: 'react-grid-Cell', style: { padding: '5px' } }, item[c.key] )); } } }); } return cells; }; CustomDragLayer.prototype.render = function render() { var isDragging = this.props.isDragging; if (!isDragging) { return null; } var draggedRows = this.renderDraggedRows(); return _react2['default'].createElement( 'div', { style: layerStyles, className: 'rdg-dragging' }, _react2['default'].createElement( 'div', { style: getItemStyles(this.props), className: 'rdg-dragging' }, _react2['default'].createElement( 'table', null, _react2['default'].createElement( 'tbody', null, draggedRows ) ) ) ); }; return CustomDragLayer; }(_react.Component); CustomDragLayer.propTypes = { item: _react.PropTypes.object, itemType: _react.PropTypes.string, currentOffset: _react.PropTypes.shape({ x: _react.PropTypes.number.isRequired, y: _react.PropTypes.number.isRequired }), isDragging: _react.PropTypes.bool.isRequired, rowSelection: _react.PropTypes.object, rows: _react.PropTypes.array.isRequired, columns: _react.PropTypes.array.isRequired }; function collect(monitor) { return { item: monitor.getItem(), itemType: monitor.getItemType(), currentOffset: monitor.getSourceClientOffset(), isDragging: monitor.isDragging() }; } exports['default'] = (0, _reactDnd.DragLayer)(collect)(CustomDragLayer); /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _DragDropContainer = __webpack_require__(130); var _DragDropContainer2 = _interopRequireDefault(_DragDropContainer); var _DraggableHeaderCell = __webpack_require__(59); var _DraggableHeaderCell2 = _interopRequireDefault(_DraggableHeaderCell); var _RowActionsCell = __webpack_require__(132); var _RowActionsCell2 = _interopRequireDefault(_RowActionsCell); var _DropTargetRowContainer = __webpack_require__(131); var _DropTargetRowContainer2 = _interopRequireDefault(_DropTargetRowContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { Container: _DragDropContainer2['default'], DraggableHeaderCell: _DraggableHeaderCell2['default'], RowActionsCell: _RowActionsCell2['default'], DropTargetRowContainer: _DropTargetRowContainer2['default'] }; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var ReactDOM = __webpack_require__(5); var ReactAutocomplete = __webpack_require__(341); var ExcelColumn = __webpack_require__(13); var optionPropType = React.PropTypes.shape({ id: React.PropTypes.required, title: React.PropTypes.string }); var AutoCompleteEditor = React.createClass({ displayName: 'AutoCompleteEditor', propTypes: { onCommit: React.PropTypes.func, options: React.PropTypes.arrayOf(optionPropType), label: React.PropTypes.any, value: React.PropTypes.any, height: React.PropTypes.number, valueParams: React.PropTypes.arrayOf(React.PropTypes.string), column: React.PropTypes.shape(ExcelColumn), resultIdentifier: React.PropTypes.string, search: React.PropTypes.string, onKeyDown: React.PropTypes.func, onFocus: React.PropTypes.func, editorDisplayValue: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { resultIdentifier: 'id' }; }, handleChange: function handleChange() { this.props.onCommit(); }, getValue: function getValue() { var value = void 0; var updated = {}; if (this.hasResults() && this.isFocusedOnSuggestion()) { value = this.getLabel(this.refs.autoComplete.state.focusedValue); if (this.props.valueParams) { value = this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue, this.props.valueParams); } } else { value = this.refs.autoComplete.state.searchTerm; } updated[this.props.column.key] = value; return updated; }, getEditorDisplayValue: function getEditorDisplayValue() { var displayValue = { title: '' }; var _props = this.props, column = _props.column, value = _props.value, editorDisplayValue = _props.editorDisplayValue; if (editorDisplayValue && typeof editorDisplayValue === 'function') { displayValue.title = editorDisplayValue(column, value); } else { displayValue.title = value; } return displayValue; }, getInputNode: function getInputNode() { return ReactDOM.findDOMNode(this).getElementsByTagName('input')[0]; }, getLabel: function getLabel(item) { var label = this.props.label != null ? this.props.label : 'title'; if (typeof label === 'function') { return label(item); } else if (typeof label === 'string') { return item[label]; } }, hasResults: function hasResults() { return this.refs.autoComplete.state.results.length > 0; }, isFocusedOnSuggestion: function isFocusedOnSuggestion() { var autoComplete = this.refs.autoComplete; return autoComplete.state.focusedValue != null; }, constuctValueFromParams: function constuctValueFromParams(obj, props) { if (!props) { return ''; } var ret = []; for (var i = 0, ii = props.length; i < ii; i++) { ret.push(obj[props[i]]); } return ret.join('|'); }, render: function render() { var label = this.props.label != null ? this.props.label : 'title'; return React.createElement( 'div', { height: this.props.height, onKeyDown: this.props.onKeyDown }, React.createElement(ReactAutocomplete, { search: this.props.search, ref: 'autoComplete', label: label, onChange: this.handleChange, onFocus: this.props.onFocus, resultIdentifier: this.props.resultIdentifier, options: this.props.options, value: this.getEditorDisplayValue() }) ); } }); module.exports = AutoCompleteEditor; /***/ }, /* 136 */ /***/ 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 _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; } // Wrapper HOC used when having an editor which is a redux container. // Required since react-data-grid requires access to getInputNode, getValue, // howvever when doing this.getEditor() in react-data-grid we get a react // componenet wrapped by the redux connect function and thus wont have access // to the required methods. module.exports = function (ContainerEditor) { return function (_Component) { _inherits(ContainerEditorWrapper, _Component); function ContainerEditorWrapper() { _classCallCheck(this, ContainerEditorWrapper); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } ContainerEditorWrapper.prototype.getInputNode = function getInputNode() { return this.editorRef.getInputNode(); }; ContainerEditorWrapper.prototype.getValue = function getValue() { return this.editorRef.getValue(); }; ContainerEditorWrapper.prototype.render = function render() { var _this2 = this; return _react2['default'].createElement(ContainerEditor, _extends({ refCallback: function refCallback(ref) { _this2.editorRef = ref; } }, this.props)); }; return ContainerEditorWrapper; }(_react.Component); }; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reactDom = __webpack_require__(5); 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"); } } 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__(61); var DropDownEditor = function (_EditorBase) { _inherits(DropDownEditor, _EditorBase); function DropDownEditor() { _classCallCheck(this, DropDownEditor); return _possibleConstructorReturn(this, _EditorBase.apply(this, arguments)); } DropDownEditor.prototype.getInputNode = function getInputNode() { return _reactDom2['default'].findDOMNode(this); }; DropDownEditor.prototype.onClick = function onClick() { this.getInputNode().focus(); }; DropDownEditor.prototype.onDoubleClick = function onDoubleClick() { this.getInputNode().focus(); }; DropDownEditor.prototype.render = function render() { return React.createElement( 'select', { style: this.getStyle(), defaultValue: this.props.value, onBlur: this.props.onBlur, onChange: this.onChange }, this.renderOptions() ); }; DropDownEditor.prototype.renderOptions = function renderOptions() { var options = []; this.props.options.forEach(function (name) { if (typeof name === 'string') { options.push(React.createElement( 'option', { key: name, value: name }, name )); } else { options.push(React.createElement( 'option', { key: name.id, value: name.value, title: name.title }, name.text || name.value )); } }, this); return options; }; return DropDownEditor; }(EditorBase); DropDownEditor.propTypes = { options: React.PropTypes.arrayOf(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.objectOf({ id: React.PropTypes.string, title: React.PropTypes.string, value: React.PropTypes.string, text: React.PropTypes.string })])).isRequired }; module.exports = DropDownEditor; /***/ }, /* 138 */ /***/ 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__(61); 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; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Editors = { AutoComplete: __webpack_require__(135), DropDownEditor: __webpack_require__(137), SimpleTextEditor: __webpack_require__(138), CheckboxEditor: __webpack_require__(60), ContainerEditorWrapper: __webpack_require__(136) }; module.exports = Editors; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // Used for displaying the value of a dropdown (using DropDownEditor) when not editing it. // Accepts the same parameters as the DropDownEditor. var React = __webpack_require__(1); var DropDownFormatter = React.createClass({ displayName: 'DropDownFormatter', propTypes: { options: React.PropTypes.arrayOf(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.objectOf({ id: React.PropTypes.string, title: React.PropTypes.string, value: React.PropTypes.string, text: React.PropTypes.string })])).isRequired, value: React.PropTypes.string.isRequired }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.value !== this.props.value; }, render: function render() { var value = this.props.value; var option = this.props.options.filter(function (v) { return v === value || v.value === value; })[0]; if (!option) { option = value; } var title = option.title || option.value || option; var text = option.text || option.value || option; return React.createElement( 'div', { title: title }, text ); } }); module.exports = DropDownFormatter; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var PendingPool = {}; var ReadyPool = {}; var ImageFormatter = React.createClass({ displayName: 'ImageFormatter', propTypes: { value: React.PropTypes.string.isRequired }, getInitialState: function getInitialState() { return { ready: false }; }, componentWillMount: function componentWillMount() { this._load(this.props.value); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState({ value: null }); this._load(nextProps.value); } }, _load: function _load(src) { var imageSrc = src; if (ReadyPool[imageSrc]) { this.setState({ value: imageSrc }); return; } if (PendingPool[imageSrc]) { PendingPool[imageSrc].push(this._onLoad); return; } PendingPool[imageSrc] = [this._onLoad]; var img = new Image(); img.onload = function () { PendingPool[imageSrc].forEach(function (callback) { callback(imageSrc); }); delete PendingPool[imageSrc]; img.onload = null; imageSrc = undefined; }; img.src = imageSrc; }, _onLoad: function _onLoad(src) { if (this.isMounted() && src === this.props.value) { this.setState({ value: src }); } }, render: function render() { var style = this.state.value ? { backgroundImage: 'url(' + this.state.value + ')' } : undefined; return React.createElement('div', { className: 'react-grid-image', style: style }); } }); module.exports = ImageFormatter; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // not including this // it currently requires the whole of moment, which we dont want to take as a dependency var ImageFormatter = __webpack_require__(141); var DropDownFormatter = __webpack_require__(140); var Formatters = { ImageFormatter: ImageFormatter, DropDownFormatter: DropDownFormatter }; module.exports = Formatters; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactContextmenu = __webpack_require__(96); 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 ReactDataGridContextMenu = function (_React$Component) { _inherits(ReactDataGridContextMenu, _React$Component); function ReactDataGridContextMenu() { _classCallCheck(this, ReactDataGridContextMenu); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ReactDataGridContextMenu.prototype.render = function render() { return _react2['default'].createElement( _reactContextmenu.ContextMenu, { identifier: 'reactDataGridContextMenu' }, this.props.children ); }; return ReactDataGridContextMenu; }(_react2['default'].Component); ReactDataGridContextMenu.propTypes = { children: _react.PropTypes.node }; exports['default'] = ReactDataGridContextMenu; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; 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 MenuHeader = function (_React$Component) { _inherits(MenuHeader, _React$Component); function MenuHeader() { _classCallCheck(this, MenuHeader); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MenuHeader.prototype.render = function render() { return _react2["default"].createElement( "div", { className: "react-context-menu-header" }, this.props.children ); }; return MenuHeader; }(_react2["default"].Component); MenuHeader.propTypes = { children: _react.PropTypes.any }; exports["default"] = MenuHeader; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ContextMenuLayer = exports.connect = exports.SubMenu = exports.monitor = exports.MenuItem = exports.MenuHeader = exports.ContextMenu = undefined; var _reactContextmenu = __webpack_require__(96); var _ContextMenu = __webpack_require__(143); var _ContextMenu2 = _interopRequireDefault(_ContextMenu); var _MenuHeader = __webpack_require__(144); var _MenuHeader2 = _interopRequireDefault(_MenuHeader); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.ContextMenu = _ContextMenu2['default']; exports.MenuHeader = _MenuHeader2['default']; exports.MenuItem = _reactContextmenu.MenuItem; exports.monitor = _reactContextmenu.monitor; exports.SubMenu = _reactContextmenu.SubMenu; exports.connect = _reactContextmenu.connect; exports.ContextMenuLayer = _reactContextmenu.ContextMenuLayer; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; 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 propTypes = { children: _react.PropTypes.array }; var defaultProps = { enableAddRow: true }; var AdvancedToolbar = function (_Component) { _inherits(AdvancedToolbar, _Component); function AdvancedToolbar() { _classCallCheck(this, AdvancedToolbar); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } AdvancedToolbar.prototype.render = function render() { return _react2["default"].createElement( "div", { className: "react-grid-Toolbar" }, this.props.children, _react2["default"].createElement("div", { className: "tools" }) ); }; return AdvancedToolbar; }(_react.Component); AdvancedToolbar.defaultProps = defaultProps; AdvancedToolbar.propTypes = propTypes; exports["default"] = AdvancedToolbar; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 GroupedColumnButton = function (_Component) { _inherits(GroupedColumnButton, _Component); function GroupedColumnButton() { _classCallCheck(this, GroupedColumnButton); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } GroupedColumnButton.prototype.render = function render() { var style = { width: '80px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; return _react2['default'].createElement( 'button', { className: 'btn grouped-col-btn btn-sm' }, _react2['default'].createElement( 'span', { style: style }, this.props.name ), _react2['default'].createElement('span', { className: 'glyphicon glyphicon-trash', style: { float: 'right', paddingLeft: '5px' }, onClick: this.props.onColumnGroupDeleted.bind(null, this.props.name) }) ); }; return GroupedColumnButton; }(_react.Component); exports['default'] = GroupedColumnButton; GroupedColumnButton.propTypes = { name: _react.PropTypes.string.isRequired, onColumnGroupDeleted: _react.PropTypes.func }; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDnd = __webpack_require__(12); var _Constants = __webpack_require__(56); var _GroupedColumnButton = __webpack_require__(147); var _GroupedColumnButton2 = _interopRequireDefault(_GroupedColumnButton); 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 propTypes = { isOver: _react.PropTypes.bool.isRequired, connectDropTarget: _react.PropTypes.func, canDrop: _react.PropTypes.bool.isRequired, groupBy: _react.PropTypes.array, noColumnsSelectedMessage: _react.PropTypes.string, panelDescription: _react.PropTypes.string, onColumnGroupDeleted: _react.PropTypes.func }; var defaultProps = { noColumnsSelectedMessage: 'Drag a column header here to group by that column', panelDescription: 'Drag a column header here to group by that column' }; var GroupedColumnsPanel = function (_Component) { _inherits(GroupedColumnsPanel, _Component); function GroupedColumnsPanel() { _classCallCheck(this, GroupedColumnsPanel); return _possibleConstructorReturn(this, _Component.call(this)); } GroupedColumnsPanel.prototype.getPanelInstructionMessage = function getPanelInstructionMessage() { var groupBy = this.props.groupBy; return groupBy && groupBy.length > 0 ? this.props.panelDescription : this.props.noColumnsSelectedMessage; }; GroupedColumnsPanel.prototype.renderGroupedColumns = function renderGroupedColumns() { var _this2 = this; return this.props.groupBy.map(function (c) { return _react2['default'].createElement(_GroupedColumnButton2['default'], { key: c, name: c, onColumnGroupDeleted: _this2.props.onColumnGroupDeleted }); }); }; GroupedColumnsPanel.prototype.renderOverlay = function renderOverlay(color) { return _react2['default'].createElement('div', { style: { position: 'absolute', top: 0, left: 0, height: '100%', width: '100%', zIndex: 1, opacity: 0.5, backgroundColor: color } }); }; GroupedColumnsPanel.prototype.render = function render() { var _props = this.props, connectDropTarget = _props.connectDropTarget, isOver = _props.isOver, canDrop = _props.canDrop; return connectDropTarget(_react2['default'].createElement( 'div', { style: { padding: '2px', position: 'relative', margin: '-10px', display: 'inline-block', border: '1px solid #eee' } }, this.renderGroupedColumns(), ' ', _react2['default'].createElement( 'span', null, this.getPanelInstructionMessage() ), isOver && canDrop && this.renderOverlay('yellow'), !isOver && canDrop && this.renderOverlay('#DBECFA') )); }; return GroupedColumnsPanel; }(_react.Component); GroupedColumnsPanel.defaultProps = defaultProps; GroupedColumnsPanel.propTypes = propTypes; var columnTarget = { drop: function drop(props, monitor) { // Obtain the dragged item var item = monitor.getItem(); if (typeof props.onColumnGroupAdded === 'function') { props.onColumnGroupAdded(item.key); } } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop(), draggedolumn: monitor.getItem() }; } exports['default'] = (0, _reactDnd.DropTarget)(_Constants.DragItemTypes.Column, columnTarget, collect)(GroupedColumnsPanel); /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var Toolbar = React.createClass({ displayName: 'Toolbar', propTypes: { onAddRow: React.PropTypes.func, onToggleFilter: React.PropTypes.func, enableFilter: React.PropTypes.bool, numberOfRows: React.PropTypes.number, addRowButtonText: React.PropTypes.string, filterRowsButtonText: React.PropTypes.string }, onAddRow: function onAddRow() { if (this.props.onAddRow !== null && this.props.onAddRow instanceof Function) { this.props.onAddRow({ newRowIndex: this.props.numberOfRows }); } }, getDefaultProps: function getDefaultProps() { return { enableAddRow: true, addRowButtonText: 'Add Row', filterRowsButtonText: 'Filter Rows' }; }, renderAddRowButton: function renderAddRowButton() { if (this.props.onAddRow) { return React.createElement( 'button', { type: 'button', className: 'btn', onClick: this.onAddRow }, this.props.addRowButtonText ); } }, renderToggleFilterButton: function renderToggleFilterButton() { if (this.props.enableFilter) { return React.createElement( 'button', { type: 'button', className: 'btn', onClick: this.props.onToggleFilter }, this.props.filterRowsButtonText ); } }, render: function render() { return React.createElement( 'div', { className: 'react-grid-Toolbar' }, React.createElement( 'div', { className: 'tools' }, this.renderAddRowButton(), this.renderToggleFilterButton() ) ); } }); module.exports = Toolbar; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.GroupedColumnsPanel = exports.AdvancedToolbar = undefined; var _AdvancedToolbar = __webpack_require__(146); var _AdvancedToolbar2 = _interopRequireDefault(_AdvancedToolbar); var _GroupedColumnsPanel = __webpack_require__(148); var _GroupedColumnsPanel2 = _interopRequireDefault(_GroupedColumnsPanel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.AdvancedToolbar = _AdvancedToolbar2['default']; exports.GroupedColumnsPanel = _GroupedColumnsPanel2['default']; /***/ }, /* 151 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function isEmpty(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object; } exports["default"] = isEmpty; /***/ }, /* 152 */ /***/ function(module, exports) { "use strict"; function createObjectWithProperties(originalObj, properties) { var result = {}; for (var _iterator = properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var property = _ref; if (originalObj[property]) { result[property] = originalObj[property]; } } return result; } module.exports = createObjectWithProperties; /***/ }, /* 153 */ /***/ 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; /***/ }, /* 154 */ /***/ 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; /***/ }, /* 155 */ /***/ 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__)); } /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; exports.__esModule = true; var _isDisposable = __webpack_require__(35); var _isDisposable2 = _interopRequireWildcard(_isDisposable); /** * Represents a group of disposable resources that are disposed together. */ var CompositeDisposable = (function () { function CompositeDisposable() { for (var _len = arguments.length, disposables = Array(_len), _key = 0; _key < _len; _key++) { disposables[_key] = arguments[_key]; } _classCallCheck(this, CompositeDisposable); if (Array.isArray(disposables[0]) && disposables.length === 1) { disposables = disposables[0]; } for (var i = 0; i < disposables.length; i++) { if (!_isDisposable2['default'](disposables[i])) { throw new Error('Expected a disposable'); } } this.disposables = disposables; this.isDisposed = false; } /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Disposable} item Disposable to add. */ CompositeDisposable.prototype.add = function add(item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Disposable} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposable.prototype.remove = function remove(item) { if (this.isDisposed) { return false; } var index = this.disposables.indexOf(item); if (index === -1) { return false; } this.disposables.splice(index, 1); item.dispose(); return true; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposable.prototype.dispose = function dispose() { if (this.isDisposed) { return; } var len = this.disposables.length; var currentDisposables = new Array(len); for (var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.isDisposed = true; this.disposables = []; this.length = 0; for (var i = 0; i < len; i++) { currentDisposables[i].dispose(); } }; return CompositeDisposable; })(); exports['default'] = CompositeDisposable; module.exports = exports['default']; /***/ }, /* 157 */ /***/ function(module, exports) { "use strict"; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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; }; })(); exports.__esModule = true; var noop = function noop() {}; /** * The basic disposable. */ var Disposable = (function () { function Disposable(action) { _classCallCheck(this, Disposable); this.isDisposed = false; this.action = action || noop; } Disposable.prototype.dispose = function dispose() { if (!this.isDisposed) { this.action.call(null); this.isDisposed = true; } }; _createClass(Disposable, null, [{ key: "empty", enumerable: true, value: { dispose: noop } }]); return Disposable; })(); exports["default"] = Disposable; module.exports = exports["default"]; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; exports.__esModule = true; var _isDisposable = __webpack_require__(35); var _isDisposable2 = _interopRequireWildcard(_isDisposable); var SerialDisposable = (function () { function SerialDisposable() { _classCallCheck(this, SerialDisposable); this.isDisposed = false; this.current = null; } /** * Gets the underlying disposable. * @return The underlying disposable. */ SerialDisposable.prototype.getDisposable = function getDisposable() { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ SerialDisposable.prototype.setDisposable = function setDisposable() { var value = arguments[0] === undefined ? null : arguments[0]; if (value != null && !_isDisposable2['default'](value)) { throw new Error('Expected either an empty value or a valid disposable'); } var isDisposed = this.isDisposed; var previous = undefined; if (!isDisposed) { previous = this.current; this.current = value; } if (previous) { previous.dispose(); } if (isDisposed && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ SerialDisposable.prototype.dispose = function dispose() { if (this.isDisposed) { return; } this.isDisposed = true; var previous = this.current; this.current = null; if (previous) { previous.dispose(); } }; return SerialDisposable; })(); exports['default'] = SerialDisposable; module.exports = exports['default']; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; var _isDisposable2 = __webpack_require__(35); var _isDisposable3 = _interopRequireWildcard(_isDisposable2); exports.isDisposable = _isDisposable3['default']; var _Disposable2 = __webpack_require__(157); var _Disposable3 = _interopRequireWildcard(_Disposable2); exports.Disposable = _Disposable3['default']; var _CompositeDisposable2 = __webpack_require__(156); var _CompositeDisposable3 = _interopRequireWildcard(_CompositeDisposable2); exports.CompositeDisposable = _CompositeDisposable3['default']; var _SerialDisposable2 = __webpack_require__(158); var _SerialDisposable3 = _interopRequireWildcard(_SerialDisposable2); exports.SerialDisposable = _SerialDisposable3['default']; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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 _reduxLibCreateStore = __webpack_require__(54); var _reduxLibCreateStore2 = _interopRequireDefault(_reduxLibCreateStore); var _reducers = __webpack_require__(167); var _reducers2 = _interopRequireDefault(_reducers); var _actionsDragDrop = __webpack_require__(18); var dragDropActions = _interopRequireWildcard(_actionsDragDrop); var _DragDropMonitor = __webpack_require__(161); var _DragDropMonitor2 = _interopRequireDefault(_DragDropMonitor); var _HandlerRegistry = __webpack_require__(64); var _HandlerRegistry2 = _interopRequireDefault(_HandlerRegistry); var DragDropManager = (function () { function DragDropManager(createBackend) { _classCallCheck(this, DragDropManager); var store = _reduxLibCreateStore2['default'](_reducers2['default']); this.store = store; this.monitor = new _DragDropMonitor2['default'](store); this.registry = this.monitor.registry; this.backend = createBackend(this); store.subscribe(this.handleRefCountChange.bind(this)); } DragDropManager.prototype.handleRefCountChange = function handleRefCountChange() { var shouldSetUp = this.store.getState().refCount > 0; if (shouldSetUp && !this.isSetUp) { this.backend.setup(); this.isSetUp = true; } else if (!shouldSetUp && this.isSetUp) { this.backend.teardown(); this.isSetUp = false; } }; DragDropManager.prototype.getMonitor = function getMonitor() { return this.monitor; }; DragDropManager.prototype.getBackend = function getBackend() { return this.backend; }; DragDropManager.prototype.getRegistry = function getRegistry() { return this.registry; }; DragDropManager.prototype.getActions = function getActions() { var manager = this; var dispatch = this.store.dispatch; function bindActionCreator(actionCreator) { return function () { var action = actionCreator.apply(manager, arguments); if (typeof action !== 'undefined') { dispatch(action); } }; } return Object.keys(dragDropActions).filter(function (key) { return typeof dragDropActions[key] === 'function'; }).reduce(function (boundActions, key) { boundActions[key] = bindActionCreator(dragDropActions[key]); return boundActions; }, {}); }; return DragDropManager; })(); exports['default'] = DragDropManager; module.exports = exports['default']; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _utilsMatchesType = __webpack_require__(67); var _utilsMatchesType2 = _interopRequireDefault(_utilsMatchesType); var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); var _HandlerRegistry = __webpack_require__(64); var _HandlerRegistry2 = _interopRequireDefault(_HandlerRegistry); var _reducersDragOffset = __webpack_require__(66); var _reducersDirtyHandlerIds = __webpack_require__(65); var DragDropMonitor = (function () { function DragDropMonitor(store) { _classCallCheck(this, DragDropMonitor); this.store = store; this.registry = new _HandlerRegistry2['default'](store); } DragDropMonitor.prototype.subscribeToStateChange = function subscribeToStateChange(listener) { var _this = this; var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var handlerIds = _ref.handlerIds; _invariant2['default'](typeof listener === 'function', 'listener must be a function.'); _invariant2['default'](typeof handlerIds === 'undefined' || _lodashIsArray2['default'](handlerIds), 'handlerIds, when specified, must be an array of strings.'); var prevStateId = this.store.getState().stateId; var handleChange = function handleChange() { var state = _this.store.getState(); var currentStateId = state.stateId; try { var canSkipListener = currentStateId === prevStateId || currentStateId === prevStateId + 1 && !_reducersDirtyHandlerIds.areDirty(state.dirtyHandlerIds, handlerIds); if (!canSkipListener) { listener(); } } finally { prevStateId = currentStateId; } }; return this.store.subscribe(handleChange); }; DragDropMonitor.prototype.subscribeToOffsetChange = function subscribeToOffsetChange(listener) { var _this2 = this; _invariant2['default'](typeof listener === 'function', 'listener must be a function.'); var previousState = this.store.getState().dragOffset; var handleChange = function handleChange() { var nextState = _this2.store.getState().dragOffset; if (nextState === previousState) { return; } previousState = nextState; listener(); }; return this.store.subscribe(handleChange); }; DragDropMonitor.prototype.canDragSource = function canDragSource(sourceId) { var source = this.registry.getSource(sourceId); _invariant2['default'](source, 'Expected to find a valid source.'); if (this.isDragging()) { return false; } return source.canDrag(this, sourceId); }; DragDropMonitor.prototype.canDropOnTarget = function canDropOnTarget(targetId) { var target = this.registry.getTarget(targetId); _invariant2['default'](target, 'Expected to find a valid target.'); if (!this.isDragging() || this.didDrop()) { return false; } var targetType = this.registry.getTargetType(targetId); var draggedItemType = this.getItemType(); return _utilsMatchesType2['default'](targetType, draggedItemType) && target.canDrop(this, targetId); }; DragDropMonitor.prototype.isDragging = function isDragging() { return Boolean(this.getItemType()); }; DragDropMonitor.prototype.isDraggingSource = function isDraggingSource(sourceId) { var source = this.registry.getSource(sourceId, true); _invariant2['default'](source, 'Expected to find a valid source.'); if (!this.isDragging() || !this.isSourcePublic()) { return false; } var sourceType = this.registry.getSourceType(sourceId); var draggedItemType = this.getItemType(); if (sourceType !== draggedItemType) { return false; } return source.isDragging(this, sourceId); }; DragDropMonitor.prototype.isOverTarget = function isOverTarget(targetId) { var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref2$shallow = _ref2.shallow; var shallow = _ref2$shallow === undefined ? false : _ref2$shallow; if (!this.isDragging()) { return false; } var targetType = this.registry.getTargetType(targetId); var draggedItemType = this.getItemType(); if (!_utilsMatchesType2['default'](targetType, draggedItemType)) { return false; } var targetIds = this.getTargetIds(); if (!targetIds.length) { return false; } var index = targetIds.indexOf(targetId); if (shallow) { return index === targetIds.length - 1; } else { return index > -1; } }; DragDropMonitor.prototype.getItemType = function getItemType() { return this.store.getState().dragOperation.itemType; }; DragDropMonitor.prototype.getItem = function getItem() { return this.store.getState().dragOperation.item; }; DragDropMonitor.prototype.getSourceId = function getSourceId() { return this.store.getState().dragOperation.sourceId; }; DragDropMonitor.prototype.getTargetIds = function getTargetIds() { return this.store.getState().dragOperation.targetIds; }; DragDropMonitor.prototype.getDropResult = function getDropResult() { return this.store.getState().dragOperation.dropResult; }; DragDropMonitor.prototype.didDrop = function didDrop() { return this.store.getState().dragOperation.didDrop; }; DragDropMonitor.prototype.isSourcePublic = function isSourcePublic() { return this.store.getState().dragOperation.isSourcePublic; }; DragDropMonitor.prototype.getInitialClientOffset = function getInitialClientOffset() { return this.store.getState().dragOffset.initialClientOffset; }; DragDropMonitor.prototype.getInitialSourceClientOffset = function getInitialSourceClientOffset() { return this.store.getState().dragOffset.initialSourceClientOffset; }; DragDropMonitor.prototype.getClientOffset = function getClientOffset() { return this.store.getState().dragOffset.clientOffset; }; DragDropMonitor.prototype.getSourceClientOffset = function getSourceClientOffset() { return _reducersDragOffset.getSourceClientOffset(this.store.getState().dragOffset); }; DragDropMonitor.prototype.getDifferenceFromInitialOffset = function getDifferenceFromInitialOffset() { return _reducersDragOffset.getDifferenceFromInitialOffset(this.store.getState().dragOffset); }; return DragDropMonitor; })(); exports['default'] = DragDropMonitor; module.exports = exports['default']; /***/ }, /* 162 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DragSource = (function () { function DragSource() { _classCallCheck(this, DragSource); } DragSource.prototype.canDrag = function canDrag() { return true; }; DragSource.prototype.isDragging = function isDragging(monitor, handle) { return handle === monitor.getSourceId(); }; DragSource.prototype.endDrag = function endDrag() {}; return DragSource; })(); exports["default"] = DragSource; module.exports = exports["default"]; /***/ }, /* 163 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DropTarget = (function () { function DropTarget() { _classCallCheck(this, DropTarget); } DropTarget.prototype.canDrop = function canDrop() { return true; }; DropTarget.prototype.hover = function hover() {}; DropTarget.prototype.drop = function drop() {}; return DropTarget; })(); exports["default"] = DropTarget; module.exports = exports["default"]; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createBackend; 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 _lodashNoop = __webpack_require__(94); var _lodashNoop2 = _interopRequireDefault(_lodashNoop); var TestBackend = (function () { function TestBackend(manager) { _classCallCheck(this, TestBackend); this.actions = manager.getActions(); } TestBackend.prototype.setup = function setup() { this.didCallSetup = true; }; TestBackend.prototype.teardown = function teardown() { this.didCallTeardown = true; }; TestBackend.prototype.connectDragSource = function connectDragSource() { return _lodashNoop2['default']; }; TestBackend.prototype.connectDragPreview = function connectDragPreview() { return _lodashNoop2['default']; }; TestBackend.prototype.connectDropTarget = function connectDropTarget() { return _lodashNoop2['default']; }; TestBackend.prototype.simulateBeginDrag = function simulateBeginDrag(sourceIds, options) { this.actions.beginDrag(sourceIds, options); }; TestBackend.prototype.simulatePublishDragSource = function simulatePublishDragSource() { this.actions.publishDragSource(); }; TestBackend.prototype.simulateHover = function simulateHover(targetIds, options) { this.actions.hover(targetIds, options); }; TestBackend.prototype.simulateDrop = function simulateDrop() { this.actions.drop(); }; TestBackend.prototype.simulateEndDrag = function simulateEndDrag() { this.actions.endDrag(); }; return TestBackend; })(); function createBackend(manager) { return new TestBackend(manager); } module.exports = exports['default']; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; } var _DragDropManager = __webpack_require__(160); exports.DragDropManager = _interopRequire(_DragDropManager); var _DragSource = __webpack_require__(162); exports.DragSource = _interopRequire(_DragSource); var _DropTarget = __webpack_require__(163); exports.DropTarget = _interopRequire(_DropTarget); var _backendsCreateTestBackend = __webpack_require__(164); exports.createTestBackend = _interopRequire(_backendsCreateTestBackend); /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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; }; exports['default'] = dragOperation; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _actionsDragDrop = __webpack_require__(18); var _actionsRegistry = __webpack_require__(19); var _lodashWithout = __webpack_require__(95); var _lodashWithout2 = _interopRequireDefault(_lodashWithout); var initialState = { itemType: null, item: null, sourceId: null, targetIds: [], dropResult: null, didDrop: false, isSourcePublic: null }; function dragOperation(state, action) { if (state === undefined) state = initialState; switch (action.type) { case _actionsDragDrop.BEGIN_DRAG: return _extends({}, state, { itemType: action.itemType, item: action.item, sourceId: action.sourceId, isSourcePublic: action.isSourcePublic, dropResult: null, didDrop: false }); case _actionsDragDrop.PUBLISH_DRAG_SOURCE: return _extends({}, state, { isSourcePublic: true }); case _actionsDragDrop.HOVER: return _extends({}, state, { targetIds: action.targetIds }); case _actionsRegistry.REMOVE_TARGET: if (state.targetIds.indexOf(action.targetId) === -1) { return state; } return _extends({}, state, { targetIds: _lodashWithout2['default'](state.targetIds, action.targetId) }); case _actionsDragDrop.DROP: return _extends({}, state, { dropResult: action.dropResult, didDrop: true, targetIds: [] }); case _actionsDragDrop.END_DRAG: return _extends({}, state, { itemType: null, item: null, sourceId: null, dropResult: null, didDrop: false, isSourcePublic: null, targetIds: [] }); default: return state; } } module.exports = exports['default']; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _dragOffset = __webpack_require__(66); var _dragOffset2 = _interopRequireDefault(_dragOffset); var _dragOperation = __webpack_require__(166); var _dragOperation2 = _interopRequireDefault(_dragOperation); var _refCount = __webpack_require__(168); var _refCount2 = _interopRequireDefault(_refCount); var _dirtyHandlerIds = __webpack_require__(65); var _dirtyHandlerIds2 = _interopRequireDefault(_dirtyHandlerIds); var _stateId = __webpack_require__(169); var _stateId2 = _interopRequireDefault(_stateId); exports['default'] = function (state, action) { if (state === undefined) state = {}; return { dirtyHandlerIds: _dirtyHandlerIds2['default'](state.dirtyHandlerIds, action, state.dragOperation), dragOffset: _dragOffset2['default'](state.dragOffset, action), refCount: _refCount2['default'](state.refCount, action), dragOperation: _dragOperation2['default'](state.dragOperation, action), stateId: _stateId2['default'](state.stateId) }; }; module.exports = exports['default']; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = refCount; var _actionsRegistry = __webpack_require__(19); function refCount(state, action) { if (state === undefined) state = 0; switch (action.type) { case _actionsRegistry.ADD_SOURCE: case _actionsRegistry.ADD_TARGET: return state + 1; case _actionsRegistry.REMOVE_SOURCE: case _actionsRegistry.REMOVE_TARGET: return state - 1; default: return state; } } module.exports = exports['default']; /***/ }, /* 169 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = stateId; function stateId() { var state = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; return state + 1; } module.exports = exports["default"]; /***/ }, /* 170 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = getNextUniqueId; var nextUniqueId = 0; function getNextUniqueId() { return nextUniqueId++; } module.exports = exports["default"]; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(69); exports.__esModule = true; /** * document.activeElement */ exports['default'] = activeElement; var _ownerDocument = __webpack_require__(36); var _ownerDocument2 = babelHelpers.interopRequireDefault(_ownerDocument); function activeElement() { var doc = arguments[0] === undefined ? document : arguments[0]; try { return doc.activeElement; } catch (e) {} } module.exports = exports['default']; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var hasClass = __webpack_require__(68); module.exports = function addClass(element, className) { if (element.classList) element.classList.add(className);else if (!hasClass(element)) element.className = element.className + ' ' + className; }; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = { addClass: __webpack_require__(172), removeClass: __webpack_require__(174), hasClass: __webpack_require__(68) }; /***/ }, /* 174 */ /***/ function(module, exports) { 'use strict'; module.exports = function removeClass(element, className) { if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ''); }; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var off = function off() {}; if (canUseDOM) { off = (function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.removeEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.detachEvent('on' + eventName, handler); }; })(); } module.exports = off; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var on = function on() {}; if (canUseDOM) { on = (function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.addEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.attachEvent('on' + eventName, handler); }; })(); } module.exports = on; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var contains = (function () { var root = canUseDOM && document.documentElement; return root && root.contains ? function (context, node) { return context.contains(node); } : root && root.compareDocumentPosition ? function (context, node) { return context === node || !!(context.compareDocumentPosition(node) & 16); } : function (context, node) { if (node) do { if (node === context) return true; } while (node = node.parentNode); return false; }; })(); module.exports = contains; /***/ }, /* 178 */ /***/ function(module, exports) { 'use strict'; module.exports = function getWindow(node) { return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false; }; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(69); var _utilCamelizeStyle = __webpack_require__(70); var _utilCamelizeStyle2 = babelHelpers.interopRequireDefault(_utilCamelizeStyle); var rposition = /^(top|right|bottom|left)$/; var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i; module.exports = function _getComputedStyle(node) { if (!node) throw new TypeError('No Element passed to `getComputedStyle()`'); var doc = node.ownerDocument; return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : { //ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72 getPropertyValue: function getPropertyValue(prop) { var style = node.style; prop = (0, _utilCamelizeStyle2['default'])(prop); if (prop == 'float') prop = 'styleFloat'; var current = node.currentStyle[prop] || null; if (current == null && style && style[prop]) current = style[prop]; if (rnumnonpx.test(current) && !rposition.test(prop)) { // Remember the original values var left = style.left; var runStyle = node.runtimeStyle; var rsLeft = runStyle && runStyle.left; // Put in the new values to get a computed value out if (rsLeft) runStyle.left = node.currentStyle.left; style.left = prop === 'fontSize' ? '1em' : current; current = style.pixelLeft + 'px'; // Revert the changed values style.left = left; if (rsLeft) runStyle.left = rsLeft; } return current; } }; }; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var camelize = __webpack_require__(70), hyphenate = __webpack_require__(184), _getComputedStyle = __webpack_require__(179), removeStyle = __webpack_require__(181); var has = Object.prototype.hasOwnProperty; module.exports = function style(node, property, value) { var css = '', props = property; if (typeof property === 'string') { if (value === undefined) return node.style[camelize(property)] || _getComputedStyle(node).getPropertyValue(hyphenate(property));else (props = {})[property] = value; } for (var key in props) if (has.call(props, key)) { !props[key] && props[key] !== 0 ? removeStyle(node, hyphenate(key)) : css += hyphenate(key) + ':' + props[key] + ';'; } node.style.cssText += ';' + css; }; /***/ }, /* 181 */ /***/ function(module, exports) { 'use strict'; module.exports = function removeStyle(node, key) { return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key); }; /***/ }, /* 182 */ /***/ function(module, exports) { "use strict"; var rHyphen = /-(.)/g; module.exports = function camelize(string) { return string.replace(rHyphen, function (_, chr) { return chr.toUpperCase(); }); }; /***/ }, /* 183 */ /***/ function(module, exports) { 'use strict'; var rUpper = /([A-Z])/g; module.exports = function hyphenate(string) { return string.replace(rUpper, '-$1').toLowerCase(); }; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js */ "use strict"; var hyphenate = __webpack_require__(183); var msPattern = /^ms-/; module.exports = function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, "-ms-"); }; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var size; module.exports = function (recalc) { if (!size || recalc) { if (canUseDOM) { var scrollDiv = document.createElement('div'); scrollDiv.style.position = 'absolute'; scrollDiv.style.top = '-9999px'; scrollDiv.style.width = '50px'; scrollDiv.style.height = '50px'; scrollDiv.style.overflow = 'scroll'; document.body.appendChild(scrollDiv); size = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } } return size; }; /***/ }, /* 186 */ /***/ 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; /***/ }, /* 187 */ /***/ function(module, exports) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @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(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(240), hashDelete = __webpack_require__(241), hashGet = __webpack_require__(242), hashHas = __webpack_require__(243), hashSet = __webpack_require__(244); /** * 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; /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(4); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 193 */ /***/ function(module, exports) { /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } module.exports = arrayAggregator; /***/ }, /* 194 */ /***/ function(module, exports) { /** * A specialized version of `_.filter` 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 {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }, /* 195 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 196 */ /***/ 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; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(16); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function assignInDefaults(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } module.exports = assignInDefaults; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(41), eq = __webpack_require__(16); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(200); /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } module.exports = baseAggregator; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(203), createBaseEach = __webpack_require__(229); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }, /* 201 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(230); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(202), keys = __webpack_require__(50); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }, /* 204 */ /***/ function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(201), baseIsNaN = __webpack_require__(210), strictIndexOf = __webpack_require__(275); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arrayIncludes = __webpack_require__(39), arrayIncludesWith = __webpack_require__(40), arrayMap = __webpack_require__(22), baseUnary = __webpack_require__(42), cacheHas = __webpack_require__(24); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseIntersection; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isObjectLike = __webpack_require__(9); /** `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; /***/ }, /* 208 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(73), equalArrays = __webpack_require__(83), equalByTag = __webpack_require__(232), equalObjects = __webpack_require__(233), getTag = __webpack_require__(237), isArray = __webpack_require__(3), isBuffer = __webpack_require__(90), isTypedArray = __webpack_require__(92); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, 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, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_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, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(73), baseIsEqual = __webpack_require__(79); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }, /* 210 */ /***/ function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(91), isMasked = __webpack_require__(248), isObject = __webpack_require__(8), toSource = __webpack_require__(89); /** * 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; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isLength = __webpack_require__(48), isObjectLike = __webpack_require__(9); /** `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; /***/ }, /* 213 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(216), baseMatchesProperty = __webpack_require__(217), identity = __webpack_require__(46), isArray = __webpack_require__(3), property = __webpack_require__(285); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(85), nativeKeys = __webpack_require__(261); /** 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; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8), isPrototype = __webpack_require__(85), nativeKeysIn = __webpack_require__(262); /** 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 `_.keysIn` 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 baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(209), getMatchData = __webpack_require__(234), matchesStrictComparable = __webpack_require__(87); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(79), get = __webpack_require__(280), hasIn = __webpack_require__(282), isKey = __webpack_require__(44), isStrictComparable = __webpack_require__(86), matchesStrictComparable = __webpack_require__(87), toKey = __webpack_require__(27); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; /***/ }, /* 218 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(78); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }, /* 220 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(278), defineProperty = __webpack_require__(82), identity = __webpack_require__(46); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; /***/ }, /* 221 */ /***/ 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; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), arrayMap = __webpack_require__(22), isArray = __webpack_require__(3), isSymbol = __webpack_require__(49); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(76), baseFlatten = __webpack_require__(77), baseUniq = __webpack_require__(80); /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } module.exports = baseXor; /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(28); /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } module.exports = castArrayLikeObject; /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(198), baseAssignValue = __webpack_require__(41); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(4); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { var arrayAggregator = __webpack_require__(193), baseAggregator = __webpack_require__(199), baseIteratee = __webpack_require__(213), isArray = __webpack_require__(3); /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, baseIteratee(iteratee, 2), accumulator); }; } module.exports = createAggregator; /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(11), isIterateeCall = __webpack_require__(246); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(17); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }, /* 230 */ /***/ function(module, exports) { /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { var Set = __webpack_require__(72), noop = __webpack_require__(94), setToArray = __webpack_require__(45); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; module.exports = createSet; /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), Uint8Array = __webpack_require__(191), eq = __webpack_require__(16), equalArrays = __webpack_require__(83), mapToArray = __webpack_require__(259), setToArray = __webpack_require__(45); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @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, bitmask, customizer, equalFunc, 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 & COMPARE_PARTIAL_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 |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { var keys = __webpack_require__(50); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_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, bitmask, customizer, 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; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(86), keys = __webpack_require__(50); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(88); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** 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; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(188), Map = __webpack_require__(37), Promise = __webpack_require__(190), Set = __webpack_require__(72), WeakMap = __webpack_require__(192), baseGetTag = __webpack_require__(10), toSource = __webpack_require__(89); /** `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; /***/ }, /* 238 */ /***/ 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; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(81), isArguments = __webpack_require__(47), isArray = __webpack_require__(3), isIndex = __webpack_require__(43), isLength = __webpack_require__(48), toKey = __webpack_require__(27); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; /***/ }, /* 240 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** * 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; /***/ }, /* 241 */ /***/ 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; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** 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; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** 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; /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** 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; /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), isArguments = __webpack_require__(47), isArray = __webpack_require__(3); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } module.exports = isFlattenable; /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(16), isArrayLike = __webpack_require__(17), isIndex = __webpack_require__(43), isObject = __webpack_require__(8); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }, /* 247 */ /***/ 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; /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(226); /** 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; /***/ }, /* 249 */ /***/ 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; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** 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; /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** * 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; /***/ }, /* 252 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** * 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; /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** * 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; /***/ }, /* 254 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(189), ListCache = __webpack_require__(20), Map = __webpack_require__(37); /** * 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; /***/ }, /* 255 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * 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; /***/ }, /* 256 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * 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; /***/ }, /* 257 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * 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; /***/ }, /* 258 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * 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; /***/ }, /* 259 */ /***/ 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; /***/ }, /* 260 */ /***/ function(module, exports, __webpack_require__) { var memoize = __webpack_require__(93); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }, /* 261 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(88); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }, /* 262 */ /***/ function(module, exports) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }, /* 263 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(84); /** 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 && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }, /* 264 */ /***/ 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; /***/ }, /* 265 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(74); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; /***/ }, /* 266 */ /***/ 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; /***/ }, /* 267 */ /***/ 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; /***/ }, /* 268 */ /***/ function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(220), shortOut = __webpack_require__(269); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; /***/ }, /* 269 */ /***/ function(module, exports) { /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; /***/ }, /* 270 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(20); /** * 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; /***/ }, /* 271 */ /***/ 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; /***/ }, /* 272 */ /***/ 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; /***/ }, /* 273 */ /***/ 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; /***/ }, /* 274 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(20), Map = __webpack_require__(37), MapCache = __webpack_require__(38); /** 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; /***/ }, /* 275 */ /***/ function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }, /* 276 */ /***/ function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(260); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }, /* 277 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(225), createAssigner = __webpack_require__(228), keysIn = __webpack_require__(284); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); module.exports = assignInWith; /***/ }, /* 278 */ /***/ function(module, exports) { /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; /***/ }, /* 279 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(74), assignInDefaults = __webpack_require__(197), assignInWith = __webpack_require__(277), baseRest = __webpack_require__(11); /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, assignInDefaults); return apply(assignInWith, undefined, args); }); module.exports = defaults; /***/ }, /* 280 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(78); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }, /* 281 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(41), createAggregator = __webpack_require__(227); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); module.exports = groupBy; /***/ }, /* 282 */ /***/ function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(204), hasPath = __webpack_require__(239); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }, /* 283 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(22), baseIntersection = __webpack_require__(206), baseRest = __webpack_require__(11), castArrayLikeObject = __webpack_require__(224); /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); module.exports = intersection; /***/ }, /* 284 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(75), baseKeysIn = __webpack_require__(215), isArrayLike = __webpack_require__(17); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @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; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }, /* 285 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(218), basePropertyDeep = __webpack_require__(219), isKey = __webpack_require__(44), toKey = __webpack_require__(27); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }, /* 286 */ /***/ 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; /***/ }, /* 287 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(222); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }, /* 288 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(77), baseRest = __webpack_require__(11), baseUniq = __webpack_require__(80), isArrayLikeObject = __webpack_require__(28); /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); module.exports = union; /***/ }, /* 289 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(194), baseRest = __webpack_require__(11), baseXor = __webpack_require__(223), isArrayLikeObject = __webpack_require__(28); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); module.exports = xor; /***/ }, /* 290 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(335); /***/ }, /* 291 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; exports.default = function (Component) { var displayName = Component.displayName || Component.name || "Component"; return _react2.default.createClass({ displayName: "ContextMenuConnector(" + displayName + ")", getInitialState: function getInitialState() { return { item: _store2.default.getState().currentItem }; }, componentDidMount: function componentDidMount() { this.unsubscribe = _store2.default.subscribe(this.handleUpdate); }, componentWillUnmount: function componentWillUnmount() { this.unsubscribe(); }, handleUpdate: function handleUpdate() { this.setState(this.getInitialState()); }, render: function render() { return _react2.default.createElement(Component, _extends({}, this.props, { item: this.state.item })); } }); }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }, /* 292 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react2 = _interopRequireDefault(_react); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); var _wrapper = __webpack_require__(293); var _wrapper2 = _interopRequireDefault(_wrapper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PropTypes = _react2.default.PropTypes; var ContextMenu = _react2.default.createClass({ displayName: "ContextMenu", propTypes: { identifier: PropTypes.string.isRequired }, getInitialState: function getInitialState() { return _store2.default.getState(); }, componentDidMount: function componentDidMount() { this.unsubscribe = _store2.default.subscribe(this.handleUpdate); }, componentWillUnmount: function componentWillUnmount() { if (this.unsubscribe) this.unsubscribe(); }, handleUpdate: function handleUpdate() { this.setState(this.getInitialState()); }, render: function render() { return _react2.default.createElement(_wrapper2.default, _extends({}, this.props, this.state)); } }); exports.default = ContextMenu; /***/ }, /* 293 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react2 = _interopRequireDefault(_react); var _monitor = __webpack_require__(51); var _monitor2 = _interopRequireDefault(_monitor); var _Modal = __webpack_require__(321); var _Modal2 = _interopRequireDefault(_Modal); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var modalStyle = { position: "fixed", zIndex: 1040, top: 0, bottom: 0, left: 0, right: 0 }, backdropStyle = _extends({}, modalStyle, { zIndex: "auto", backgroundColor: "transparent" }), menuStyles = { position: "fixed", zIndex: "auto" }; var ContextMenuWrapper = _react2.default.createClass({ displayName: "ContextMenuWrapper", getInitialState: function getInitialState() { return { left: 0, top: 0 }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var _this = this; if (nextProps.isVisible === nextProps.identifier) { var wrapper = window.requestAnimationFrame || setTimeout; wrapper(function () { _this.setState(_this.getMenuPosition(nextProps.x, nextProps.y)); _this.menu.parentNode.addEventListener("contextmenu", _this.hideMenu); }); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return this.props.isVisible !== nextProps.visible; }, hideMenu: function hideMenu(e) { e.preventDefault(); this.menu.parentNode.removeEventListener("contextmenu", this.hideMenu); _monitor2.default.hideMenu(); }, getMenuPosition: function getMenuPosition(x, y) { var scrollX = document.documentElement.scrollTop; var scrollY = document.documentElement.scrollLeft; var _window = window; var innerWidth = _window.innerWidth; var innerHeight = _window.innerHeight; var rect = this.menu.getBoundingClientRect(); var menuStyles = { top: y + scrollY, left: x + scrollX }; if (y + rect.height > innerHeight) { menuStyles.top -= rect.height; } if (x + rect.width > innerWidth) { menuStyles.left -= rect.width; } return menuStyles; }, render: function render() { var _this2 = this; var _props = this.props; var isVisible = _props.isVisible; var identifier = _props.identifier; var children = _props.children; var style = _extends({}, menuStyles, this.state); return _react2.default.createElement( _Modal2.default, { style: modalStyle, backdropStyle: backdropStyle, show: isVisible === identifier, onHide: function onHide() { return _monitor2.default.hideMenu(); } }, _react2.default.createElement( "nav", { ref: function ref(c) { return _this2.menu = c; }, style: style, className: "react-context-menu" }, children ) ); } }); exports.default = ContextMenuWrapper; /***/ }, /* 294 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; exports.default = function (identifier, configure) { return function (Component) { var displayName = Component.displayName || Component.name || "Component"; (0, _invariant2.default)(identifier && (typeof identifier === "string" || (typeof identifier === "undefined" ? "undefined" : _typeof(identifier)) === "symbol" || typeof identifier === "function"), "Expected identifier to be string, symbol or function. See %s", displayName); if (configure) { (0, _invariant2.default)(typeof configure === "function", "Expected configure to be a function. See %s", displayName); } return _react2.default.createClass({ displayName: displayName + "ContextMenuLayer", getDefaultProps: function getDefaultProps() { return { renderTag: "div", attributes: {} }; }, mouseDown: false, handleMouseDown: function handleMouseDown(event) { var _this = this; if (this.props.holdToDisplay >= 0 && event.button === 0) { event.persist(); this.mouseDown = true; setTimeout(function () { if (_this.mouseDown) _this.handleContextClick(event); }, this.props.holdToDisplay); } }, handleTouchstart: function handleTouchstart(event) { var _this2 = this; event.persist(); this.mouseDown = true; setTimeout(function () { if (_this2.mouseDown) _this2.handleContextClick(event); }, this.props.holdToDisplay); }, handleTouchEnd: function handleTouchEnd(event) { event.preventDefault(); this.mouseDown = false; }, handleMouseUp: function handleMouseUp(event) { if (event.button === 0) { this.mouseDown = false; } }, handleContextClick: function handleContextClick(event) { var currentItem = typeof configure === "function" ? configure(this.props) : {}; (0, _invariant2.default)((0, _lodash2.default)(currentItem), "Expected configure to return an object. See %s", displayName); event.preventDefault(); var xPos = event.clientX || event.touches && event.touches[0].pageX, yPos = event.clientY || event.touches && event.touches[0].pageY; _store2.default.dispatch({ type: "SET_PARAMS", data: { x: xPos, y: yPos, currentItem: currentItem, isVisible: typeof identifier === "function" ? identifier(this.props) : identifier } }); }, render: function render() { var _props = this.props; var _props$attributes = _props.attributes; var _props$attributes$cla = _props$attributes.className; var className = _props$attributes$cla === undefined ? "" : _props$attributes$cla; var attributes = _objectWithoutProperties(_props$attributes, ["className"]); var renderTag = _props.renderTag; var props = _objectWithoutProperties(_props, ["attributes", "renderTag"]); attributes.className = "react-context-menu-wrapper " + className; attributes.onContextMenu = this.handleContextClick; attributes.onMouseDown = this.handleMouseDown; attributes.onMouseUp = this.handleMouseUp; attributes.onTouchStart = this.handleTouchstart; attributes.onTouchEnd = this.handleTouchEnd; attributes.onMouseOut = this.handleMouseUp; return _react2.default.createElement(renderTag, attributes, _react2.default.createElement(Component, props)); } }); }; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodash = __webpack_require__(187); var _lodash2 = _interopRequireDefault(_lodash); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /***/ }, /* 295 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(97); var _classnames2 = _interopRequireDefault(_classnames); var _objectAssign = __webpack_require__(98); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _monitor = __webpack_require__(51); var _monitor2 = _interopRequireDefault(_monitor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var PropTypes = _react2.default.PropTypes; var MenuItem = _react2.default.createClass({ displayName: "MenuItem", propTypes: { onClick: PropTypes.func.isRequired, data: PropTypes.object, disabled: PropTypes.bool, preventClose: PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { disabled: false, data: {}, attributes: {} }; }, handleClick: function handleClick(event) { var _props = this.props; var disabled = _props.disabled; var onClick = _props.onClick; var data = _props.data; var preventClose = _props.preventClose; event.preventDefault(); if (disabled) return; (0, _objectAssign2.default)(data, _monitor2.default.getItem()); if (typeof onClick === "function") { onClick(event, data); } if (preventClose) return; _monitor2.default.hideMenu(); }, render: function render() { var _props2 = this.props; var disabled = _props2.disabled; var children = _props2.children; var _props2$attributes = _props2.attributes; var _props2$attributes$cl = _props2$attributes.className; var className = _props2$attributes$cl === undefined ? "" : _props2$attributes$cl; var props = _objectWithoutProperties(_props2$attributes, ["className"]); var menuItemClassNames = "react-context-menu-item " + className; var classes = (0, _classnames2.default)({ "react-context-menu-link": true, disabled: disabled }); return _react2.default.createElement( "div", _extends({ className: menuItemClassNames }, props), _react2.default.createElement( "a", { href: "#", className: classes, onClick: this.handleClick }, children ) ); } }); exports.default = MenuItem; /***/ }, /* 296 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { var state = arguments.length <= 0 || arguments[0] === undefined ? defaultState : arguments[0]; var action = arguments[1]; return action.type === "SET_PARAMS" ? (0, _objectAssign2.default)({}, state, action.data) : state; }; var _objectAssign = __webpack_require__(98); var _objectAssign2 = _interopRequireDefault(_objectAssign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultState = { x: 0, y: 0, isVisible: false, currentItem: {} }; /***/ }, /* 297 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(97); var _classnames2 = _interopRequireDefault(_classnames); var _wrapper = __webpack_require__(298); var _wrapper2 = _interopRequireDefault(_wrapper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var menuStyles = { position: "relative", zIndex: "auto" }; var SubMenu = _react2.default.createClass({ displayName: "SubMenu", propTypes: { title: _react2.default.PropTypes.string.isRequired, disabled: _react2.default.PropTypes.bool, hoverDelay: _react2.default.PropTypes.number }, getDefaultProps: function getDefaultProps() { return { hoverDelay: 500 }; }, getInitialState: function getInitialState() { return { visible: false }; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return this.state.isVisible !== nextState.visible; }, componentWillUnmount: function componentWillUnmount() { if (this.opentimer) clearTimeout(this.opentimer); if (this.closetimer) clearTimeout(this.closetimer); }, handleClick: function handleClick(e) { e.preventDefault(); }, handleMouseEnter: function handleMouseEnter() { var _this = this; if (this.closetimer) clearTimeout(this.closetimer); if (this.props.disabled || this.state.visible) return; this.opentimer = setTimeout(function () { return _this.setState({ visible: true }); }, this.props.hoverDelay); }, handleMouseLeave: function handleMouseLeave() { var _this2 = this; if (this.opentimer) clearTimeout(this.opentimer); if (!this.state.visible) return; this.closetimer = setTimeout(function () { return _this2.setState({ visible: false }); }, this.props.hoverDelay); }, render: function render() { var _this3 = this; var _props = this.props; var disabled = _props.disabled; var children = _props.children; var title = _props.title; var visible = this.state.visible; var classes = (0, _classnames2.default)({ "react-context-menu-link": true, disabled: disabled, active: visible }), menuClasses = "react-context-menu-item submenu"; return _react2.default.createElement( "div", { ref: function ref(c) { return _this3.item = c; }, className: menuClasses, style: menuStyles, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, _react2.default.createElement( "a", { href: "#", className: classes, onClick: this.handleClick }, title ), _react2.default.createElement( _wrapper2.default, { visible: visible }, children ) ); } }); exports.default = SubMenu; /***/ }, /* 298 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SubMenuWrapper = _react2.default.createClass({ displayName: "SubMenuWrapper", propTypes: { visible: _react2.default.PropTypes.bool }, getInitialState: function getInitialState() { return { position: { top: true, right: true } }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var _this = this; if (nextProps.visible) { var wrapper = window.requestAnimationFrame || setTimeout; wrapper(function () { _this.setState(_this.getMenuPosition()); _this.forceUpdate(); }); } else { this.setState(this.getInitialState()); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return this.props.visible !== nextProps.visible; }, getMenuPosition: function getMenuPosition() { var _window = window; var innerWidth = _window.innerWidth; var innerHeight = _window.innerHeight; var rect = this.menu.getBoundingClientRect(); var position = {}; if (rect.bottom > innerHeight) { position.bottom = true; } else { position.top = true; } if (rect.right > innerWidth) { position.left = true; } else { position.right = true; } return { position: position }; }, getPositionStyles: function getPositionStyles() { var style = {}; var position = this.state.position; if (position.top) style.top = 0; if (position.bottom) style.bottom = 0; if (position.right) style.left = "100%"; if (position.left) style.right = "100%"; return style; }, render: function render() { var _this2 = this; var _props = this.props; var children = _props.children; var visible = _props.visible; var style = _extends({ display: visible ? "block" : "none", position: "absolute" }, this.getPositionStyles()); return _react2.default.createElement( "nav", { ref: function ref(c) { return _this2.menu = c; }, style: style, className: "react-context-menu" }, children ); } }); exports.default = SubMenuWrapper; /***/ }, /* 299 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _lodashUnion = __webpack_require__(288); var _lodashUnion2 = _interopRequireDefault(_lodashUnion); var _lodashWithout = __webpack_require__(95); var _lodashWithout2 = _interopRequireDefault(_lodashWithout); var EnterLeaveCounter = (function () { function EnterLeaveCounter() { _classCallCheck(this, EnterLeaveCounter); this.entered = []; } EnterLeaveCounter.prototype.enter = function enter(enteringNode) { var previousLength = this.entered.length; this.entered = _lodashUnion2['default'](this.entered.filter(function (node) { return document.documentElement.contains(node) && (!node.contains || node.contains(enteringNode)); }), [enteringNode]); return previousLength === 0 && this.entered.length > 0; }; EnterLeaveCounter.prototype.leave = function leave(leavingNode) { var previousLength = this.entered.length; this.entered = _lodashWithout2['default'](this.entered.filter(function (node) { return document.documentElement.contains(node); }), leavingNode); return previousLength > 0 && this.entered.length === 0; }; EnterLeaveCounter.prototype.reset = function reset() { this.entered = []; }; return EnterLeaveCounter; })(); exports['default'] = EnterLeaveCounter; module.exports = exports['default']; /***/ }, /* 300 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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 _lodashDefaults = __webpack_require__(279); var _lodashDefaults2 = _interopRequireDefault(_lodashDefaults); var _shallowEqual = __webpack_require__(306); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _EnterLeaveCounter = __webpack_require__(299); var _EnterLeaveCounter2 = _interopRequireDefault(_EnterLeaveCounter); var _BrowserDetector = __webpack_require__(99); var _OffsetUtils = __webpack_require__(303); var _NativeDragSources = __webpack_require__(302); var _NativeTypes = __webpack_require__(52); var NativeTypes = _interopRequireWildcard(_NativeTypes); var HTML5Backend = (function () { function HTML5Backend(manager) { _classCallCheck(this, HTML5Backend); this.actions = manager.getActions(); this.monitor = manager.getMonitor(); this.registry = manager.getRegistry(); this.sourcePreviewNodes = {}; this.sourcePreviewNodeOptions = {}; this.sourceNodes = {}; this.sourceNodeOptions = {}; this.enterLeaveCounter = new _EnterLeaveCounter2['default'](); this.getSourceClientOffset = this.getSourceClientOffset.bind(this); this.handleTopDragStart = this.handleTopDragStart.bind(this); this.handleTopDragStartCapture = this.handleTopDragStartCapture.bind(this); this.handleTopDragEndCapture = this.handleTopDragEndCapture.bind(this); this.handleTopDragEnter = this.handleTopDragEnter.bind(this); this.handleTopDragEnterCapture = this.handleTopDragEnterCapture.bind(this); this.handleTopDragLeaveCapture = this.handleTopDragLeaveCapture.bind(this); this.handleTopDragOver = this.handleTopDragOver.bind(this); this.handleTopDragOverCapture = this.handleTopDragOverCapture.bind(this); this.handleTopDrop = this.handleTopDrop.bind(this); this.handleTopDropCapture = this.handleTopDropCapture.bind(this); this.handleSelectStart = this.handleSelectStart.bind(this); this.endDragIfSourceWasRemovedFromDOM = this.endDragIfSourceWasRemovedFromDOM.bind(this); this.endDragNativeItem = this.endDragNativeItem.bind(this); } HTML5Backend.prototype.setup = function setup() { if (typeof window === 'undefined') { return; } if (this.constructor.isSetUp) { throw new Error('Cannot have two HTML5 backends at the same time.'); } this.constructor.isSetUp = true; this.addEventListeners(window); }; HTML5Backend.prototype.teardown = function teardown() { if (typeof window === 'undefined') { return; } this.constructor.isSetUp = false; this.removeEventListeners(window); this.clearCurrentDragSourceNode(); }; HTML5Backend.prototype.addEventListeners = function addEventListeners(target) { target.addEventListener('dragstart', this.handleTopDragStart); target.addEventListener('dragstart', this.handleTopDragStartCapture, true); target.addEventListener('dragend', this.handleTopDragEndCapture, true); target.addEventListener('dragenter', this.handleTopDragEnter); target.addEventListener('dragenter', this.handleTopDragEnterCapture, true); target.addEventListener('dragleave', this.handleTopDragLeaveCapture, true); target.addEventListener('dragover', this.handleTopDragOver); target.addEventListener('dragover', this.handleTopDragOverCapture, true); target.addEventListener('drop', this.handleTopDrop); target.addEventListener('drop', this.handleTopDropCapture, true); }; HTML5Backend.prototype.removeEventListeners = function removeEventListeners(target) { target.removeEventListener('dragstart', this.handleTopDragStart); target.removeEventListener('dragstart', this.handleTopDragStartCapture, true); target.removeEventListener('dragend', this.handleTopDragEndCapture, true); target.removeEventListener('dragenter', this.handleTopDragEnter); target.removeEventListener('dragenter', this.handleTopDragEnterCapture, true); target.removeEventListener('dragleave', this.handleTopDragLeaveCapture, true); target.removeEventListener('dragover', this.handleTopDragOver); target.removeEventListener('dragover', this.handleTopDragOverCapture, true); target.removeEventListener('drop', this.handleTopDrop); target.removeEventListener('drop', this.handleTopDropCapture, true); }; HTML5Backend.prototype.connectDragPreview = function connectDragPreview(sourceId, node, options) { var _this = this; this.sourcePreviewNodeOptions[sourceId] = options; this.sourcePreviewNodes[sourceId] = node; return function () { delete _this.sourcePreviewNodes[sourceId]; delete _this.sourcePreviewNodeOptions[sourceId]; }; }; HTML5Backend.prototype.connectDragSource = function connectDragSource(sourceId, node, options) { var _this2 = this; this.sourceNodes[sourceId] = node; this.sourceNodeOptions[sourceId] = options; var handleDragStart = function handleDragStart(e) { return _this2.handleDragStart(e, sourceId); }; var handleSelectStart = function handleSelectStart(e) { return _this2.handleSelectStart(e, sourceId); }; node.setAttribute('draggable', true); node.addEventListener('dragstart', handleDragStart); node.addEventListener('selectstart', handleSelectStart); return function () { delete _this2.sourceNodes[sourceId]; delete _this2.sourceNodeOptions[sourceId]; node.removeEventListener('dragstart', handleDragStart); node.removeEventListener('selectstart', handleSelectStart); node.setAttribute('draggable', false); }; }; HTML5Backend.prototype.connectDropTarget = function connectDropTarget(targetId, node) { var _this3 = this; var handleDragEnter = function handleDragEnter(e) { return _this3.handleDragEnter(e, targetId); }; var handleDragOver = function handleDragOver(e) { return _this3.handleDragOver(e, targetId); }; var handleDrop = function handleDrop(e) { return _this3.handleDrop(e, targetId); }; node.addEventListener('dragenter', handleDragEnter); node.addEventListener('dragover', handleDragOver); node.addEventListener('drop', handleDrop); return function () { node.removeEventListener('dragenter', handleDragEnter); node.removeEventListener('dragover', handleDragOver); node.removeEventListener('drop', handleDrop); }; }; HTML5Backend.prototype.getCurrentSourceNodeOptions = function getCurrentSourceNodeOptions() { var sourceId = this.monitor.getSourceId(); var sourceNodeOptions = this.sourceNodeOptions[sourceId]; return _lodashDefaults2['default'](sourceNodeOptions || {}, { dropEffect: 'move' }); }; HTML5Backend.prototype.getCurrentDropEffect = function getCurrentDropEffect() { if (this.isDraggingNativeItem()) { // It makes more sense to default to 'copy' for native resources return 'copy'; } return this.getCurrentSourceNodeOptions().dropEffect; }; HTML5Backend.prototype.getCurrentSourcePreviewNodeOptions = function getCurrentSourcePreviewNodeOptions() { var sourceId = this.monitor.getSourceId(); var sourcePreviewNodeOptions = this.sourcePreviewNodeOptions[sourceId]; return _lodashDefaults2['default'](sourcePreviewNodeOptions || {}, { anchorX: 0.5, anchorY: 0.5, captureDraggingState: false }); }; HTML5Backend.prototype.getSourceClientOffset = function getSourceClientOffset(sourceId) { return _OffsetUtils.getNodeClientOffset(this.sourceNodes[sourceId]); }; HTML5Backend.prototype.isDraggingNativeItem = function isDraggingNativeItem() { var itemType = this.monitor.getItemType(); return Object.keys(NativeTypes).some(function (key) { return NativeTypes[key] === itemType; }); }; HTML5Backend.prototype.beginDragNativeItem = function beginDragNativeItem(type) { this.clearCurrentDragSourceNode(); var SourceType = _NativeDragSources.createNativeDragSource(type); this.currentNativeSource = new SourceType(); this.currentNativeHandle = this.registry.addSource(type, this.currentNativeSource); this.actions.beginDrag([this.currentNativeHandle]); // On Firefox, if mousemove fires, the drag is over but browser failed to tell us. // This is not true for other browsers. if (_BrowserDetector.isFirefox()) { window.addEventListener('mousemove', this.endDragNativeItem, true); } }; HTML5Backend.prototype.endDragNativeItem = function endDragNativeItem() { if (!this.isDraggingNativeItem()) { return; } if (_BrowserDetector.isFirefox()) { window.removeEventListener('mousemove', this.endDragNativeItem, true); } this.actions.endDrag(); this.registry.removeSource(this.currentNativeHandle); this.currentNativeHandle = null; this.currentNativeSource = null; }; HTML5Backend.prototype.endDragIfSourceWasRemovedFromDOM = function endDragIfSourceWasRemovedFromDOM() { var node = this.currentDragSourceNode; if (document.body.contains(node)) { return; } if (this.clearCurrentDragSourceNode()) { this.actions.endDrag(); } }; HTML5Backend.prototype.setCurrentDragSourceNode = function setCurrentDragSourceNode(node) { this.clearCurrentDragSourceNode(); this.currentDragSourceNode = node; this.currentDragSourceNodeOffset = _OffsetUtils.getNodeClientOffset(node); this.currentDragSourceNodeOffsetChanged = false; // Receiving a mouse event in the middle of a dragging operation // means it has ended and the drag source node disappeared from DOM, // so the browser didn't dispatch the dragend event. window.addEventListener('mousemove', this.endDragIfSourceWasRemovedFromDOM, true); }; HTML5Backend.prototype.clearCurrentDragSourceNode = function clearCurrentDragSourceNode() { if (this.currentDragSourceNode) { this.currentDragSourceNode = null; this.currentDragSourceNodeOffset = null; this.currentDragSourceNodeOffsetChanged = false; window.removeEventListener('mousemove', this.endDragIfSourceWasRemovedFromDOM, true); return true; } return false; }; HTML5Backend.prototype.checkIfCurrentDragSourceRectChanged = function checkIfCurrentDragSourceRectChanged() { var node = this.currentDragSourceNode; if (!node) { return false; } if (this.currentDragSourceNodeOffsetChanged) { return true; } this.currentDragSourceNodeOffsetChanged = !_shallowEqual2['default'](_OffsetUtils.getNodeClientOffset(node), this.currentDragSourceNodeOffset); return this.currentDragSourceNodeOffsetChanged; }; HTML5Backend.prototype.handleTopDragStartCapture = function handleTopDragStartCapture() { this.clearCurrentDragSourceNode(); this.dragStartSourceIds = []; }; HTML5Backend.prototype.handleDragStart = function handleDragStart(e, sourceId) { this.dragStartSourceIds.unshift(sourceId); }; HTML5Backend.prototype.handleTopDragStart = function handleTopDragStart(e) { var _this4 = this; var dragStartSourceIds = this.dragStartSourceIds; this.dragStartSourceIds = null; var clientOffset = _OffsetUtils.getEventClientOffset(e); // Don't publish the source just yet (see why below) this.actions.beginDrag(dragStartSourceIds, { publishSource: false, getSourceClientOffset: this.getSourceClientOffset, clientOffset: clientOffset }); var dataTransfer = e.dataTransfer; var nativeType = _NativeDragSources.matchNativeItemType(dataTransfer); if (this.monitor.isDragging()) { if (typeof dataTransfer.setDragImage === 'function') { // Use custom drag image if user specifies it. // If child drag source refuses drag but parent agrees, // use parent's node as drag image. Neither works in IE though. var sourceId = this.monitor.getSourceId(); var sourceNode = this.sourceNodes[sourceId]; var dragPreview = this.sourcePreviewNodes[sourceId] || sourceNode; var _getCurrentSourcePreviewNodeOptions = this.getCurrentSourcePreviewNodeOptions(); var anchorX = _getCurrentSourcePreviewNodeOptions.anchorX; var anchorY = _getCurrentSourcePreviewNodeOptions.anchorY; var anchorPoint = { anchorX: anchorX, anchorY: anchorY }; var dragPreviewOffset = _OffsetUtils.getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint); dataTransfer.setDragImage(dragPreview, dragPreviewOffset.x, dragPreviewOffset.y); } try { // Firefox won't drag without setting data dataTransfer.setData('application/json', {}); } catch (err) {} // IE doesn't support MIME types in setData // Store drag source node so we can check whether // it is removed from DOM and trigger endDrag manually. this.setCurrentDragSourceNode(e.target); // Now we are ready to publish the drag source.. or are we not? var _getCurrentSourcePreviewNodeOptions2 = this.getCurrentSourcePreviewNodeOptions(); var captureDraggingState = _getCurrentSourcePreviewNodeOptions2.captureDraggingState; if (!captureDraggingState) { // Usually we want to publish it in the next tick so that browser // is able to screenshot the current (not yet dragging) state. // // It also neatly avoids a situation where render() returns null // in the same tick for the source element, and browser freaks out. setTimeout(function () { return _this4.actions.publishDragSource(); }); } else { // In some cases the user may want to override this behavior, e.g. // to work around IE not supporting custom drag previews. // // When using a custom drag layer, the only way to prevent // the default drag preview from drawing in IE is to screenshot // the dragging state in which the node itself has zero opacity // and height. In this case, though, returning null from render() // will abruptly end the dragging, which is not obvious. // // This is the reason such behavior is strictly opt-in. this.actions.publishDragSource(); } } else if (nativeType) { // A native item (such as URL) dragged from inside the document this.beginDragNativeItem(nativeType); } else if (!dataTransfer.types && (!e.target.hasAttribute || !e.target.hasAttribute('draggable'))) { // Looks like a Safari bug: dataTransfer.types is null, but there was no draggable. // Just let it drag. It's a native type (URL or text) and will be picked up in dragenter handler. return; } else { // If by this time no drag source reacted, tell browser not to drag. e.preventDefault(); } }; HTML5Backend.prototype.handleTopDragEndCapture = function handleTopDragEndCapture() { if (this.clearCurrentDragSourceNode()) { // Firefox can dispatch this event in an infinite loop // if dragend handler does something like showing an alert. // Only proceed if we have not handled it already. this.actions.endDrag(); } }; HTML5Backend.prototype.handleTopDragEnterCapture = function handleTopDragEnterCapture(e) { this.dragEnterTargetIds = []; var isFirstEnter = this.enterLeaveCounter.enter(e.target); if (!isFirstEnter || this.monitor.isDragging()) { return; } var dataTransfer = e.dataTransfer; var nativeType = _NativeDragSources.matchNativeItemType(dataTransfer); if (nativeType) { // A native item (such as file or URL) dragged from outside the document this.beginDragNativeItem(nativeType); } }; HTML5Backend.prototype.handleDragEnter = function handleDragEnter(e, targetId) { this.dragEnterTargetIds.unshift(targetId); }; HTML5Backend.prototype.handleTopDragEnter = function handleTopDragEnter(e) { var _this5 = this; var dragEnterTargetIds = this.dragEnterTargetIds; this.dragEnterTargetIds = []; if (!this.monitor.isDragging()) { // This is probably a native item type we don't understand. return; } if (!_BrowserDetector.isFirefox()) { // Don't emit hover in `dragenter` on Firefox due to an edge case. // If the target changes position as the result of `dragenter`, Firefox // will still happily dispatch `dragover` despite target being no longer // there. The easy solution is to only fire `hover` in `dragover` on FF. this.actions.hover(dragEnterTargetIds, { clientOffset: _OffsetUtils.getEventClientOffset(e) }); } var canDrop = dragEnterTargetIds.some(function (targetId) { return _this5.monitor.canDropOnTarget(targetId); }); if (canDrop) { // IE requires this to fire dragover events e.preventDefault(); e.dataTransfer.dropEffect = this.getCurrentDropEffect(); } }; HTML5Backend.prototype.handleTopDragOverCapture = function handleTopDragOverCapture() { this.dragOverTargetIds = []; }; HTML5Backend.prototype.handleDragOver = function handleDragOver(e, targetId) { this.dragOverTargetIds.unshift(targetId); }; HTML5Backend.prototype.handleTopDragOver = function handleTopDragOver(e) { var _this6 = this; var dragOverTargetIds = this.dragOverTargetIds; this.dragOverTargetIds = []; if (!this.monitor.isDragging()) { // This is probably a native item type we don't understand. // Prevent default "drop and blow away the whole document" action. e.preventDefault(); e.dataTransfer.dropEffect = 'none'; return; } this.actions.hover(dragOverTargetIds, { clientOffset: _OffsetUtils.getEventClientOffset(e) }); var canDrop = dragOverTargetIds.some(function (targetId) { return _this6.monitor.canDropOnTarget(targetId); }); if (canDrop) { // Show user-specified drop effect. e.preventDefault(); e.dataTransfer.dropEffect = this.getCurrentDropEffect(); } else if (this.isDraggingNativeItem()) { // Don't show a nice cursor but still prevent default // "drop and blow away the whole document" action. e.preventDefault(); e.dataTransfer.dropEffect = 'none'; } else if (this.checkIfCurrentDragSourceRectChanged()) { // Prevent animating to incorrect position. // Drop effect must be other than 'none' to prevent animation. e.preventDefault(); e.dataTransfer.dropEffect = 'move'; } }; HTML5Backend.prototype.handleTopDragLeaveCapture = function handleTopDragLeaveCapture(e) { if (this.isDraggingNativeItem()) { e.preventDefault(); } var isLastLeave = this.enterLeaveCounter.leave(e.target); if (!isLastLeave) { return; } if (this.isDraggingNativeItem()) { this.endDragNativeItem(); } }; HTML5Backend.prototype.handleTopDropCapture = function handleTopDropCapture(e) { this.dropTargetIds = []; e.preventDefault(); if (this.isDraggingNativeItem()) { this.currentNativeSource.mutateItemByReadingDataTransfer(e.dataTransfer); } this.enterLeaveCounter.reset(); }; HTML5Backend.prototype.handleDrop = function handleDrop(e, targetId) { this.dropTargetIds.unshift(targetId); }; HTML5Backend.prototype.handleTopDrop = function handleTopDrop(e) { var dropTargetIds = this.dropTargetIds; this.dropTargetIds = []; this.actions.hover(dropTargetIds, { clientOffset: _OffsetUtils.getEventClientOffset(e) }); this.actions.drop(); if (this.isDraggingNativeItem()) { this.endDragNativeItem(); } else { this.endDragIfSourceWasRemovedFromDOM(); } }; HTML5Backend.prototype.handleSelectStart = function handleSelectStart(e) { var target = e.target; // Only IE requires us to explicitly say // we want drag drop operation to start if (typeof target.dragDrop !== 'function') { return; } // Inputs and textareas should be selectable if (target.tagName === 'INPUT' || target.tagName === 'SELECT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { return; } // For other targets, ask IE // to enable drag and drop e.preventDefault(); target.dragDrop(); }; return HTML5Backend; })(); exports['default'] = HTML5Backend; module.exports = exports['default']; /***/ }, /* 301 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var MonotonicInterpolant = (function () { function MonotonicInterpolant(xs, ys) { _classCallCheck(this, MonotonicInterpolant); var length = xs.length; // Rearrange xs and ys so that xs is sorted var indexes = []; for (var i = 0; i < length; i++) { indexes.push(i); } indexes.sort(function (a, b) { return xs[a] < xs[b] ? -1 : 1; }); // Get consecutive differences and slopes var dys = []; var dxs = []; var ms = []; var dx = undefined; var dy = undefined; for (var i = 0; i < length - 1; i++) { dx = xs[i + 1] - xs[i]; dy = ys[i + 1] - ys[i]; dxs.push(dx); dys.push(dy); ms.push(dy / dx); } // Get degree-1 coefficients var c1s = [ms[0]]; for (var i = 0; i < dxs.length - 1; i++) { var _m = ms[i]; var mNext = ms[i + 1]; if (_m * mNext <= 0) { c1s.push(0); } else { dx = dxs[i]; var dxNext = dxs[i + 1]; var common = dx + dxNext; c1s.push(3 * common / ((common + dxNext) / _m + (common + dx) / mNext)); } } c1s.push(ms[ms.length - 1]); // Get degree-2 and degree-3 coefficients var c2s = []; var c3s = []; var m = undefined; for (var i = 0; i < c1s.length - 1; i++) { m = ms[i]; var c1 = c1s[i]; var invDx = 1 / dxs[i]; var common = c1 + c1s[i + 1] - m - m; c2s.push((m - c1 - common) * invDx); c3s.push(common * invDx * invDx); } this.xs = xs; this.ys = ys; this.c1s = c1s; this.c2s = c2s; this.c3s = c3s; } MonotonicInterpolant.prototype.interpolate = function interpolate(x) { var xs = this.xs; var ys = this.ys; var c1s = this.c1s; var c2s = this.c2s; var c3s = this.c3s; // The rightmost point in the dataset should give an exact result var i = xs.length - 1; if (x === xs[i]) { return ys[i]; } // Search for the interval x is in, returning the corresponding y if x is one of the original xs var low = 0; var high = c3s.length - 1; var mid = undefined; while (low <= high) { mid = Math.floor(0.5 * (low + high)); var xHere = xs[mid]; if (xHere < x) { low = mid + 1; } else if (xHere > x) { high = mid - 1; } else { return ys[mid]; } } i = Math.max(0, high); // Interpolate var diff = x - xs[i]; var diffSq = diff * diff; return ys[i] + c1s[i] * diff + c2s[i] * diffSq + c3s[i] * diff * diffSq; }; return MonotonicInterpolant; })(); exports["default"] = MonotonicInterpolant; module.exports = exports["default"]; /***/ }, /* 302 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _nativeTypesConfig; exports.createNativeDragSource = createNativeDragSource; exports.matchNativeItemType = matchNativeItemType; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _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; } var _NativeTypes = __webpack_require__(52); var NativeTypes = _interopRequireWildcard(_NativeTypes); function getDataFromDataTransfer(dataTransfer, typesToTry, defaultValue) { var result = typesToTry.reduce(function (resultSoFar, typeToTry) { return resultSoFar || dataTransfer.getData(typeToTry); }, null); return result != null ? // eslint-disable-line eqeqeq result : defaultValue; } var nativeTypesConfig = (_nativeTypesConfig = {}, _defineProperty(_nativeTypesConfig, NativeTypes.FILE, { exposeProperty: 'files', matchesTypes: ['Files'], getData: function getData(dataTransfer) { return Array.prototype.slice.call(dataTransfer.files); } }), _defineProperty(_nativeTypesConfig, NativeTypes.URL, { exposeProperty: 'urls', matchesTypes: ['Url', 'text/uri-list'], getData: function getData(dataTransfer, matchesTypes) { return getDataFromDataTransfer(dataTransfer, matchesTypes, '').split('\n'); } }), _defineProperty(_nativeTypesConfig, NativeTypes.TEXT, { exposeProperty: 'text', matchesTypes: ['Text', 'text/plain'], getData: function getData(dataTransfer, matchesTypes) { return getDataFromDataTransfer(dataTransfer, matchesTypes, ''); } }), _nativeTypesConfig); function createNativeDragSource(type) { var _nativeTypesConfig$type = nativeTypesConfig[type]; var exposeProperty = _nativeTypesConfig$type.exposeProperty; var matchesTypes = _nativeTypesConfig$type.matchesTypes; var getData = _nativeTypesConfig$type.getData; return (function () { function NativeDragSource() { _classCallCheck(this, NativeDragSource); this.item = Object.defineProperties({}, _defineProperty({}, exposeProperty, { get: function get() { console.warn( // eslint-disable-line no-console 'Browser doesn\'t allow reading "' + exposeProperty + '" until the drop event.'); return null; }, configurable: true, enumerable: true })); } NativeDragSource.prototype.mutateItemByReadingDataTransfer = function mutateItemByReadingDataTransfer(dataTransfer) { delete this.item[exposeProperty]; this.item[exposeProperty] = getData(dataTransfer, matchesTypes); }; NativeDragSource.prototype.canDrag = function canDrag() { return true; }; NativeDragSource.prototype.beginDrag = function beginDrag() { return this.item; }; NativeDragSource.prototype.isDragging = function isDragging(monitor, handle) { return handle === monitor.getSourceId(); }; NativeDragSource.prototype.endDrag = function endDrag() {}; return NativeDragSource; })(); } function matchNativeItemType(dataTransfer) { var dataTransferTypes = Array.prototype.slice.call(dataTransfer.types || []); return Object.keys(nativeTypesConfig).filter(function (nativeItemType) { var matchesTypes = nativeTypesConfig[nativeItemType].matchesTypes; return matchesTypes.some(function (t) { return dataTransferTypes.indexOf(t) > -1; }); })[0] || null; } /***/ }, /* 303 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.getNodeClientOffset = getNodeClientOffset; exports.getEventClientOffset = getEventClientOffset; exports.getDragPreviewOffset = getDragPreviewOffset; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _BrowserDetector = __webpack_require__(99); var _MonotonicInterpolant = __webpack_require__(301); var _MonotonicInterpolant2 = _interopRequireDefault(_MonotonicInterpolant); var ELEMENT_NODE = 1; function getNodeClientOffset(node) { var el = node.nodeType === ELEMENT_NODE ? node : node.parentElement; if (!el) { return null; } var _el$getBoundingClientRect = el.getBoundingClientRect(); var top = _el$getBoundingClientRect.top; var left = _el$getBoundingClientRect.left; return { x: left, y: top }; } function getEventClientOffset(e) { return { x: e.clientX, y: e.clientY }; } function getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint) { // The browsers will use the image intrinsic size under different conditions. // Firefox only cares if it's an image, but WebKit also wants it to be detached. var isImage = dragPreview.nodeName === 'IMG' && (_BrowserDetector.isFirefox() || !document.documentElement.contains(dragPreview)); var dragPreviewNode = isImage ? sourceNode : dragPreview; var dragPreviewNodeOffsetFromClient = getNodeClientOffset(dragPreviewNode); var offsetFromDragPreview = { x: clientOffset.x - dragPreviewNodeOffsetFromClient.x, y: clientOffset.y - dragPreviewNodeOffsetFromClient.y }; var sourceWidth = sourceNode.offsetWidth; var sourceHeight = sourceNode.offsetHeight; var anchorX = anchorPoint.anchorX; var anchorY = anchorPoint.anchorY; var dragPreviewWidth = isImage ? dragPreview.width : sourceWidth; var dragPreviewHeight = isImage ? dragPreview.height : sourceHeight; // Work around @2x coordinate discrepancies in browsers if (_BrowserDetector.isSafari() && isImage) { dragPreviewHeight /= window.devicePixelRatio; dragPreviewWidth /= window.devicePixelRatio; } else if (_BrowserDetector.isFirefox() && !isImage) { dragPreviewHeight *= window.devicePixelRatio; dragPreviewWidth *= window.devicePixelRatio; } // Interpolate coordinates depending on anchor point // If you know a simpler way to do this, let me know var interpolantX = new _MonotonicInterpolant2['default']([0, 0.5, 1], [ // Dock to the left offsetFromDragPreview.x, // Align at the center offsetFromDragPreview.x / sourceWidth * dragPreviewWidth, // Dock to the right offsetFromDragPreview.x + dragPreviewWidth - sourceWidth]); var interpolantY = new _MonotonicInterpolant2['default']([0, 0.5, 1], [ // Dock to the top offsetFromDragPreview.y, // Align at the center offsetFromDragPreview.y / sourceHeight * dragPreviewHeight, // Dock to the bottom offsetFromDragPreview.y + dragPreviewHeight - sourceHeight]); var x = interpolantX.interpolate(anchorX); var y = interpolantY.interpolate(anchorY); // Work around Safari 8 positioning bug if (_BrowserDetector.isSafari() && isImage) { // We'll have to wait for @3x to see if this is entirely correct y += (window.devicePixelRatio - 1) * dragPreviewHeight; } return { x: x, y: y }; } /***/ }, /* 304 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = getEmptyImage; var emptyImage = undefined; function getEmptyImage() { if (!emptyImage) { emptyImage = new Image(); emptyImage.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; } return emptyImage; } module.exports = exports['default']; /***/ }, /* 305 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createHTML5Backend; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _HTML5Backend = __webpack_require__(300); var _HTML5Backend2 = _interopRequireDefault(_HTML5Backend); var _getEmptyImage = __webpack_require__(304); var _getEmptyImage2 = _interopRequireDefault(_getEmptyImage); var _NativeTypes = __webpack_require__(52); var NativeTypes = _interopRequireWildcard(_NativeTypes); exports.NativeTypes = NativeTypes; exports.getEmptyImage = _getEmptyImage2['default']; function createHTML5Backend(manager) { return new _HTML5Backend2['default'](manager); } /***/ }, /* 306 */ 53, /* 307 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _slice = Array.prototype.slice; 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; }; })(); exports['default'] = DragDropContext; 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 _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 _react2 = _interopRequireDefault(_react); var _dndCore = __webpack_require__(165); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); function DragDropContext(backendOrModule) { _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DragDropContext', 'backend'].concat(_slice.call(arguments))); // Auto-detect ES6 default export for people still using ES5 var backend = undefined; if (typeof backendOrModule === 'object' && typeof backendOrModule['default'] === 'function') { backend = backendOrModule['default']; } else { backend = backendOrModule; } _invariant2['default'](typeof backend === 'function', 'Expected the backend to be a function or an ES6 module exporting a default function. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-drop-context.html'); var childContext = { dragDropManager: new _dndCore.DragDropManager(backend) }; return function decorateContext(DecoratedComponent) { var displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'; return (function (_Component) { _inherits(DragDropContextContainer, _Component); function DragDropContextContainer() { _classCallCheck(this, DragDropContextContainer); _Component.apply(this, arguments); } DragDropContextContainer.prototype.getDecoratedComponentInstance = function getDecoratedComponentInstance() { return this.refs.child; }; DragDropContextContainer.prototype.getManager = function getManager() { return childContext.dragDropManager; }; DragDropContextContainer.prototype.getChildContext = function getChildContext() { return childContext; }; DragDropContextContainer.prototype.render = function render() { return _react2['default'].createElement(DecoratedComponent, _extends({}, this.props, { ref: 'child' })); }; _createClass(DragDropContextContainer, null, [{ key: 'DecoratedComponent', value: DecoratedComponent, enumerable: true }, { key: 'displayName', value: 'DragDropContext(' + displayName + ')', enumerable: true }, { key: 'childContextTypes', value: { dragDropManager: _react.PropTypes.object.isRequired }, enumerable: true }]); return DragDropContextContainer; })(_react.Component); }; } module.exports = exports['default']; /***/ }, /* 308 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _slice = Array.prototype.slice; 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; }; })(); exports['default'] = DragLayer; 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 _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 _react2 = _interopRequireDefault(_react); var _utilsShallowEqual = __webpack_require__(53); var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual); var _utilsShallowEqualScalar = __webpack_require__(103); var _utilsShallowEqualScalar2 = _interopRequireDefault(_utilsShallowEqualScalar); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); function DragLayer(collect) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DragLayer', 'collect[, options]'].concat(_slice.call(arguments))); _invariant2['default'](typeof collect === 'function', 'Expected "collect" provided as the first argument to DragLayer ' + 'to be a function that collects props to inject into the component. ', 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html', collect); _invariant2['default'](_lodashIsPlainObject2['default'](options), 'Expected "options" provided as the second argument to DragLayer to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html', options); return function decorateLayer(DecoratedComponent) { var _options$arePropsEqual = options.arePropsEqual; var arePropsEqual = _options$arePropsEqual === undefined ? _utilsShallowEqualScalar2['default'] : _options$arePropsEqual; var displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'; return (function (_Component) { _inherits(DragLayerContainer, _Component); DragLayerContainer.prototype.getDecoratedComponentInstance = function getDecoratedComponentInstance() { return this.refs.child; }; DragLayerContainer.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { return !arePropsEqual(nextProps, this.props) || !_utilsShallowEqual2['default'](nextState, this.state); }; _createClass(DragLayerContainer, null, [{ key: 'DecoratedComponent', value: DecoratedComponent, enumerable: true }, { key: 'displayName', value: 'DragLayer(' + displayName + ')', enumerable: true }, { key: 'contextTypes', value: { dragDropManager: _react.PropTypes.object.isRequired }, enumerable: true }]); function DragLayerContainer(props, context) { _classCallCheck(this, DragLayerContainer); _Component.call(this, props); this.handleChange = this.handleChange.bind(this); this.manager = context.dragDropManager; _invariant2['default'](typeof this.manager === 'object', 'Could not find the drag and drop manager in the context of %s. ' + 'Make sure to wrap the top-level component of your app with DragDropContext. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context', displayName, displayName); this.state = this.getCurrentState(); } DragLayerContainer.prototype.componentDidMount = function componentDidMount() { this.isCurrentlyMounted = true; var monitor = this.manager.getMonitor(); this.unsubscribeFromOffsetChange = monitor.subscribeToOffsetChange(this.handleChange); this.unsubscribeFromStateChange = monitor.subscribeToStateChange(this.handleChange); this.handleChange(); }; DragLayerContainer.prototype.componentWillUnmount = function componentWillUnmount() { this.isCurrentlyMounted = false; this.unsubscribeFromOffsetChange(); this.unsubscribeFromStateChange(); }; DragLayerContainer.prototype.handleChange = function handleChange() { if (!this.isCurrentlyMounted) { return; } var nextState = this.getCurrentState(); if (!_utilsShallowEqual2['default'](nextState, this.state)) { this.setState(nextState); } }; DragLayerContainer.prototype.getCurrentState = function getCurrentState() { var monitor = this.manager.getMonitor(); return collect(monitor); }; DragLayerContainer.prototype.render = function render() { return _react2['default'].createElement(DecoratedComponent, _extends({}, this.props, this.state, { ref: 'child' })); }; return DragLayerContainer; })(_react.Component); }; } module.exports = exports['default']; /***/ }, /* 309 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _slice = Array.prototype.slice; exports['default'] = DragSource; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); var _decorateHandler = __webpack_require__(101); var _decorateHandler2 = _interopRequireDefault(_decorateHandler); var _registerSource = __webpack_require__(317); var _registerSource2 = _interopRequireDefault(_registerSource); var _createSourceFactory = __webpack_require__(312); var _createSourceFactory2 = _interopRequireDefault(_createSourceFactory); var _createSourceMonitor = __webpack_require__(313); var _createSourceMonitor2 = _interopRequireDefault(_createSourceMonitor); var _createSourceConnector = __webpack_require__(311); var _createSourceConnector2 = _interopRequireDefault(_createSourceConnector); var _utilsIsValidType = __webpack_require__(102); var _utilsIsValidType2 = _interopRequireDefault(_utilsIsValidType); function DragSource(type, spec, collect) { var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DragSource', 'type, spec, collect[, options]'].concat(_slice.call(arguments))); var getType = type; if (typeof type !== 'function') { _invariant2['default'](_utilsIsValidType2['default'](type), 'Expected "type" provided as the first argument to DragSource to be ' + 'a string, or a function that returns a string given the current props. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', type); getType = function () { return type; }; } _invariant2['default'](_lodashIsPlainObject2['default'](spec), 'Expected "spec" provided as the second argument to DragSource to be ' + 'a plain object. Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', spec); var createSource = _createSourceFactory2['default'](spec); _invariant2['default'](typeof collect === 'function', 'Expected "collect" provided as the third argument to DragSource to be ' + 'a function that returns a plain object of props to inject. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', collect); _invariant2['default'](_lodashIsPlainObject2['default'](options), 'Expected "options" provided as the fourth argument to DragSource to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', collect); return function decorateSource(DecoratedComponent) { return _decorateHandler2['default']({ connectBackend: function connectBackend(backend, sourceId) { return backend.connectDragSource(sourceId); }, containerDisplayName: 'DragSource', createHandler: createSource, registerHandler: _registerSource2['default'], createMonitor: _createSourceMonitor2['default'], createConnector: _createSourceConnector2['default'], DecoratedComponent: DecoratedComponent, getType: getType, collect: collect, options: options }); }; } module.exports = exports['default']; /***/ }, /* 310 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _slice = Array.prototype.slice; exports['default'] = DropTarget; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); var _decorateHandler = __webpack_require__(101); var _decorateHandler2 = _interopRequireDefault(_decorateHandler); var _registerTarget = __webpack_require__(318); var _registerTarget2 = _interopRequireDefault(_registerTarget); var _createTargetFactory = __webpack_require__(315); var _createTargetFactory2 = _interopRequireDefault(_createTargetFactory); var _createTargetMonitor = __webpack_require__(316); var _createTargetMonitor2 = _interopRequireDefault(_createTargetMonitor); var _createTargetConnector = __webpack_require__(314); var _createTargetConnector2 = _interopRequireDefault(_createTargetConnector); var _utilsIsValidType = __webpack_require__(102); var _utilsIsValidType2 = _interopRequireDefault(_utilsIsValidType); function DropTarget(type, spec, collect) { var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DropTarget', 'type, spec, collect[, options]'].concat(_slice.call(arguments))); var getType = type; if (typeof type !== 'function') { _invariant2['default'](_utilsIsValidType2['default'](type, true), 'Expected "type" provided as the first argument to DropTarget to be ' + 'a string, an array of strings, or a function that returns either given ' + 'the current props. Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', type); getType = function () { return type; }; } _invariant2['default'](_lodashIsPlainObject2['default'](spec), 'Expected "spec" provided as the second argument to DropTarget to be ' + 'a plain object. Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', spec); var createTarget = _createTargetFactory2['default'](spec); _invariant2['default'](typeof collect === 'function', 'Expected "collect" provided as the third argument to DropTarget to be ' + 'a function that returns a plain object of props to inject. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', collect); _invariant2['default'](_lodashIsPlainObject2['default'](options), 'Expected "options" provided as the fourth argument to DropTarget to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', collect); return function decorateTarget(DecoratedComponent) { return _decorateHandler2['default']({ connectBackend: function connectBackend(backend, targetId) { return backend.connectDropTarget(targetId); }, containerDisplayName: 'DropTarget', createHandler: createTarget, registerHandler: _registerTarget2['default'], createMonitor: _createTargetMonitor2['default'], createConnector: _createTargetConnector2['default'], DecoratedComponent: DecoratedComponent, getType: getType, collect: collect, options: options }); }; } module.exports = exports['default']; /***/ }, /* 311 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createSourceConnector; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _wrapConnectorHooks = __webpack_require__(104); var _wrapConnectorHooks2 = _interopRequireDefault(_wrapConnectorHooks); var _areOptionsEqual = __webpack_require__(100); var _areOptionsEqual2 = _interopRequireDefault(_areOptionsEqual); function createSourceConnector(backend) { var currentHandlerId = undefined; var currentDragSourceNode = undefined; var currentDragSourceOptions = undefined; var disconnectCurrentDragSource = undefined; var currentDragPreviewNode = undefined; var currentDragPreviewOptions = undefined; var disconnectCurrentDragPreview = undefined; function reconnectDragSource() { if (disconnectCurrentDragSource) { disconnectCurrentDragSource(); disconnectCurrentDragSource = null; } if (currentHandlerId && currentDragSourceNode) { disconnectCurrentDragSource = backend.connectDragSource(currentHandlerId, currentDragSourceNode, currentDragSourceOptions); } } function reconnectDragPreview() { if (disconnectCurrentDragPreview) { disconnectCurrentDragPreview(); disconnectCurrentDragPreview = null; } if (currentHandlerId && currentDragPreviewNode) { disconnectCurrentDragPreview = backend.connectDragPreview(currentHandlerId, currentDragPreviewNode, currentDragPreviewOptions); } } function receiveHandlerId(handlerId) { if (handlerId === currentHandlerId) { return; } currentHandlerId = handlerId; reconnectDragSource(); reconnectDragPreview(); } var hooks = _wrapConnectorHooks2['default']({ dragSource: function connectDragSource(node, options) { if (node === currentDragSourceNode && _areOptionsEqual2['default'](options, currentDragSourceOptions)) { return; } currentDragSourceNode = node; currentDragSourceOptions = options; reconnectDragSource(); }, dragPreview: function connectDragPreview(node, options) { if (node === currentDragPreviewNode && _areOptionsEqual2['default'](options, currentDragPreviewOptions)) { return; } currentDragPreviewNode = node; currentDragPreviewOptions = options; reconnectDragPreview(); } }); return { receiveHandlerId: receiveHandlerId, hooks: hooks }; } module.exports = exports['default']; /***/ }, /* 312 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createSourceFactory; 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 _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var ALLOWED_SPEC_METHODS = ['canDrag', 'beginDrag', 'canDrag', 'isDragging', 'endDrag']; var REQUIRED_SPEC_METHODS = ['beginDrag']; function createSourceFactory(spec) { Object.keys(spec).forEach(function (key) { _invariant2['default'](ALLOWED_SPEC_METHODS.indexOf(key) > -1, 'Expected the drag source specification to only have ' + 'some of the following keys: %s. ' + 'Instead received a specification with an unexpected "%s" key. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', ALLOWED_SPEC_METHODS.join(', '), key); _invariant2['default'](typeof spec[key] === 'function', 'Expected %s in the drag source specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', key, key, spec[key]); }); REQUIRED_SPEC_METHODS.forEach(function (key) { _invariant2['default'](typeof spec[key] === 'function', 'Expected %s in the drag source specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', key, key, spec[key]); }); var Source = (function () { function Source(monitor) { _classCallCheck(this, Source); this.monitor = monitor; this.props = null; this.component = null; } Source.prototype.receiveProps = function receiveProps(props) { this.props = props; }; Source.prototype.receiveComponent = function receiveComponent(component) { this.component = component; }; Source.prototype.canDrag = function canDrag() { if (!spec.canDrag) { return true; } return spec.canDrag(this.props, this.monitor); }; Source.prototype.isDragging = function isDragging(globalMonitor, sourceId) { if (!spec.isDragging) { return sourceId === globalMonitor.getSourceId(); } return spec.isDragging(this.props, this.monitor); }; Source.prototype.beginDrag = function beginDrag() { var item = spec.beginDrag(this.props, this.monitor, this.component); if (false) { _invariant2['default'](_lodashIsPlainObject2['default'](item), 'beginDrag() must return a plain object that represents the dragged item. ' + 'Instead received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', item); } return item; }; Source.prototype.endDrag = function endDrag() { if (!spec.endDrag) { return; } spec.endDrag(this.props, this.monitor, this.component); }; return Source; })(); return function createSource(monitor) { return new Source(monitor); }; } module.exports = exports['default']; /***/ }, /* 313 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createSourceMonitor; 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 _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var isCallingCanDrag = false; var isCallingIsDragging = false; var SourceMonitor = (function () { function SourceMonitor(manager) { _classCallCheck(this, SourceMonitor); this.internalMonitor = manager.getMonitor(); } SourceMonitor.prototype.receiveHandlerId = function receiveHandlerId(sourceId) { this.sourceId = sourceId; }; SourceMonitor.prototype.canDrag = function canDrag() { _invariant2['default'](!isCallingCanDrag, 'You may not call monitor.canDrag() inside your canDrag() implementation. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html'); try { isCallingCanDrag = true; return this.internalMonitor.canDragSource(this.sourceId); } finally { isCallingCanDrag = false; } }; SourceMonitor.prototype.isDragging = function isDragging() { _invariant2['default'](!isCallingIsDragging, 'You may not call monitor.isDragging() inside your isDragging() implementation. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html'); try { isCallingIsDragging = true; return this.internalMonitor.isDraggingSource(this.sourceId); } finally { isCallingIsDragging = false; } }; SourceMonitor.prototype.getItemType = function getItemType() { return this.internalMonitor.getItemType(); }; SourceMonitor.prototype.getItem = function getItem() { return this.internalMonitor.getItem(); }; SourceMonitor.prototype.getDropResult = function getDropResult() { return this.internalMonitor.getDropResult(); }; SourceMonitor.prototype.didDrop = function didDrop() { return this.internalMonitor.didDrop(); }; SourceMonitor.prototype.getInitialClientOffset = function getInitialClientOffset() { return this.internalMonitor.getInitialClientOffset(); }; SourceMonitor.prototype.getInitialSourceClientOffset = function getInitialSourceClientOffset() { return this.internalMonitor.getInitialSourceClientOffset(); }; SourceMonitor.prototype.getSourceClientOffset = function getSourceClientOffset() { return this.internalMonitor.getSourceClientOffset(); }; SourceMonitor.prototype.getClientOffset = function getClientOffset() { return this.internalMonitor.getClientOffset(); }; SourceMonitor.prototype.getDifferenceFromInitialOffset = function getDifferenceFromInitialOffset() { return this.internalMonitor.getDifferenceFromInitialOffset(); }; return SourceMonitor; })(); function createSourceMonitor(manager) { return new SourceMonitor(manager); } module.exports = exports['default']; /***/ }, /* 314 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createTargetConnector; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _wrapConnectorHooks = __webpack_require__(104); var _wrapConnectorHooks2 = _interopRequireDefault(_wrapConnectorHooks); var _areOptionsEqual = __webpack_require__(100); var _areOptionsEqual2 = _interopRequireDefault(_areOptionsEqual); function createTargetConnector(backend) { var currentHandlerId = undefined; var currentDropTargetNode = undefined; var currentDropTargetOptions = undefined; var disconnectCurrentDropTarget = undefined; function reconnectDropTarget() { if (disconnectCurrentDropTarget) { disconnectCurrentDropTarget(); disconnectCurrentDropTarget = null; } if (currentHandlerId && currentDropTargetNode) { disconnectCurrentDropTarget = backend.connectDropTarget(currentHandlerId, currentDropTargetNode, currentDropTargetOptions); } } function receiveHandlerId(handlerId) { if (handlerId === currentHandlerId) { return; } currentHandlerId = handlerId; reconnectDropTarget(); } var hooks = _wrapConnectorHooks2['default']({ dropTarget: function connectDropTarget(node, options) { if (node === currentDropTargetNode && _areOptionsEqual2['default'](options, currentDropTargetOptions)) { return; } currentDropTargetNode = node; currentDropTargetOptions = options; reconnectDropTarget(); } }); return { receiveHandlerId: receiveHandlerId, hooks: hooks }; } module.exports = exports['default']; /***/ }, /* 315 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createTargetFactory; 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 _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var ALLOWED_SPEC_METHODS = ['canDrop', 'hover', 'drop']; function createTargetFactory(spec) { Object.keys(spec).forEach(function (key) { _invariant2['default'](ALLOWED_SPEC_METHODS.indexOf(key) > -1, 'Expected the drop target specification to only have ' + 'some of the following keys: %s. ' + 'Instead received a specification with an unexpected "%s" key. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', ALLOWED_SPEC_METHODS.join(', '), key); _invariant2['default'](typeof spec[key] === 'function', 'Expected %s in the drop target specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', key, key, spec[key]); }); var Target = (function () { function Target(monitor) { _classCallCheck(this, Target); this.monitor = monitor; this.props = null; this.component = null; } Target.prototype.receiveProps = function receiveProps(props) { this.props = props; }; Target.prototype.receiveMonitor = function receiveMonitor(monitor) { this.monitor = monitor; }; Target.prototype.receiveComponent = function receiveComponent(component) { this.component = component; }; Target.prototype.canDrop = function canDrop() { if (!spec.canDrop) { return true; } return spec.canDrop(this.props, this.monitor); }; Target.prototype.hover = function hover() { if (!spec.hover) { return; } spec.hover(this.props, this.monitor, this.component); }; Target.prototype.drop = function drop() { if (!spec.drop) { return; } var dropResult = spec.drop(this.props, this.monitor, this.component); if (false) { _invariant2['default'](typeof dropResult === 'undefined' || _lodashIsPlainObject2['default'](dropResult), 'drop() must either return undefined, or an object that represents the drop result. ' + 'Instead received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', dropResult); } return dropResult; }; return Target; })(); return function createTarget(monitor) { return new Target(monitor); }; } module.exports = exports['default']; /***/ }, /* 316 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createTargetMonitor; 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 _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var isCallingCanDrop = false; var TargetMonitor = (function () { function TargetMonitor(manager) { _classCallCheck(this, TargetMonitor); this.internalMonitor = manager.getMonitor(); } TargetMonitor.prototype.receiveHandlerId = function receiveHandlerId(targetId) { this.targetId = targetId; }; TargetMonitor.prototype.canDrop = function canDrop() { _invariant2['default'](!isCallingCanDrop, 'You may not call monitor.canDrop() inside your canDrop() implementation. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target-monitor.html'); try { isCallingCanDrop = true; return this.internalMonitor.canDropOnTarget(this.targetId); } finally { isCallingCanDrop = false; } }; TargetMonitor.prototype.isOver = function isOver(options) { return this.internalMonitor.isOverTarget(this.targetId, options); }; TargetMonitor.prototype.getItemType = function getItemType() { return this.internalMonitor.getItemType(); }; TargetMonitor.prototype.getItem = function getItem() { return this.internalMonitor.getItem(); }; TargetMonitor.prototype.getDropResult = function getDropResult() { return this.internalMonitor.getDropResult(); }; TargetMonitor.prototype.didDrop = function didDrop() { return this.internalMonitor.didDrop(); }; TargetMonitor.prototype.getInitialClientOffset = function getInitialClientOffset() { return this.internalMonitor.getInitialClientOffset(); }; TargetMonitor.prototype.getInitialSourceClientOffset = function getInitialSourceClientOffset() { return this.internalMonitor.getInitialSourceClientOffset(); }; TargetMonitor.prototype.getSourceClientOffset = function getSourceClientOffset() { return this.internalMonitor.getSourceClientOffset(); }; TargetMonitor.prototype.getClientOffset = function getClientOffset() { return this.internalMonitor.getClientOffset(); }; TargetMonitor.prototype.getDifferenceFromInitialOffset = function getDifferenceFromInitialOffset() { return this.internalMonitor.getDifferenceFromInitialOffset(); }; return TargetMonitor; })(); function createTargetMonitor(manager) { return new TargetMonitor(manager); } module.exports = exports['default']; /***/ }, /* 317 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = registerSource; function registerSource(type, source, manager) { var registry = manager.getRegistry(); var sourceId = registry.addSource(type, source); function unregisterSource() { registry.removeSource(sourceId); } return { handlerId: sourceId, unregister: unregisterSource }; } module.exports = exports["default"]; /***/ }, /* 318 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = registerTarget; function registerTarget(type, target, manager) { var registry = manager.getRegistry(); var targetId = registry.addTarget(type, target); function unregisterTarget() { registry.removeTarget(targetId); } return { handlerId: targetId, unregister: unregisterTarget }; } module.exports = exports["default"]; /***/ }, /* 319 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = cloneWithRef; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(1); function cloneWithRef(element, newRef) { var previousRef = element.ref; _invariant2['default'](typeof previousRef !== 'string', 'Cannot connect React DnD to an element with an existing string ref. ' + 'Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. ' + 'Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute'); if (!previousRef) { // When there is no ref on the element, use the new ref directly return _react.cloneElement(element, { ref: newRef }); } return _react.cloneElement(element, { ref: function ref(node) { newRef(node); if (previousRef) { previousRef(node); } } }); } module.exports = exports['default']; /***/ }, /* 320 */ /***/ 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 sizerStyle = { position: 'absolute', top: 0, left: 0, visibility: 'hidden', height: 0, overflow: 'scroll', whiteSpace: 'pre' }; var AutosizeInput = React.createClass({ displayName: 'AutosizeInput', propTypes: { className: React.PropTypes.string, // className for the outer element defaultValue: React.PropTypes.any, // default field value inputClassName: React.PropTypes.string, // className for the input element inputStyle: React.PropTypes.object, // css styles for the input element minWidth: React.PropTypes.oneOfType([// minimum width for input element React.PropTypes.number, React.PropTypes.string]), onChange: React.PropTypes.func, // onChange handler: function(newValue) {} placeholder: React.PropTypes.string, // placeholder text placeholderIsMinWidth: React.PropTypes.bool, // don't collapse size to less than the placeholder style: React.PropTypes.object, // css styles for the outer element value: React.PropTypes.any }, // field value getDefaultProps: function getDefaultProps() { return { minWidth: 1 }; }, getInitialState: function getInitialState() { return { inputWidth: this.props.minWidth }; }, componentDidMount: function componentDidMount() { this.copyInputStyles(); this.updateInputWidth(); }, componentDidUpdate: function componentDidUpdate() { this.updateInputWidth(); }, copyInputStyles: function copyInputStyles() { if (!this.isMounted() || !window.getComputedStyle) { return; } var inputStyle = window.getComputedStyle(this.refs.input); if (!inputStyle) { return; } var widthNode = this.refs.sizer; widthNode.style.fontSize = inputStyle.fontSize; widthNode.style.fontFamily = inputStyle.fontFamily; widthNode.style.fontWeight = inputStyle.fontWeight; widthNode.style.fontStyle = inputStyle.fontStyle; widthNode.style.letterSpacing = inputStyle.letterSpacing; if (this.props.placeholder) { var placeholderNode = this.refs.placeholderSizer; placeholderNode.style.fontSize = inputStyle.fontSize; placeholderNode.style.fontFamily = inputStyle.fontFamily; placeholderNode.style.fontWeight = inputStyle.fontWeight; placeholderNode.style.fontStyle = inputStyle.fontStyle; placeholderNode.style.letterSpacing = inputStyle.letterSpacing; } }, updateInputWidth: function updateInputWidth() { if (!this.isMounted() || typeof this.refs.sizer.scrollWidth === 'undefined') { return; } var newInputWidth = undefined; if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) { newInputWidth = Math.max(this.refs.sizer.scrollWidth, this.refs.placeholderSizer.scrollWidth) + 2; } else { newInputWidth = this.refs.sizer.scrollWidth + 2; } if (newInputWidth < this.props.minWidth) { newInputWidth = this.props.minWidth; } if (newInputWidth !== this.state.inputWidth) { this.setState({ inputWidth: newInputWidth }); } }, getInput: function getInput() { return this.refs.input; }, focus: function focus() { this.refs.input.focus(); }, blur: function blur() { this.refs.input.blur(); }, select: function select() { this.refs.input.select(); }, render: function render() { var sizerValue = this.props.defaultValue || this.props.value || ''; var wrapperStyle = this.props.style || {}; if (!wrapperStyle.display) wrapperStyle.display = 'inline-block'; var inputStyle = _extends({}, this.props.inputStyle); inputStyle.width = this.state.inputWidth + 'px'; inputStyle.boxSizing = 'content-box'; var inputProps = _extends({}, this.props); inputProps.className = this.props.inputClassName; inputProps.style = inputStyle; // ensure props meant for `AutosizeInput` don't end up on the `input` delete inputProps.inputClassName; delete inputProps.inputStyle; delete inputProps.minWidth; delete inputProps.placeholderIsMinWidth; return React.createElement( 'div', { className: this.props.className, style: wrapperStyle }, React.createElement('input', _extends({}, inputProps, { ref: 'input' })), React.createElement( 'div', { ref: 'sizer', style: sizerStyle }, sizerValue ), this.props.placeholder ? React.createElement( 'div', { ref: 'placeholderSizer', style: sizerStyle }, this.props.placeholder ) : null ); } }); module.exports = AutosizeInput; /***/ }, /* 321 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; /*eslint-disable react/prop-types */ var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(345); var _warning2 = _interopRequireDefault(_warning); var _componentOrElement = __webpack_require__(107); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _elementType = __webpack_require__(328); var _elementType2 = _interopRequireDefault(_elementType); var _Portal = __webpack_require__(323); var _Portal2 = _interopRequireDefault(_Portal); var _ModalManager = __webpack_require__(322); var _ModalManager2 = _interopRequireDefault(_ModalManager); var _ownerDocument = __webpack_require__(106); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _addEventListener = __webpack_require__(324); var _addEventListener2 = _interopRequireDefault(_addEventListener); var _addFocusListener = __webpack_require__(325); var _addFocusListener2 = _interopRequireDefault(_addFocusListener); var _inDOM = __webpack_require__(14); var _inDOM2 = _interopRequireDefault(_inDOM); var _activeElement = __webpack_require__(171); var _activeElement2 = _interopRequireDefault(_activeElement); var _contains = __webpack_require__(177); var _contains2 = _interopRequireDefault(_contains); var _getContainer = __webpack_require__(105); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var modalManager = new _ModalManager2.default(); /** * Love them or hate them, `<Modal/>` provides a solid foundation for creating dialogs, lightboxes, or whatever else. * The Modal component renders its `children` node in front of a backdrop component. * * The Modal offers a few helpful features over using just a `<Portal/>` component and some styles: * * - Manages dialog stacking when one-at-a-time just isn't enough. * - Creates a backdrop, for disabling interaction below the modal. * - It properly manages focus; moving to the modal content, and keeping it there until the modal is closed. * - It disables scrolling of the page content while open. * - Adds the appropriate ARIA roles are automatically. * - Easily pluggable animations via a `<Transition/>` component. * * Note that, in the same way the backdrop element prevents users from clicking or interacting * with the page content underneath the Modal, Screen readers also need to be signaled to not to * interact with page content while the Modal is open. To do this, we use a common technique of applying * the `aria-hidden='true'` attribute to the non-Modal elements in the Modal `container`. This means that for * a Modal to be truly modal, it should have a `container` that is _outside_ your app's * React hierarchy (such as the default: document.body). */ var Modal = _react2.default.createClass({ displayName: 'Modal', propTypes: _extends({}, _Portal2.default.propTypes, { /** * Set the visibility of the Modal */ show: _react2.default.PropTypes.bool, /** * A Node, Component instance, or function that returns either. The Modal is appended to it's container element. * * For the sake of assistive technologies, the container should usually be the document body, so that the rest of the * page content can be placed behind a virtual backdrop as well as a visual one. */ container: _react2.default.PropTypes.oneOfType([_componentOrElement2.default, _react2.default.PropTypes.func]), /** * A callback fired when the Modal is opening. */ onShow: _react2.default.PropTypes.func, /** * A callback fired when either the backdrop is clicked, or the escape key is pressed. * * The `onHide` callback only signals intent from the Modal, * you must actually set the `show` prop to `false` for the Modal to close. */ onHide: _react2.default.PropTypes.func, /** * Include a backdrop component. */ backdrop: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.bool, _react2.default.PropTypes.oneOf(['static'])]), /** * A function that returns a backdrop component. Useful for custom * backdrop rendering. * * ```js * renderBackdrop={props => <MyBackdrop {...props} />} * ``` */ renderBackdrop: _react2.default.PropTypes.func, /** * A callback fired when the escape key, if specified in `keyboard`, is pressed. */ onEscapeKeyUp: _react2.default.PropTypes.func, /** * A callback fired when the backdrop, if specified, is clicked. */ onBackdropClick: _react2.default.PropTypes.func, /** * A style object for the backdrop component. */ backdropStyle: _react2.default.PropTypes.object, /** * A css class or classes for the backdrop component. */ backdropClassName: _react2.default.PropTypes.string, /** * A css class or set of classes applied to the modal container when the modal is open, * and removed when it is closed. */ containerClassName: _react2.default.PropTypes.string, /** * Close the modal when escape key is pressed */ keyboard: _react2.default.PropTypes.bool, /** * A `<Transition/>` component to use for the dialog and backdrop components. */ transition: _elementType2.default, /** * The `timeout` of the dialog transition if specified. This number is used to ensure that * transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ dialogTransitionTimeout: _react2.default.PropTypes.number, /** * The `timeout` of the backdrop transition if specified. This number is used to * ensure that transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ backdropTransitionTimeout: _react2.default.PropTypes.number, /** * When `true` The modal will automatically shift focus to itself when it opens, and * replace it to the last focused element when it closes. This also * works correctly with any Modal children that have the `autoFocus` prop. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ autoFocus: _react2.default.PropTypes.bool, /** * When `true` The modal will prevent focus from leaving the Modal while open. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ enforceFocus: _react2.default.PropTypes.bool, /** * Callback fired before the Modal transitions in */ onEnter: _react2.default.PropTypes.func, /** * Callback fired as the Modal begins to transition in */ onEntering: _react2.default.PropTypes.func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: _react2.default.PropTypes.func, /** * Callback fired right before the Modal transitions out */ onExit: _react2.default.PropTypes.func, /** * Callback fired as the Modal begins to transition out */ onExiting: _react2.default.PropTypes.func, /** * Callback fired after the Modal finishes transitioning out */ onExited: _react2.default.PropTypes.func, /** * A ModalManager instance used to track and manage the state of open * Modals. Useful when customizing how modals interact within a container */ manager: _react2.default.PropTypes.object.isRequired }), getDefaultProps: function getDefaultProps() { var noop = function noop() {}; return { show: false, backdrop: true, keyboard: true, autoFocus: true, enforceFocus: true, onHide: noop, manager: modalManager, renderBackdrop: function renderBackdrop(props) { return _react2.default.createElement('div', props); } }; }, getInitialState: function getInitialState() { return { exited: !this.props.show }; }, render: function render() { var _props = this.props; var show = _props.show; var container = _props.container; var children = _props.children; var Transition = _props.transition; var backdrop = _props.backdrop; var dialogTransitionTimeout = _props.dialogTransitionTimeout; var className = _props.className; var style = _props.style; var onExit = _props.onExit; var onExiting = _props.onExiting; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var dialog = _react2.default.Children.only(children); var mountModal = show || Transition && !this.state.exited; if (!mountModal) { return null; } var _dialog$props = dialog.props; var role = _dialog$props.role; var tabIndex = _dialog$props.tabIndex; if (role === undefined || tabIndex === undefined) { dialog = (0, _react.cloneElement)(dialog, { role: role === undefined ? 'document' : role, tabIndex: tabIndex == null ? '-1' : tabIndex }); } if (Transition) { dialog = _react2.default.createElement( Transition, { transitionAppear: true, unmountOnExit: true, 'in': show, timeout: dialogTransitionTimeout, onExit: onExit, onExiting: onExiting, onExited: this.handleHidden, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered }, dialog ); } return _react2.default.createElement( _Portal2.default, { ref: this.setMountNode, container: container }, _react2.default.createElement( 'div', { ref: 'modal', role: role || 'dialog', style: style, className: className }, backdrop && this.renderBackdrop(), dialog ) ); }, renderBackdrop: function renderBackdrop() { var _this = this; var _props2 = this.props; var backdropStyle = _props2.backdropStyle; var backdropClassName = _props2.backdropClassName; var renderBackdrop = _props2.renderBackdrop; var Transition = _props2.transition; var backdropTransitionTimeout = _props2.backdropTransitionTimeout; var backdropRef = function backdropRef(ref) { return _this.backdrop = ref; }; var backdrop = _react2.default.createElement('div', { ref: backdropRef, style: this.props.backdropStyle, className: this.props.backdropClassName, onClick: this.handleBackdropClick }); if (Transition) { backdrop = _react2.default.createElement( Transition, { transitionAppear: true, 'in': this.props.show, timeout: backdropTransitionTimeout }, renderBackdrop({ ref: backdropRef, style: backdropStyle, className: backdropClassName, onClick: this.handleBackdropClick }) ); } return backdrop; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.show) { this.setState({ exited: false }); } else if (!nextProps.transition) { // Otherwise let handleHidden take care of marking exited. this.setState({ exited: true }); } }, componentWillUpdate: function componentWillUpdate(nextProps) { if (!this.props.show && nextProps.show) { this.checkForFocus(); } }, componentDidMount: function componentDidMount() { if (this.props.show) { this.onShow(); } }, componentDidUpdate: function componentDidUpdate(prevProps) { var transition = this.props.transition; if (prevProps.show && !this.props.show && !transition) { // Otherwise handleHidden will call this. this.onHide(); } else if (!prevProps.show && this.props.show) { this.onShow(); } }, componentWillUnmount: function componentWillUnmount() { var _props3 = this.props; var show = _props3.show; var transition = _props3.transition; if (show || transition && !this.state.exited) { this.onHide(); } }, onShow: function onShow() { var doc = (0, _ownerDocument2.default)(this); var container = (0, _getContainer2.default)(this.props.container, doc.body); this.props.manager.add(this, container, this.props.containerClassName); this._onDocumentKeyupListener = (0, _addEventListener2.default)(doc, 'keyup', this.handleDocumentKeyUp); this._onFocusinListener = (0, _addFocusListener2.default)(this.enforceFocus); this.focus(); if (this.props.onShow) { this.props.onShow(); } }, onHide: function onHide() { this.props.manager.remove(this); this._onDocumentKeyupListener.remove(); this._onFocusinListener.remove(); this.restoreLastFocus(); }, setMountNode: function setMountNode(ref) { this.mountNode = ref ? ref.getMountNode() : ref; }, handleHidden: function handleHidden() { this.setState({ exited: true }); this.onHide(); if (this.props.onExited) { var _props4; (_props4 = this.props).onExited.apply(_props4, arguments); } }, handleBackdropClick: function handleBackdropClick(e) { if (e.target !== e.currentTarget) { return; } if (this.props.onBackdropClick) { this.props.onBackdropClick(e); } if (this.props.backdrop === true) { this.props.onHide(); } }, handleDocumentKeyUp: function handleDocumentKeyUp(e) { if (this.props.keyboard && e.keyCode === 27 && this.isTopModal()) { if (this.props.onEscapeKeyUp) { this.props.onEscapeKeyUp(e); } this.props.onHide(); } }, checkForFocus: function checkForFocus() { if (_inDOM2.default) { this.lastFocus = (0, _activeElement2.default)(); } }, focus: function focus() { var autoFocus = this.props.autoFocus; var modalContent = this.getDialogElement(); var current = (0, _activeElement2.default)((0, _ownerDocument2.default)(this)); var focusInModal = current && (0, _contains2.default)(modalContent, current); if (modalContent && autoFocus && !focusInModal) { this.lastFocus = current; if (!modalContent.hasAttribute('tabIndex')) { modalContent.setAttribute('tabIndex', -1); (0, _warning2.default)(false, 'The modal content node does not accept focus. ' + 'For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".'); } modalContent.focus(); } }, restoreLastFocus: function restoreLastFocus() { // Support: <=IE11 doesn't support `focus()` on svg elements (RB: #917) if (this.lastFocus && this.lastFocus.focus) { this.lastFocus.focus(); this.lastFocus = null; } }, enforceFocus: function enforceFocus() { var enforceFocus = this.props.enforceFocus; if (!enforceFocus || !this.isMounted() || !this.isTopModal()) { return; } var active = (0, _activeElement2.default)((0, _ownerDocument2.default)(this)); var modal = this.getDialogElement(); if (modal && modal !== active && !(0, _contains2.default)(modal, active)) { modal.focus(); } }, //instead of a ref, which might conflict with one the parent applied. getDialogElement: function getDialogElement() { var node = this.refs.modal; return node && node.lastChild; }, isTopModal: function isTopModal() { return this.props.manager.isTopModal(this); } }); Modal.Manager = _ModalManager2.default; exports.default = Modal; module.exports = exports['default']; /***/ }, /* 322 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _style = __webpack_require__(180); var _style2 = _interopRequireDefault(_style); var _class = __webpack_require__(173); var _class2 = _interopRequireDefault(_class); var _scrollbarSize = __webpack_require__(185); var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize); var _isOverflowing = __webpack_require__(326); var _isOverflowing2 = _interopRequireDefault(_isOverflowing); var _manageAriaHidden = __webpack_require__(327); 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 findIndexOf(arr, cb) { var idx = -1; arr.some(function (d, i) { if (cb(d, i)) { idx = i; return true; } }); return idx; } function findContainer(data, modal) { return findIndexOf(data, function (d) { return d.modals.indexOf(modal) !== -1; }); } function setContainerStyle(state, container) { var style = { overflow: 'hidden' }; // we are only interested in the actual `style` here // becasue we will override it state.style = { overflow: container.style.overflow, paddingRight: container.style.paddingRight }; if (state.overflowing) { // use computed style, here to get the real padding // to add our scrollbar width style.paddingRight = parseInt((0, _style2.default)(container, 'paddingRight') || 0, 10) + (0, _scrollbarSize2.default)() + 'px'; } (0, _style2.default)(container, style); } function removeContainerStyle(_ref, container) { var style = _ref.style; Object.keys(style).forEach(function (key) { return container.style[key] = style[key]; }); } /** * Proper state managment for containers and the modals in those containers. * * @internal Used by the Modal to ensure proper styling of containers. */ var ModalManager = function () { function ModalManager() { var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _ref2$hideSiblingNode = _ref2.hideSiblingNodes; var hideSiblingNodes = _ref2$hideSiblingNode === undefined ? true : _ref2$hideSiblingNode; var _ref2$handleContainer = _ref2.handleContainerOverflow; var handleContainerOverflow = _ref2$handleContainer === undefined ? true : _ref2$handleContainer; _classCallCheck(this, ModalManager); this.hideSiblingNodes = hideSiblingNodes; this.handleContainerOverflow = handleContainerOverflow; this.modals = []; this.containers = []; this.data = []; } _createClass(ModalManager, [{ key: 'add', value: function add(modal, container, className) { var modalIdx = this.modals.indexOf(modal); var containerIdx = this.containers.indexOf(container); if (modalIdx !== -1) { return modalIdx; } modalIdx = this.modals.length; this.modals.push(modal); if (this.hideSiblingNodes) { (0, _manageAriaHidden.hideSiblings)(container, modal.mountNode); } if (containerIdx !== -1) { this.data[containerIdx].modals.push(modal); return modalIdx; } var data = { modals: [modal], //right now only the first modal of a container will have its classes applied classes: className ? className.split(/\s+/) : [], overflowing: (0, _isOverflowing2.default)(container) }; if (this.handleContainerOverflow) { setContainerStyle(data, container); } data.classes.forEach(_class2.default.addClass.bind(null, container)); this.containers.push(container); this.data.push(data); return modalIdx; } }, { key: 'remove', value: function remove(modal) { var modalIdx = this.modals.indexOf(modal); if (modalIdx === -1) { return; } var containerIdx = findContainer(this.data, modal); var data = this.data[containerIdx]; var container = this.containers[containerIdx]; data.modals.splice(data.modals.indexOf(modal), 1); this.modals.splice(modalIdx, 1); // if that was the last modal in a container, // clean up the container if (data.modals.length === 0) { data.classes.forEach(_class2.default.removeClass.bind(null, container)); if (this.handleContainerOverflow) { removeContainerStyle(data, container); } if (this.hideSiblingNodes) { (0, _manageAriaHidden.showSiblings)(container, modal.mountNode); } this.containers.splice(containerIdx, 1); this.data.splice(containerIdx, 1); } else if (this.hideSiblingNodes) { //otherwise make sure the next top modal is visible to a SR (0, _manageAriaHidden.ariaHidden)(false, data.modals[data.modals.length - 1].mountNode); } } }, { key: 'isTopModal', value: function isTopModal(modal) { return !!this.modals.length && this.modals[this.modals.length - 1] === modal; } }]); return ModalManager; }(); exports.default = ModalManager; module.exports = exports['default']; /***/ }, /* 323 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _componentOrElement = __webpack_require__(107); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _ownerDocument = __webpack_require__(106); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _getContainer = __webpack_require__(105); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ var Portal = _react2.default.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: _react2.default.PropTypes.oneOfType([_componentOrElement2.default, _react2.default.PropTypes.func]) }, componentDidMount: function componentDidMount() { this._renderOverlay(); }, componentDidUpdate: function componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = (0, _getContainer2.default)(nextProps.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount: function componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget: function _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); this._portalContainerNode = (0, _getContainer2.default)(this.props.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget: function _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay: function _renderOverlay() { var overlay = !this.props.children ? null : _react2.default.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = _reactDom2.default.unstable_renderSubtreeIntoContainer(this, overlay, this._overlayTarget); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay: function _unrenderOverlay() { if (this._overlayTarget) { _reactDom2.default.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render: function render() { return null; }, getMountNode: function getMountNode() { return this._overlayTarget; }, getOverlayDOMNode: function getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return _reactDom2.default.findDOMNode(this._overlayInstance); } return null; } }); exports.default = Portal; module.exports = exports['default']; /***/ }, /* 324 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (node, event, handler, capture) { (0, _on2.default)(node, event, handler, capture); return { remove: function remove() { (0, _off2.default)(node, event, handler, capture); } }; }; var _on = __webpack_require__(176); var _on2 = _interopRequireDefault(_on); var _off = __webpack_require__(175); var _off2 = _interopRequireDefault(_off); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }, /* 325 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addFocusListener; /** * Firefox doesn't have a focusin event so using capture is easiest way to get bubbling * IE8 can't do addEventListener, but does have onfocusin, so we use that in ie8 * * We only allow one Listener at a time to avoid stack overflows */ function addFocusListener(handler) { var useFocusin = !document.addEventListener; var remove = void 0; if (useFocusin) { document.attachEvent('onfocusin', handler); remove = function remove() { return document.detachEvent('onfocusin', handler); }; } else { document.addEventListener('focus', handler, true); remove = function remove() { return document.removeEventListener('focus', handler, true); }; } return { remove: remove }; } module.exports = exports['default']; /***/ }, /* 326 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isOverflowing; var _isWindow = __webpack_require__(178); var _isWindow2 = _interopRequireDefault(_isWindow); var _ownerDocument = __webpack_require__(36); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isBody(node) { return node && node.tagName.toLowerCase() === 'body'; } function bodyIsOverflowing(node) { var doc = (0, _ownerDocument2.default)(node); var win = (0, _isWindow2.default)(doc); var fullWidth = win.innerWidth; // Support: ie8, no innerWidth if (!fullWidth) { var documentElementRect = doc.documentElement.getBoundingClientRect(); fullWidth = documentElementRect.right - Math.abs(documentElementRect.left); } return doc.body.clientWidth < fullWidth; } function isOverflowing(container) { var win = (0, _isWindow2.default)(container); return win || isBody(container) ? bodyIsOverflowing(container) : container.scrollHeight > container.clientHeight; } module.exports = exports['default']; /***/ }, /* 327 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ariaHidden = ariaHidden; exports.hideSiblings = hideSiblings; exports.showSiblings = showSiblings; var BLACKLIST = ['template', 'script', 'style']; var isHidable = function isHidable(_ref) { var nodeType = _ref.nodeType; var tagName = _ref.tagName; return nodeType === 1 && BLACKLIST.indexOf(tagName.toLowerCase()) === -1; }; var siblings = function siblings(container, mount, cb) { mount = [].concat(mount); [].forEach.call(container.children, function (node) { if (mount.indexOf(node) === -1 && isHidable(node)) { cb(node); } }); }; function ariaHidden(show, node) { if (!node) { return; } if (show) { node.setAttribute('aria-hidden', 'true'); } else { node.removeAttribute('aria-hidden'); } } function hideSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(true, node); }); } function showSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(false, node); }); } /***/ }, /* 328 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(108); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function elementType(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } if (propType !== 'function' && propType !== 'string') { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } return null; } exports.default = (0, _createChainableTypeChecker2.default)(elementType); /***/ }, /* 329 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); 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 _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; }; })(); var _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); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(31); var _Select2 = _interopRequireDefault(_Select); var _utilsStripDiacritics = __webpack_require__(111); var _utilsStripDiacritics2 = _interopRequireDefault(_utilsStripDiacritics); var propTypes = { autoload: _react2['default'].PropTypes.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true cache: _react2['default'].PropTypes.any, // object to use to cache results; set to null/false to disable caching children: _react2['default'].PropTypes.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element ignoreAccents: _react2['default'].PropTypes.bool, // strip diacritics when filtering; defaults to true ignoreCase: _react2['default'].PropTypes.bool, // perform case-insensitive filtering; defaults to true loadingPlaceholder: _react.PropTypes.string.isRequired, // replaces the placeholder while options are loading loadOptions: _react2['default'].PropTypes.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise options: _react.PropTypes.array.isRequired, // array of options placeholder: _react2['default'].PropTypes.oneOfType([// field placeholder, displayed when there's no value (shared with Select) _react2['default'].PropTypes.string, _react2['default'].PropTypes.node]), searchPromptText: _react2['default'].PropTypes.oneOfType([// label to prompt for search input _react2['default'].PropTypes.string, _react2['default'].PropTypes.node]) }; var defaultProps = { autoload: true, cache: {}, children: defaultChildren, ignoreAccents: true, ignoreCase: true, loadingPlaceholder: 'Loading...', options: [], searchPromptText: 'Type to search' }; var Async = (function (_Component) { _inherits(Async, _Component); function Async(props, context) { _classCallCheck(this, Async); _get(Object.getPrototypeOf(Async.prototype), 'constructor', this).call(this, props, context); this.state = { isLoading: false, options: props.options }; this._onInputChange = this._onInputChange.bind(this); } _createClass(Async, [{ key: 'componentDidMount', value: function componentDidMount() { var autoload = this.props.autoload; if (autoload) { this.loadOptions(''); } } }, { key: 'componentWillUpdate', value: function componentWillUpdate(nextProps, nextState) { var _this = this; var propertiesToSync = ['options']; propertiesToSync.forEach(function (prop) { if (_this.props[prop] !== nextProps[prop]) { _this.setState(_defineProperty({}, prop, nextProps[prop])); } }); } }, { key: 'loadOptions', value: function loadOptions(inputValue) { var _this2 = this; var _props = this.props; var cache = _props.cache; var loadOptions = _props.loadOptions; if (cache && cache.hasOwnProperty(inputValue)) { this.setState({ options: cache[inputValue] }); return; } var callback = function callback(error, data) { if (callback === _this2._callback) { _this2._callback = null; var options = data && data.options || []; if (cache) { cache[inputValue] = options; } _this2.setState({ isLoading: false, options: options }); } }; // Ignore all but the most recent request this._callback = callback; var promise = loadOptions(inputValue, callback); if (promise) { promise.then(function (data) { return callback(null, data); }, function (error) { return callback(error); }); } if (this._callback && !this.state.isLoading) { this.setState({ isLoading: true }); } return inputValue; } }, { key: '_onInputChange', value: function _onInputChange(inputValue) { var _props2 = this.props; var ignoreAccents = _props2.ignoreAccents; var ignoreCase = _props2.ignoreCase; if (ignoreAccents) { inputValue = (0, _utilsStripDiacritics2['default'])(inputValue); } if (ignoreCase) { inputValue = inputValue.toLowerCase(); } return this.loadOptions(inputValue); } }, { key: 'render', value: function render() { var _props3 = this.props; var children = _props3.children; var loadingPlaceholder = _props3.loadingPlaceholder; var placeholder = _props3.placeholder; var searchPromptText = _props3.searchPromptText; var _state = this.state; var isLoading = _state.isLoading; var options = _state.options; var props = { noResultsText: isLoading ? loadingPlaceholder : searchPromptText, placeholder: isLoading ? loadingPlaceholder : placeholder, options: isLoading ? [] : options }; return children(_extends({}, this.props, props, { isLoading: isLoading, onInputChange: this._onInputChange })); } }]); return Async; })(_react.Component); exports['default'] = Async; Async.propTypes = propTypes; Async.defaultProps = defaultProps; function defaultChildren(props) { return _react2['default'].createElement(_Select2['default'], props); }; module.exports = exports['default']; /***/ }, /* 330 */ /***/ 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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(31); var _Select2 = _interopRequireDefault(_Select); var AsyncCreatable = _react2['default'].createClass({ displayName: 'AsyncCreatableSelect', render: function render() { var _this = this; return _react2['default'].createElement( _Select2['default'].Async, this.props, function (asyncProps) { return _react2['default'].createElement( _Select2['default'].Creatable, _this.props, function (creatableProps) { return _react2['default'].createElement(_Select2['default'], _extends({}, asyncProps, creatableProps, { onInputChange: function (input) { creatableProps.onInputChange(input); return asyncProps.onInputChange(input); } })); } ); } ); } }); module.exports = AsyncCreatable; /***/ }, /* 331 */ /***/ 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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(31); var _Select2 = _interopRequireDefault(_Select); var _utilsDefaultFilterOptions = __webpack_require__(109); var _utilsDefaultFilterOptions2 = _interopRequireDefault(_utilsDefaultFilterOptions); var _utilsDefaultMenuRenderer = __webpack_require__(110); var _utilsDefaultMenuRenderer2 = _interopRequireDefault(_utilsDefaultMenuRenderer); var Creatable = _react2['default'].createClass({ displayName: 'CreatableSelect', propTypes: { // Child function responsible for creating the inner Select component // This component can be used to compose HOCs (eg Creatable and Async) // (props: Object): PropTypes.element children: _react2['default'].PropTypes.func, // See Select.propTypes.filterOptions filterOptions: _react2['default'].PropTypes.any, // Searches for any matching option within the set of options. // This function prevents duplicate options from being created. // ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean isOptionUnique: _react2['default'].PropTypes.func, // Determines if the current input text represents a valid option. // ({ label: string }): boolean isValidNewOption: _react2['default'].PropTypes.func, // See Select.propTypes.menuRenderer menuRenderer: _react2['default'].PropTypes.any, // Factory to create new option. // ({ label: string, labelKey: string, valueKey: string }): Object newOptionCreator: _react2['default'].PropTypes.func, // See Select.propTypes.options options: _react2['default'].PropTypes.array, // Creates prompt/placeholder option text. // (filterText: string): string promptTextCreator: _react2['default'].PropTypes.func, // Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option. shouldKeyDownEventCreateNewOption: _react2['default'].PropTypes.func }, // Default prop methods statics: { isOptionUnique: isOptionUnique, isValidNewOption: isValidNewOption, newOptionCreator: newOptionCreator, promptTextCreator: promptTextCreator, shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption }, getDefaultProps: function getDefaultProps() { return { filterOptions: _utilsDefaultFilterOptions2['default'], isOptionUnique: isOptionUnique, isValidNewOption: isValidNewOption, menuRenderer: _utilsDefaultMenuRenderer2['default'], newOptionCreator: newOptionCreator, promptTextCreator: promptTextCreator, shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption }; }, createNewOption: function createNewOption() { var _props = this.props; var isValidNewOption = _props.isValidNewOption; var newOptionCreator = _props.newOptionCreator; var _props$options = _props.options; var options = _props$options === undefined ? [] : _props$options; var shouldKeyDownEventCreateNewOption = _props.shouldKeyDownEventCreateNewOption; if (isValidNewOption({ label: this.inputValue })) { var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); var _isOptionUnique = this.isOptionUnique({ option: option }); // Don't add the same option twice. if (_isOptionUnique) { options.unshift(option); this.select.selectValue(option); } } }, filterOptions: function filterOptions() { var _props2 = this.props; var filterOptions = _props2.filterOptions; var isValidNewOption = _props2.isValidNewOption; var options = _props2.options; var promptTextCreator = _props2.promptTextCreator; // TRICKY Check currently selected options as well. // Don't display a create-prompt for a value that's selected. // This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array. var excludeOptions = arguments[2] || []; var filteredOptions = filterOptions.apply(undefined, arguments) || []; if (isValidNewOption({ label: this.inputValue })) { var _newOptionCreator = this.props.newOptionCreator; var option = _newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); // TRICKY Compare to all options (not just filtered options) in case option has already been selected). // For multi-selects, this would remove it from the filtered list. var _isOptionUnique2 = this.isOptionUnique({ option: option, options: excludeOptions.concat(filteredOptions) }); if (_isOptionUnique2) { var _prompt = promptTextCreator(this.inputValue); this._createPlaceholderOption = _newOptionCreator({ label: _prompt, labelKey: this.labelKey, valueKey: this.valueKey }); filteredOptions.unshift(this._createPlaceholderOption); } } return filteredOptions; }, isOptionUnique: function isOptionUnique(_ref2) { var option = _ref2.option; var options = _ref2.options; var isOptionUnique = this.props.isOptionUnique; options = options || this.select.filterOptions(); return isOptionUnique({ labelKey: this.labelKey, option: option, options: options, valueKey: this.valueKey }); }, menuRenderer: function menuRenderer(params) { var menuRenderer = this.props.menuRenderer; return menuRenderer(_extends({}, params, { onSelect: this.onOptionSelect })); }, onInputChange: function onInputChange(input) { // This value may be needed in between Select mounts (when this.select is null) this.inputValue = input; }, onInputKeyDown: function onInputKeyDown(event) { var shouldKeyDownEventCreateNewOption = this.props.shouldKeyDownEventCreateNewOption; var focusedOption = this.select.getFocusedOption(); if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) { this.createNewOption(); // Prevent decorated Select from doing anything additional with this keyDown event event.preventDefault(); } }, onOptionSelect: function onOptionSelect(option, event) { if (option === this._createPlaceholderOption) { this.createNewOption(); } else { this.select.selectValue(option); } }, render: function render() { var _this = this; var _props3 = this.props; var _props3$children = _props3.children; var children = _props3$children === undefined ? defaultChildren : _props3$children; var newOptionCreator = _props3.newOptionCreator; var shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption; var restProps = _objectWithoutProperties(_props3, ['children', 'newOptionCreator', 'shouldKeyDownEventCreateNewOption']); var props = _extends({}, restProps, { allowCreate: true, filterOptions: this.filterOptions, menuRenderer: this.menuRenderer, onInputChange: this.onInputChange, onInputKeyDown: this.onInputKeyDown, ref: function ref(_ref) { _this.select = _ref; // These values may be needed in between Select mounts (when this.select is null) if (_ref) { _this.labelKey = _ref.props.labelKey; _this.valueKey = _ref.props.valueKey; } } }); return children(props); } }); function defaultChildren(props) { return _react2['default'].createElement(_Select2['default'], props); }; function isOptionUnique(_ref3) { var option = _ref3.option; var options = _ref3.options; var labelKey = _ref3.labelKey; var valueKey = _ref3.valueKey; return options.filter(function (existingOption) { return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey]; }).length === 0; }; function isValidNewOption(_ref4) { var label = _ref4.label; return !!label; }; function newOptionCreator(_ref5) { var label = _ref5.label; var labelKey = _ref5.labelKey; var valueKey = _ref5.valueKey; var option = {}; option[valueKey] = label; option[labelKey] = label; option.className = 'Select-create-option-placeholder'; return option; }; function promptTextCreator(label) { return 'Create option "' + label + '"'; } function shouldKeyDownEventCreateNewOption(_ref6) { var keyCode = _ref6.keyCode; switch (keyCode) { case 9: // TAB case 13: // ENTER case 188: // COMMA return true; } return false; }; module.exports = Creatable; /***/ }, /* 332 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var Option = _react2['default'].createClass({ displayName: 'Option', propTypes: { children: _react2['default'].PropTypes.node, className: _react2['default'].PropTypes.string, // className (based on mouse position) instancePrefix: _react2['default'].PropTypes.string.isRequired, // unique prefix for the ids (used for aria) isDisabled: _react2['default'].PropTypes.bool, // the option is disabled isFocused: _react2['default'].PropTypes.bool, // the option is focused isSelected: _react2['default'].PropTypes.bool, // the option is selected onFocus: _react2['default'].PropTypes.func, // method to handle mouseEnter on option element onSelect: _react2['default'].PropTypes.func, // method to handle click on option element onUnfocus: _react2['default'].PropTypes.func, // method to handle mouseLeave on option element option: _react2['default'].PropTypes.object.isRequired, // object that is base for that option optionIndex: _react2['default'].PropTypes.number }, // index of the option, used to generate unique ids for aria blockEvent: function blockEvent(event) { event.preventDefault(); event.stopPropagation(); if (event.target.tagName !== 'A' || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href, event.target.target); } else { window.location.href = event.target.href; } }, handleMouseDown: function handleMouseDown(event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); }, handleMouseEnter: function handleMouseEnter(event) { this.onFocus(event); }, handleMouseMove: function handleMouseMove(event) { this.onFocus(event); }, handleTouchEnd: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; this.handleMouseDown(event); }, handleTouchMove: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; }, onFocus: function onFocus(event) { if (!this.props.isFocused) { this.props.onFocus(this.props.option, event); } }, render: function render() { var _props = this.props; var option = _props.option; var instancePrefix = _props.instancePrefix; var optionIndex = _props.optionIndex; var className = (0, _classnames2['default'])(this.props.className, option.className); return option.disabled ? _react2['default'].createElement( 'div', { className: className, onMouseDown: this.blockEvent, onClick: this.blockEvent }, this.props.children ) : _react2['default'].createElement( 'div', { className: className, style: option.style, role: 'option', onMouseDown: this.handleMouseDown, onMouseEnter: this.handleMouseEnter, onMouseMove: this.handleMouseMove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEnd, id: instancePrefix + '-option-' + optionIndex, title: option.title }, this.props.children ); } }); module.exports = Option; /***/ }, /* 333 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var Value = _react2['default'].createClass({ displayName: 'Value', propTypes: { children: _react2['default'].PropTypes.node, disabled: _react2['default'].PropTypes.bool, // disabled prop passed to ReactSelect id: _react2['default'].PropTypes.string, // Unique id for the value - used for aria onClick: _react2['default'].PropTypes.func, // method to handle click on value label onRemove: _react2['default'].PropTypes.func, // method to handle removal of the value value: _react2['default'].PropTypes.object.isRequired }, // the option object for this value handleMouseDown: function handleMouseDown(event) { if (event.type === 'mousedown' && event.button !== 0) { return; } if (this.props.onClick) { event.stopPropagation(); this.props.onClick(this.props.value, event); return; } if (this.props.value.href) { event.stopPropagation(); } }, onRemove: function onRemove(event) { event.preventDefault(); event.stopPropagation(); this.props.onRemove(this.props.value); }, handleTouchEndRemove: function handleTouchEndRemove(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.onRemove(event); }, handleTouchMove: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; }, renderRemoveIcon: function renderRemoveIcon() { if (this.props.disabled || !this.props.onRemove) return; return _react2['default'].createElement( 'span', { className: 'Select-value-icon', 'aria-hidden': 'true', onMouseDown: this.onRemove, onTouchEnd: this.handleTouchEndRemove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, '×' ); }, renderLabel: function renderLabel() { var className = 'Select-value-label'; return this.props.onClick || this.props.value.href ? _react2['default'].createElement( 'a', { className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown }, this.props.children ) : _react2['default'].createElement( 'span', { className: className, role: 'option', 'aria-selected': 'true', id: this.props.id }, this.props.children ); }, render: function render() { return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])('Select-value', this.props.value.className), style: this.props.value.style, title: this.props.value.title }, this.renderRemoveIcon(), this.renderLabel() ); } }); module.exports = Value; /***/ }, /* 334 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = arrowRenderer; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function arrowRenderer(_ref) { var onMouseDown = _ref.onMouseDown; return _react2["default"].createElement("span", { className: "Select-arrow", onMouseDown: onMouseDown }); } ; module.exports = exports["default"]; /***/ }, /* 335 */ /***/ 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 shallowCompare */ 'use strict'; var shallowEqual = __webpack_require__(186); /** * Does a shallow comparison for props and state. * See ReactComponentWithPureRenderMixin */ function shallowCompare(instance, nextProps, nextState) { return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState); } module.exports = shallowCompare; /***/ }, /* 336 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(112); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 337 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 338 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(54); var _isPlainObject = __webpack_require__(6); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(113); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (false) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (false) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (false) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 339 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(54); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(338); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(337); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(336); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(112); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(113); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (false) { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 340 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.defaultMemoize = defaultMemoize; exports.createSelectorCreator = createSelectorCreator; exports.createStructuredSelector = createStructuredSelector; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function defaultEqualityCheck(a, b) { return a === b; } function defaultMemoize(func) { var equalityCheck = arguments.length <= 1 || arguments[1] === undefined ? defaultEqualityCheck : arguments[1]; var lastArgs = null; var lastResult = null; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (lastArgs === null || lastArgs.length !== args.length || !args.every(function (value, index) { return equalityCheck(value, lastArgs[index]); })) { lastResult = func.apply(undefined, args); } lastArgs = args; return lastResult; }; } function getDependencies(funcs) { var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs; if (!dependencies.every(function (dep) { return typeof dep === 'function'; })) { var dependencyTypes = dependencies.map(function (dep) { return typeof dep; }).join(', '); throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']')); } return dependencies; } function createSelectorCreator(memoize) { for (var _len2 = arguments.length, memoizeOptions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { memoizeOptions[_key2 - 1] = arguments[_key2]; } return function () { for (var _len3 = arguments.length, funcs = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { funcs[_key3] = arguments[_key3]; } var recomputations = 0; var resultFunc = funcs.pop(); var dependencies = getDependencies(funcs); var memoizedResultFunc = memoize.apply(undefined, [function () { recomputations++; return resultFunc.apply(undefined, arguments); }].concat(memoizeOptions)); var selector = function selector(state, props) { for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { args[_key4 - 2] = arguments[_key4]; } var params = dependencies.map(function (dependency) { return dependency.apply(undefined, [state, props].concat(args)); }); return memoizedResultFunc.apply(undefined, _toConsumableArray(params)); }; selector.resultFunc = resultFunc; selector.recomputations = function () { return recomputations; }; selector.resetRecomputations = function () { return recomputations = 0; }; return selector; }; } var createSelector = exports.createSelector = createSelectorCreator(defaultMemoize); function createStructuredSelector(selectors) { var selectorCreator = arguments.length <= 1 || arguments[1] === undefined ? createSelector : arguments[1]; if (typeof selectors !== 'object') { throw new Error('createStructuredSelector expects first argument to be an object ' + ('where each property is a selector, instead received a ' + typeof selectors)); } var objectKeys = Object.keys(selectors); return selectorCreator(objectKeys.map(function (key) { return selectors[key]; }), function () { for (var _len5 = arguments.length, values = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { values[_key5] = arguments[_key5]; } return values.reduce(function (composition, value, index) { composition[objectKeys[index]] = value; return composition; }, {}); }); } /***/ }, /* 341 */ /***/ function(module, exports, __webpack_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(__webpack_require__(1)); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactAutocomplete"] = factory(require("react")); else root["ReactAutocomplete"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { 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 React = __webpack_require__(1); var joinClasses = __webpack_require__(2); var Autocomplete = React.createClass({ displayName: "Autocomplete", propTypes: { options: React.PropTypes.any, search: React.PropTypes.func, resultRenderer: React.PropTypes.oneOfType([React.PropTypes.component, React.PropTypes.func]), value: React.PropTypes.object, onChange: React.PropTypes.func, onError: React.PropTypes.func, onFocus: React.PropTypes.func }, getDefaultProps: function () { return { search: searchArray }; }, getInitialState: function () { var searchTerm = this.props.searchTerm ? this.props.searchTerm : this.props.value ? this.props.value.title : ""; return { results: [], showResults: false, showResultsInProgress: false, searchTerm: searchTerm, focusedValue: null }; }, getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var className = joinClasses(this.props.className, "react-autocomplete-Autocomplete", this.state.showResults ? "react-autocomplete-Autocomplete--resultsShown" : undefined); var style = { position: "relative", outline: "none" }; return React.createElement("div", { tabIndex: "1", className: className, onFocus: this.onFocus, onBlur: this.onBlur, style: style }, React.createElement("input", { ref: "search", className: "react-autocomplete-Autocomplete__search", style: { width: "100%" }, onClick: this.showAllResults, onChange: this.onQueryChange, onFocus: this.onSearchInputFocus, onBlur: this.onQueryBlur, onKeyDown: this.onQueryKeyDown, value: this.state.searchTerm }), React.createElement(Results, { className: "react-autocomplete-Autocomplete__results", onSelect: this.onValueChange, onFocus: this.onValueFocus, results: this.state.results, focusedValue: this.state.focusedValue, show: this.state.showResults, renderer: this.props.resultRenderer, label: this.props.label, resultIdentifier: this.props.resultIdentifier })); }, componentWillReceiveProps: function (nextProps) { var searchTerm = nextProps.searchTerm ? nextProps.searchTerm : nextProps.value ? nextProps.value.title : ""; this.setState({ searchTerm: searchTerm }); }, componentWillMount: function () { this.blurTimer = null; }, /** * Show results for a search term value. * * This method doesn't update search term value itself. * * @param {Search} searchTerm */ showResults: function (searchTerm) { this.setState({ showResultsInProgress: true }); this.props.search(this.props.options, searchTerm.trim(), this.onSearchComplete); }, showAllResults: function () { if (!this.state.showResultsInProgress && !this.state.showResults) { this.showResults(""); } }, onValueChange: function (value) { var state = { value: value, showResults: false }; if (value) { state.searchTerm = value.title; } this.setState(state); if (this.props.onChange) { this.props.onChange(value); } }, onSearchComplete: function (err, results) { if (err) { if (this.props.onError) { this.props.onError(err); } else { throw err; } } this.setState({ showResultsInProgress: false, showResults: true, results: results }); }, onValueFocus: function (value) { this.setState({ focusedValue: value }); }, onQueryChange: function (e) { var searchTerm = e.target.value; this.setState({ searchTerm: searchTerm, focusedValue: null }); this.showResults(searchTerm); }, onFocus: function () { if (this.blurTimer) { clearTimeout(this.blurTimer); this.blurTimer = null; } this.refs.search.getDOMNode().focus(); }, onSearchInputFocus: function () { if (this.props.onFocus) { this.props.onFocus(); } this.showAllResults(); }, onBlur: function () { // wrap in setTimeout so we can catch a click on results this.blurTimer = setTimeout((function () { if (this.isMounted()) { this.setState({ showResults: false }); } }).bind(this), 100); }, onQueryKeyDown: function (e) { if (e.key === "Enter") { e.preventDefault(); if (this.state.focusedValue) { this.onValueChange(this.state.focusedValue); } } else if (e.key === "ArrowUp" && this.state.showResults) { e.preventDefault(); var prevIdx = Math.max(this.focusedValueIndex() - 1, 0); this.setState({ focusedValue: this.state.results[prevIdx] }); } else if (e.key === "ArrowDown") { e.preventDefault(); if (this.state.showResults) { var nextIdx = Math.min(this.focusedValueIndex() + (this.state.showResults ? 1 : 0), this.state.results.length - 1); this.setState({ showResults: true, focusedValue: this.state.results[nextIdx] }); } else { this.showAllResults(); } } }, focusedValueIndex: function () { if (!this.state.focusedValue) { return -1; } for (var i = 0, len = this.state.results.length; i < len; i++) { if (this.getResultIdentifier(this.state.results[i]) === this.getResultIdentifier(this.state.focusedValue)) { return i; } } return -1; } }); var Results = React.createClass({ displayName: "Results", getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { if (!result.id) { throw "id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component"; } return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var style = { display: this.props.show ? "block" : "none", position: "absolute", listStyleType: "none" }; var $__0 = this.props, className = $__0.className, props = (function (source, exclusion) { var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) { throw new TypeError(); }for (var key in source) { if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) { rest[key] = source[key]; } }return rest; })($__0, { className: 1 }); return React.createElement("ul", React.__spread({}, props, { style: style, className: className + " react-autocomplete-Results" }), this.props.results.map(this.renderResult)); }, renderResult: function (result) { var focused = this.props.focusedValue && this.getResultIdentifier(this.props.focusedValue) === this.getResultIdentifier(result); var Renderer = this.props.renderer || Result; return React.createElement(Renderer, { ref: focused ? "focused" : undefined, key: this.getResultIdentifier(result), result: result, focused: focused, onMouseEnter: this.onMouseEnterResult, onClick: this.props.onSelect, label: this.props.label }); }, componentDidUpdate: function () { this.scrollToFocused(); }, componentDidMount: function () { this.scrollToFocused(); }, componentWillMount: function () { this.ignoreFocus = false; }, scrollToFocused: function () { var focused = this.refs && this.refs.focused; if (focused) { var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = focused.getDOMNode(); var top = node.offsetTop; var bottom = top + node.offsetHeight; // we update ignoreFocus to true if we change the scroll position so // the mouseover event triggered because of that won't have an // effect if (top < scroll) { this.ignoreFocus = true; containerNode.scrollTop = top; } else if (bottom - scroll > height) { this.ignoreFocus = true; containerNode.scrollTop = bottom - height; } } }, onMouseEnterResult: function (e, result) { // check if we need to prevent the next onFocus event because it was // probably caused by a mouseover due to scroll position change if (this.ignoreFocus) { this.ignoreFocus = false; } else { // we need to make sure focused node is visible // for some reason mouse events fire on visible nodes due to // box-shadow var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = e.target; var top = node.offsetTop; var bottom = top + node.offsetHeight; if (bottom > scroll && top < scroll + height) { this.props.onFocus(result); } } } }); var Result = React.createClass({ displayName: "Result", getDefaultProps: function () { return { label: function (result) { return result.title; } }; }, getLabel: function (result) { if (typeof this.props.label === "function") { return this.props.label(result); } else if (typeof this.props.label === "string") { return result[this.props.label]; } }, render: function () { var className = joinClasses({ "react-autocomplete-Result": true, "react-autocomplete-Result--active": this.props.focused }); return React.createElement("li", { style: { listStyleType: "none" }, className: className, onClick: this.onClick, onMouseEnter: this.onMouseEnter }, React.createElement("a", null, this.getLabel(this.props.result))); }, onClick: function () { this.props.onClick(this.props.result); }, onMouseEnter: function (e) { if (this.props.onMouseEnter) { this.props.onMouseEnter(e, this.props.result); } }, shouldComponentUpdate: function (nextProps) { return nextProps.result.id !== this.props.result.id || nextProps.focused !== this.props.focused; } }); /** * Search options using specified search term treating options as an array * of candidates. * * @param {Array.<Object>} options * @param {String} searchTerm * @param {Callback} cb */ function searchArray(options, searchTerm, cb) { if (!options) { return cb(null, []); } searchTerm = new RegExp(searchTerm, "i"); var results = []; for (var i = 0, len = options.length; i < len; i++) { if (searchTerm.exec(options[i].title)) { results.push(options[i]); } } cb(null, results); } module.exports = Autocomplete; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ 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__)); } /***/ } /******/ ]) }); ; /***/ }, /* 342 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(343); /***/ }, /* 343 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(344); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root; /* global window */ if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof (window) !== 'undefined') { root = (window); } else if (true) { root = module; } else { root = Function('return this')(); } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }, /* 344 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }, /* 345 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-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. */ 'use strict'; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (false) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ } /******/ ]))) }); ;
/*! 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);
/** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** * The YUI global namespace object. If YUI is already defined, the * existing YUI object will not be overwritten so that defined * namespaces are preserved. It is the constructor for the object * the end user interacts with. As indicated below, each instance * has full custom event support, but only if the event system * is available. This is a self-instantiable factory function. You * can invoke it directly like this: * * YUI().use('*', function(Y) { * // ready * }); * * But it also works like this: * * var Y = YUI(); * * @class YUI * @constructor * @global * @uses EventTarget * @param o* {object} 0..n optional configuration objects. these values * are store in Y.config. See <a href="config.html">Config</a> for the list of supported * properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); // YUI.GlobalConfig is a master configuration that might span // multiple contexts in a non-browser environment. It is applied // first to all instances in all contexts. if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } // YUI_Config is a page-level config. It is applied to all // instances created on the page. This is applied after // YUI.GlobalConfig, and before the instance level configuration // objects. if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.3.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {object} the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, rls = config.rls, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (rls && name == 'rls') { clobber(rls, attr); } else if (name == 'win') { config[name] = attr.contentWindow || attr; config.doc = config[name].document; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** * Old way to apply a config to the instance (calls `applyConfig` under the hood) * @private * @method _config * @param {Object} o The config to apply */ _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private * @method _init */ _init: function() { var filter, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path } } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { win: win, doc: doc, debug: true, useBrowserConsole: true, throwFail: true, bootstrap: true, cacheUse: true, fetchCSS: true, use_rls: false, rls_timeout: 2000 }; if (YUI.Env.rls_disabled) { Y.config.use_rls = false; } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later']; for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); // Y.log(Y.id + ' initialized', 'info', 'yui'); }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {String} the YUI instance id. * @param method {String} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {Object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m.apply(instance, args); } return null; }, /** * Registers a module with the YUI global. The easiest way to create a * first-class YUI module is to use the YUI component build tool. * * http://yuilibrary.com/projects/builder * * The build system will produce the `YUI.add` wrapper for you module, along * with any configuration info required for the module. * @method add * @param name {String} module name. * @param fn {Function} entry point into the module that * is used to bind module to the YUI instance. * @param version {String} version string. * @param details {Object} optional config data: * @param details.requires {Array} features that must be present before this module can be attached. * @param details.optional {Array} optional features that should be present if loadOptional * is defined. Note: modules are not often loaded this way in YUI 3, * but this field is still useful to inform the user that certain * features in the component will require additional dependencies. * @param details.use {Array} features that are included within this module which need to * be attached automatically when this module is attached. This * supports the YUI 3 rollup system -- a module with submodules * defined will need to have the submodules listed in the 'use' * config. The YUI component build tool does this for you. * @return {YUI} the YUI instance. * */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name]) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, done = Y.Env._attached, len = r.length, loader; //console.info('attaching: ' + r, 'info', 'yui'); for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name]) { Y._attach(aliases[name]); continue; } if (!mod) { loader = Y.Env._loader; if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; if (mod.use) { moot = true; } } // Y.log('no js def for: ' + name, 'info', 'yui'); //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot) { if (name.indexOf('skin-') === -1) { Y.Env._missed.push(name); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * * All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * * Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * * Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * * Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @method use * @param modules* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * * @example * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) {}); * * // loads and attaches dd and node as well as all of their dependencies (since 3.4.0) * YUI().use(['dd', 'node'], function(Y) {}); * * // attaches all modules that are available on the page * YUI().use('*', function(Y) {}); * * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) {}); * * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) {}); * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { Y.log('already provisioned: ' + args, 'info', 'yui'); } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { Y.log('already provisioned: ' + args, 'info', 'yui'); } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** * Notify handler from Loader for attachment/load errors * @method _notify * @param callback {Function} The callback to pass to the `Y.config.loadErrorFn` * @param response {Object} The response returned from Loader * @param args {Array} The aruments passed from Loader * @private */ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, /** * This private method is called from the `use` method queue. To ensure that only one set of loading * logic is performed at a time. * @method _use * @private * @param args* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. */ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { if (!names.length) { return; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = false; Y._use(args, function() { Y.log('Nested use callback: ' + data, 'info', 'yui'); if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { // Y.log('attaching from loader: ' + data, 'info', 'yui'); ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui'); // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } // Y.log('before loader requirements: ' + args, 'info', 'yui'); // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui'); } // dynamic load if (boot && len && Y.Loader) { // Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui'); Y.log('Using Loader', 'info', 'yui'); Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); // loader.partial(missing, (fetchCSS) ? null : 'js'); } else if (len && Y.config.use_rls && !YUI.Env.rls_enabled) { G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue(); // server side loader service handleRLS = function(instance, argz) { var rls_end = function(o) { handleLoader(o); instance.rls_advance(); }, rls_url = instance._rls(argz); if (rls_url) { Y.log('Fetching RLS url', 'info', 'rls'); instance.rls_oncomplete(function(o) { rls_end(o); }); instance.Get.script(rls_url, { data: argz, timeout: instance.config.rls_timeout, onFailure: instance.rls_handleFailure, onTimeout: instance.rls_handleTimeout }); } else { rls_end({ data: argz }); } }; G_ENV._rls_queue.add(function() { Y.log('executing queued rls request', 'info', 'rls'); G_ENV._rls_in_progress = true; Y.rls_callback = callback; Y.rls_locals(Y, args, handleRLS); }); if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) { G_ENV._rls_queue.next()(); } } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { Y.log('Waiting for loader', 'info', 'yui'); queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui'); Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { Y.log('Attaching available dependencies: ' + args, 'info', 'yui'); ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** * Returns the namespace specified and creates it if it doesn't exist * * YUI.namespace("property.package"); * YUI.namespace("YAHOO.property.package"); * * Either of the above would create `YUI.property`, then * `YUI.property.package` (`YAHOO` is scrubbed out, this is * to remain compatible with YUI2) * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: * * YUI.namespace("really.long.nested.namespace"); * * This fails because "long" is a future reserved word in ECMAScript * * @method namespace * @param {string*} arguments 1-n namespaces to create. * @return {object} A reference to the last namespace object created. */ namespace: function() { var a = arguments, o = this, i = 0, j, d, arg; for (; i < a.length; i++) { // d = ('' + a[i]).split('.'); arg = a[i]; if (arg.indexOf(PERIOD)) { d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** * Report an error. The reporting mechanism is controled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param data Optional additional info * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, data) { var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error'); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {String} optional guid prefix. * @return {String} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a `guid` associated with an object. If the object * does not have one, a new one is created unless `readOnly` * is specified. * @method stamp * @param o {Object} The object to stamp. * @param readOnly {Boolean} if `true`, a valid guid will only * be returned if the object has one assigned to it. * @return {String} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the `YUI` instance. This object is supplied by the implementer * when instantiating a `YUI` instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * `applyConfig()` to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the `domready` custom event. * * @property injected * @type boolean * @default false */ /** * If `throwFail` is set, `Y.error` will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default). * * @property core * @type string[] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in `DataType.Date.format()` instead. */ /** * The default locale * @property locale * @type string * @deprecated use `config.lang` instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because removing the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?` * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * For dynamic loading. * * @property filter * @type string|object */ /** * The `skin` config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the `use()` method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. See `Loader.addModule` for the supported module * metadata fields. Also see groups, which provides a way to * configure the base and combo spec for a set of modules. * * modules: { * mymod1: { * requires: ['node'], * fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js' * } * } * * @property modules * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. * * groups: { * yui2: { * // specify whether or not this group has a combo service * combine: true, * * // the base path for non-combo paths * base: 'http://yui.yahooapis.com/2.8.0r4/build/', * * // the path to the combo service * comboBase: 'http://yui.yahooapis.com/combo?', * * // a fragment to prepend to the path attribute when * // when building combo urls * root: '2.8.0r4/build/', * * // the module definitions * modules: { * yui2_yde: { * path: "yahoo-dom-event/yahoo-dom-event.js" * }, * yui2_anim: { * path: "animation/animation.js", * requires: ['yui2_yde'] * } * } * } * } * * @property groups * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.8.1 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 1 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * The parameter defaults for the remote loader service. * Requires the rls submodule. The properties that are * supported: * * * `m`: comma separated list of module requirements. This * must be the param name even for custom implemetations. * * `v`: the version of YUI to load. Defaults to the version * of YUI that is being used. * * `gv`: the version of the gallery to load (see the gallery config) * * `env`: comma separated list of modules already on the page. * this must be the param name even for custom implemetations. * * `lang`: the languages supported on the page (see the lang config) * * `'2in3v'`: the version of the 2in3 wrapper to use (see the 2in3 config). * * `'2v'`: the version of yui2 to use in the yui 2in3 wrappers * * `filt`: a filter def to apply to the urls (see the filter config). * * `filts`: a list of custom filters to apply per module * * `tests`: this is a map of conditional module test function id keys * with the values of 1 if the test passes, 0 if not. This must be * the name of the querystring param in custom templates. * * @since 3.2.0 * @property rls */ /** * The base path to the remote loader service * * @since 3.2.0 * @property rls_base */ /** * The template to use for building the querystring portion * of the remote loader service url. The default is determined * by the rls config -- each property that has a value will be * represented. * * @since 3.2.0 * @property rls_tmpl * @example * m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests} * */ /** * Configure the instance to use a remote loader service instead of * the client loader. * * @since 3.2.0 * @property use_rls */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementation. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype); /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = (!unsafeNatives && Array.isArray) || function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * <p> * Returns a string representing the type of the item passed in. * </p> * * <p> * Known issues: * </p> * * <ul> * <li> * <code>typeof HTMLElementCollection</code> returns function in Safari, but * <code>Y.type()</code> reports object, which could be a good thing -- * but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. * </li> * </ul> * * @method type * @param o the item to test. * @return {string} the detected type. * @static */ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * * @module yui * @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Native.indexOf ? function (array, value) { // TODO: support fromIndex return Native.indexOf.call(array, value); } : function (array, value) { for (var i = 0, len = array.length; i < len; ++i) { if (array[i] === value) { return i; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Native.some ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : arg.toString(); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var args = arguments, i = 0, len = args.length, result = {}; for (; i < len; ++i) { Y.mix(result, args[i], true); } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties will not be overwritten or merged unless the _overwrite_ or _merge_ parameters are `true`, respectively. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Int} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a call // to `hasOwnProperty` on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } exists = alwaysOverwrite ? false : hasOwn.call(to, key); if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } exists = alwaysOverwrite ? false : hasOwn.call(to, key); if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var hasOwn = Object.prototype.hasOwnProperty, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementations. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype), UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type {Boolean} * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = (!unsafeNatives && Object.keys) || function (obj) { if (!Y.Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; for (key in obj) { if (owns(obj, key)) { keys.push(key); } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { return O.keys(obj).length; }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Y.Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(obj).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method for parsing the UA string. Defaults to assigning it's value to Y.UA * @static * @method Env.parseUA * @param {String} subUA Parse this UA string instead of navigator.userAgent * @returns {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome o.safari = 0; //Reset safari back to 0 } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } YUI.Env.UA = o; return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["controller","model","model-list","view"], "attribute": ["attribute-base","attribute-complex"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"], "datatype": ["datatype-number","datatype-date","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"] }; }, '@VERSION@' ); YUI.add('get', function(Y) { /** * Provides a mechanism to fetch remote resources and * insert them into a document. * @module yui * @submodule get */ /** * Fetches and inserts one or more script or link nodes into the document * @class Get * @static */ var ua = Y.UA, L = Y.Lang, TYPE_JS = 'text/javascript', TYPE_CSS = 'text/css', STYLESHEET = 'stylesheet', SCRIPT = 'script', AUTOPURGE = 'autopurge', UTF8 = 'utf-8', LINK = 'link', ASYNC = 'async', ALL = true, // FireFox does not support the onload event for link nodes, so // there is no way to make the css requests synchronous. This means // that the css rules in multiple files could be applied out of order // in this browser if a later request returns before an earlier one. // Safari too. ONLOAD_SUPPORTED = { script: ALL, css: !(ua.webkit || ua.gecko) }, /** * hash of queues to manage multiple requests * @property queues * @private */ queues = {}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx = 0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging, /** * Clear timeout state * * @method _clearTimeout * @param {Object} q Queue data * @private */ _clearTimeout = function(q) { var timer = q.timer; if (timer) { clearTimeout(timer); q.timer = null; } }, /** * Generates an HTML element, this is not appended to a document * @method _node * @param {string} type the type of element. * @param {Object} attr the fixed set of attribute for the type. * @param {Object} custAttrs optional Any custom attributes provided by the user. * @param {Window} win optional window to create the element in. * @return {HTMLElement} the generated node. * @private */ _node = function(type, attr, custAttrs, win) { var w = win || Y.config.win, d = w.document, n = d.createElement(type), i; if (custAttrs) { Y.mix(attr, custAttrs); } for (i in attr) { if (attr[i] && attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param {string} url the url for the css file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _linkNode = function(url, win, attributes) { return _node(LINK, { id: Y.guid(), type: TYPE_CSS, rel: STYLESHEET, href: url }, attributes, win); }, /** * Generates a script node * @method _scriptNode * @param {string} url the url for the script file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _scriptNode = function(url, win, attributes) { return _node(SCRIPT, { id: Y.guid(), type: TYPE_JS, src: url }, attributes, win); }, /** * Returns the data payload for callback functions. * @method _returnData * @param {object} q the queue. * @param {string} msg the result message. * @param {string} result the status message from the request. * @return {object} the state data from the request. * @private */ _returnData = function(q, msg, result) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, statusText: result, purge: function() { _purge(this.tId); } }; }, /** * The transaction is finished * @method _end * @param {string} id the id of the request. * @param {string} msg the result message. * @param {string} result the status message from the request. * @private */ _end = function(id, msg, result) { var q = queues[id], onEnd = q && q.onEnd; q.finished = true; if (onEnd) { onEnd.call(q.context, _returnData(q, msg, result)); } }, /** * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param {string} id the id of the request * @private */ _fail = function(id, msg) { Y.log('get failure: ' + msg, 'warn', 'get'); var q = queues[id], onFailure = q.onFailure; _clearTimeout(q); if (onFailure) { onFailure.call(q.context, _returnData(q, msg)); } _end(id, msg, 'failure'); }, /** * Abort the transaction * * @method _abort * @param {Object} id * @private */ _abort = function(id) { _fail(id, 'transaction ' + id + ' was aborted'); }, /** * The request is complete, so executing the requester's callback * @method _complete * @param {string} id the id of the request. * @private */ _complete = function(id) { Y.log("Finishing transaction " + id, "info", "get"); var q = queues[id], onSuccess = q.onSuccess; _clearTimeout(q); if (q.aborted) { _abort(id); } else { if (onSuccess) { onSuccess.call(q.context, _returnData(q)); } // 3.3.0 had undefined msg for this path. _end(id, undefined, 'OK'); } }, /** * Get node reference, from string * * @method _getNodeRef * @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned. * @param {String} tId Queue id, used to determine document for queue * @private */ _getNodeRef = function(nId, tId) { var q = queues[tId], n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, 'target node not found: ' + nId); } return n; }, /** * Removes the nodes for the specified queue * @method _purge * @param {string} tId the transaction id. * @private */ _purge = function(tId) { var nodes, doc, parent, sibling, node, attr, insertBefore, i, l, q = queues[tId]; if (q) { nodes = q.nodes; l = nodes.length; // TODO: Why is node.parentNode undefined? Which forces us to do this... /* doc = q.win.document; parent = doc.getElementsByTagName('head')[0]; insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0]; if (insertBefore) { sibling = _getNodeRef(insertBefore, tId); if (sibling) { parent = sibling.parentNode; } } */ for (i = 0; i < l; i++) { node = nodes[i]; parent = node.parentNode; if (node.clearAttributes) { node.clearAttributes(); } else { // This destroys parentNode ref, so we hold onto it above first. for (attr in node) { if (node.hasOwnProperty(attr)) { delete node[attr]; } } } parent.removeChild(node); } } q.nodes = []; }, /** * Progress callback * * @method _progress * @param {string} id The id of the request. * @param {string} The url which just completed. * @private */ _progress = function(id, url) { var q = queues[id], onProgress = q.onProgress, o; if (onProgress) { o = _returnData(q); o.url = url; onProgress.call(q.context, o); } }, /** * Timeout detected * @method _timeout * @param {string} id the id of the request. * @private */ _timeout = function(id) { Y.log('Timeout ' + id, 'info', 'get'); var q = queues[id], onTimeout = q.onTimeout; if (onTimeout) { onTimeout.call(q.context, _returnData(q)); } _end(id, 'timeout', 'timeout'); }, /** * onload callback * @method _loaded * @param {string} id the id of the request. * @return {string} the result. * @private */ _loaded = function(id, url) { var q = queues[id], sync = (q && !q.async); if (!q) { return; } if (sync) { _clearTimeout(q); } _progress(id, url); // TODO: Cleaning up flow to have a consistent end point // !q.finished check is for the async case, // where scripts may still be loading when we've // already aborted. Ideally there should be a single path // for this. if (!q.finished) { if (q.aborted) { _abort(id); } else { if ((--q.remaining) === 0) { _complete(id); } else if (sync) { _next(id); } } } }, /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _trackLoad * @param {string} type the type of node to track. * @param {HTMLElement} n the node to track. * @param {string} id the id of the request. * @param {string} url the url that is being loaded. * @private */ _trackLoad = function(type, n, id, url) { // TODO: Can we massage this to use ONLOAD_SUPPORTED[type]? // IE supports the readystatechange event for script and css nodes // Opera only for script nodes. Opera support onload for script // nodes, but this doesn't fire when there is a load failure. // The onreadystatechange appears to be a better way to respond // to both success and failure. if (ua.ie) { n.onreadystatechange = function() { var rs = this.readyState; if ('loaded' === rs || 'complete' === rs) { // Y.log(id + " onreadstatechange " + url, "info", "get"); n.onreadystatechange = null; _loaded(id, url); } }; } else if (ua.webkit) { // webkit prior to 3.x is no longer supported if (type === SCRIPT) { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener('load', function() { _loaded(id, url); }, false); } } else { // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link nodes. n.onload = function() { // Y.log(id + " onload " + url, "info", "get"); _loaded(id, url); }; n.onerror = function(e) { _fail(id, e + ': ' + url); }; } }, _insertInDoc = function(node, id, win) { // Add it to the head or insert it before 'insertBefore'. // Work around IE bug if there is a base tag. var q = queues[id], doc = win.document, insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0], sibling; if (insertBefore) { sibling = _getNodeRef(insertBefore, id); if (sibling) { Y.log('inserting before: ' + insertBefore, 'info', 'get'); sibling.parentNode.insertBefore(node, sibling); } } else { // 3.3.0 assumed head is always around. doc.getElementsByTagName('head')[0].appendChild(node); } }, /** * Loads the next item for a given request * @method _next * @param {string} id the id of the request. * @return {string} the result. * @private */ _next = function(id) { // Assigning out here for readability var q = queues[id], type = q.type, attrs = q.attributes, win = q.win, timeout = q.timeout, node, url; if (q.url.length > 0) { url = q.url.shift(); Y.log('attempting to load ' + url, 'info', 'get'); // !q.timer ensures that this only happens once for async if (timeout && !q.timer) { q.timer = setTimeout(function() { _timeout(id); }, timeout); } if (type === SCRIPT) { node = _scriptNode(url, win, attrs); } else { node = _linkNode(url, win, attrs); } // add the node to the queue so we can return it in the callback q.nodes.push(node); _trackLoad(type, node, id, url); _insertInDoc(node, id, win); if (!ONLOAD_SUPPORTED[type]) { _loaded(id, url); } if (q.async) { // For sync, the _next call is chained in _loaded _next(id); } } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (purging) { return; } purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param {string} type the type of node to insert. * @param {string} url the url to load. * @param {object} opts the hash of options for this request. * @return {object} transaction object. * @private */ _queue = function(type, url, opts) { opts = opts || {}; var id = 'q' + (qidx++), thresh = opts.purgethreshold || Y.Get.PURGE_THRESH, q; if (qidx % thresh === 0) { _autoPurge(); } // Merge to protect opts (grandfathered in). q = queues[id] = Y.merge(opts); // Avoid mix, merge overhead. Known set of props. q.tId = id; q.type = type; q.url = url; q.finished = false; q.nodes = []; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || UTF8; if (ASYNC in q && type === SCRIPT) { q.attributes.async = q.async; } q.url = (L.isString(q.url)) ? [q.url] : q.url; // TODO: Do we really need to account for this developer error? // If the url is undefined, this is probably a trailing comma problem in IE. if (!q.url[0]) { q.url.shift(); Y.log('skipping empty url'); } q.remaining = q.url.length; _next(id); return { tId: id }; }; Y.Get = { /** * The number of request required before an automatic purge. * Can be configured via the 'purgethreshold' config * @property PURGE_THRESH * @static * @type int * @default 20 * @private */ PURGE_THRESH: 20, /** * Abort a transaction * @method abort * @static * @param {string|object} o Either the tId or the object returned from * script() or css(). */ abort : function(o) { var id = (L.isString(o)) ? o : o.tId, q = queues[id]; if (q) { Y.log('Aborting ' + id, 'info', 'get'); q.aborted = true; } }, /** * Fetches and inserts one or more script nodes into the head * of the current document or the document in a specified window. * * @method script * @static * @param {string|string[]} url the url or urls to the script(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onTimeout</dt> * <dd> * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onEnd</dt> * <dd>a function that executes when the transaction finishes, * regardless of the exit path</dd> * <dt>onFailure</dt> * <dd> * callback to execute when the script load operation fails * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted successfully</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove any nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading * (useful when passing in an array of js files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> * property, which identifies the file which was loaded.</dd> * <dt>async</dt> * <dd> * <p>When passing in an array of JS files, setting this flag to true * will insert them into the document in parallel, as opposed to the * default behavior, which is to chain load them serially. It will also * set the async attribute on the script node to true.</p> * <p>Setting async:true * will lead to optimal file download performance allowing the browser to * download multiple scripts in parallel, and execute them as soon as they * are available.</p> * <p>Note that async:true does not guarantee execution order of the * scripts being downloaded. They are executed in whichever order they * are received.</p> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>autopurge</dt> * <dd> * setting to true will let the utilities cleanup routine purge * the script once loaded * </dd> * <dt>purgethreshold</dt> * <dd> * The number of transaction before autopurge should be initiated * </dd> * <dt>data</dt> * <dd> * data that is supplied to the callback when the script(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling. * If this is not specified, nodes will be inserted before a base * tag should it exist. Otherwise, the nodes will be appended to the * end of the document head.</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing * the timeout event</dd> * <pre> * &nbsp; Y.Get.script( * &nbsp; ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp; "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], * &nbsp; &#123; * &nbsp; onSuccess: function(o) &#123; * &nbsp; this.log("won't cause error because Y is the context"); * &nbsp; Y.log(o.data); // foo * &nbsp; Y.log(o.nodes.length === 2) // true * &nbsp; // o.purge(); // optionally remove the script nodes * &nbsp; // immediately * &nbsp; &#125;, * &nbsp; onFailure: function(o) &#123; * &nbsp; Y.log("transaction failed"); * &nbsp; &#125;, * &nbsp; onTimeout: function(o) &#123; * &nbsp; Y.log("transaction timed out"); * &nbsp; &#125;, * &nbsp; data: "foo", * &nbsp; timeout: 10000, // 10 second timeout * &nbsp; context: Y, // make the YUI instance * &nbsp; // win: otherframe // target another window/frame * &nbsp; autopurge: true // allow the utility to choose when to * &nbsp; // remove the nodes * &nbsp; purgetheshold: 1 // purge previous transaction before * &nbsp; // next transaction * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ script: function(url, opts) { return _queue(SCRIPT, url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param {string} url the url or urls to the css file(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: * <dl>win</dl> * <dd>the window the link nodes(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers, * where onload for css is detected accurately.</dd> * <dt>async</dt> * <dd>When passing in an array of css files, setting this flag to true will insert them * into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible). * This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>data</dt> * <dd> * data that is supplied to the callbacks when the nodes(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * </dl> * <pre> * Y.Get.css("http://localhost/css/menu.css"); * </pre> * <pre> * &nbsp; Y.Get.css( * &nbsp; ["http://localhost/css/menu.css", * &nbsp; "http://localhost/css/logger.css"], &#123; * &nbsp; insertBefore: 'custom-styles' // nodes will be inserted * &nbsp; // before the specified node * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ css: function(url, opts) { return _queue('css', url, opts); } }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; Y.mix(Y.namespace('Features'), { tests: feature_tests, add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // graphics-svg.js add('load', '0', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // ie-base-test.js add('load', '1', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-vml.js add('load', '2', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // ie-style-test.js add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // transition-test.js add('load', '4', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // 0 add('load', '5', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // autocomplete-list-keys-sniff.js add('load', '6', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-canvas.js add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // dd-gestures-test.js add('load', '8', { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // selector-test.js add('load', '9', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // history-hash-ie-test.js add('load', '10', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : data; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later']}); YUI.add('oop', function(Y) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Applies object properties from the supplier to the receiver. If * the target has the property, and the property is an object, the target * object will be augmented with the supplier's value. If the property * is an array, the suppliers value will be appended to the target. * @method aggregate * @param {function} r the object to receive the augmentation. * @param {function} s the object that supplies the properties to augment. * @param {boolean} ov if true, properties already on the receiver * will be overwritten if found on the supplier. * @param {string[]} wl a whitelist. If supplied, only properties in * this list will be applied to the receiver. * @return {object} the extended object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; Y.mix(Y.namespace('Features'), { tests: feature_tests, add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // graphics-svg.js add('load', '0', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // ie-base-test.js add('load', '1', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-vml.js add('load', '2', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // ie-style-test.js add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // transition-test.js add('load', '4', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // 0 add('load', '5', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // autocomplete-list-keys-sniff.js add('load', '6', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-canvas.js add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // dd-gestures-test.js add('load', '8', { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // selector-test.js add('load', '9', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // history-hash-ie-test.js add('load', '10', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('dom-core', function(Y) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf) { var ancestor = Y_DOM.ancestor.apply(Y_DOM, arguments), ret = (ancestor) ? [ancestor] : []; while ((ancestor = Y_DOM.ancestor(ancestor, fn))) { if (ancestor) { ret.unshift(ancestor); } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS]) { if (Y.UA.opera || needle[NODE_TYPE] === 1) { // IE & SAF contains fail if needle not an ELEMENT_NODE ret = element[CONTAINS](needle); } else { ret = Y_DOM._bruteContains(element, needle); } } else if (element[COMPARE_DOCUMENT_POSITION]) { // gecko if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.alert && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, wrap: function(node, html) { var parent = Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@' ,{requires:['oop','features']}); YUI.add('dom-base', function(Y) { var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } else { Y.log('bad input to setAttribute', 'warn', 'dom'); } }, /** * Provides a normalized attribute interface. * @method getAttibute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } else { Y.log('bad input to getAttribute', 'warn', 'dom'); } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } } } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { Y.log('multiple select normalization not implemented', 'warn', 'DOM'); } else { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { //Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node'); removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification else { Y.log('unable to convert ' + nodes + ' to fragment', 'warn', 'dom'); } return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (where.nodeType) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': nodeParent.insertBefore(newNode, node); break; case 'after': if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } break; default: node.appendChild(newNode); } } } else if (newNode) { node.appendChild(newNode); } return ret; } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = frag.children.tags('tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; } creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Int} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Int} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@' ,{requires:['dom-core']}); YUI.add('dom-style', function(Y) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT]; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { val = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null)[att]; } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('dom-style-ie', function(Y) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { Y.log('getStyle: IE opacity filter not found; returning 1', 'warn', 'dom-style'); } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { Y.log('invalid style value for height: ' + val, 'warn', 'dom-style'); } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { Y.log('invalid style value for width: ' + val, 'warn', 'dom-style'); } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@' ,{requires:['dom-style']}); YUI.add('dom-screen', function(Y) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; Y.log('winHeight returning ' + h, 'info', 'dom-screen'); return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; Y.log('winWidth returning ' + w, 'info', 'dom-screen'); return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; Y.log('docHeight returning ' + h, 'info', 'dom-screen'); return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; Y.log('docWidth returning ' + w, 'info', 'dom-screen'); return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, box, off1, off2, bLeft, bTop, mode, doc, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; rootNode = doc[DOCUMENT_ELEMENT]; // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (Y.UA.ie) { off1 = 2; off2 = 2; mode = doc[COMPAT_MODE]; bLeft = Y_DOM[GET_COMPUTED_STYLE](doc[DOCUMENT_ELEMENT], BORDER_LEFT_WIDTH); bTop = Y_DOM[GET_COMPUTED_STYLE](doc[DOCUMENT_ELEMENT], BORDER_TOP_WIDTH); if (Y.UA.ie === 6) { if (mode !== _BACK_COMPAT) { off1 = 0; off2 = 0; } } if ((mode == _BACK_COMPAT)) { if (bLeft !== MEDIUM) { off1 = parseInt(bLeft, 10); } if (bTop !== MEDIUM) { off2 = parseInt(bTop, 10); } } xy[0] -= off1; xy[1] -= off2; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; } } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Int} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Int} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } Y.log('setXY setting position to ' + xy, 'info', 'dom-screen'); } else { Y.log('setXY failed to set ' + node + ' to ' + xy, 'info', 'dom-screen'); } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Int} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Int} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passes nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance i.e. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node2 The node to get the region from or an Object literal of the region * $param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance i.e. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance i.e. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@' ,{requires:['dom-base', 'dom-style']}); YUI.add('selector-native', function(Y) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _foundCache: [], useNative: true, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } Y.log('query: ' + selector + ' returning: ' + ret.length, 'info', 'Selector'); return (firstOnly) ? (ret[0] || null) : ret; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { var groups = selector.split(','), queries = [], prefix = '', i, len; if (node) { // enforce for element scoping if (node.tagName) { node.id = node.id || Y.guid(); prefix = '[id="' + node.id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { //Y.log('trying native query with: ' + selector, 'info', 'selector-native'); return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available //Y.log('native query error; reverting to brute query with: ' + selector, 'info', 'selector-native'); return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { Y.log('invalid filter input (nodes: ' + nodes + ', selector: ' + selector + ')', 'warn', 'Selector'); } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; if (!node.id) { node.id = Y.guid(); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + node.id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('selector', function(Y) { }, '@VERSION@' ,{requires:['selector-native']}); YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property Do.originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property Do.currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ onceAfter: function() { var args = YArray(arguments, 0, true); args[0] = AFTER_PREFIX + args[0]; return this.once.apply(this, args); }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {string} type the type * @param {string} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('drag:drophit', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']}); YUI.add('event-custom-complex', function(Y) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property type * @type string */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.extend(Y.EventFacade, Object, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; if (self.stoppedFn) { events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } // if (subCount) { if (subs[0]) { // self._procSubs(Y.merge(self.subscribers), args, ef); self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; // self.bubbling = true; es.bubbling = self.type; // if (host !== ef.target || es.type != self.type) { if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); // self.bubbling = false; es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, o2, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { o2 = {}; // protect the event facade properties Y.mix(o2, ef, true, FACADE_KEYS); // mix the data Y.mix(ef, o, true); // restore ef Y.mix(ef, o2, true, FACADE_KEYS); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } this.events.fire('stopped', this); }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } this.events.fire('stopped', this); }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { // Y.log('Bubbling ' + evt.type); for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = Y.Object.keys(FACADE); }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('node-core', function(Y) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Y.Node || HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Y.Node | Y.NodeList | any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && Y.instanceOf(args[0], Y_Node)) { args[0] = args[0]._node; } if (args[1] && Y.instanceOf(args[1], Y_Node)) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { Y.log('unable to add method: ' + name, 'warn', 'Node'); } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Y.Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Y.Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (Y.instanceOf(refNode, Y_Node)) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf) { return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf)); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf) { return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf)); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a Node instance of nodes based on the given CSS selector. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node} A Node instance for the matching HTMLElement. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Y.Node || HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && Y.instanceOf(a, Y_Node)) { a = a._node; } if (b && Y.instanceOf(b, Y_Node)) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, /** * @method getData * @description Retrieves arbitrary data stored on a Node instance. * This is not stored with the DOM node. * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { var ret; this._data = this._data || {}; if (arguments.length) { ret = this._data[name]; } else { ret = this._data; } return ret; }, /** * @method setData * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._data = this._data || {}; if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @description Clears stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (name) { delete this._data[name]; } else { delete this._data; } } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor */ var NodeList = function(nodes) { var tmp = []; if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (Y.instanceOf(nodes, Y.Node)) { nodes = [nodes._node]; } else if (Y.instanceOf(nodes[0], Y.Node)) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {Y.NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { Y.log('no nodes bound to ' + this, 'warn', 'NodeList'); } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { Y.log('unable to add method: ' + name + ' to NodeList', 'warn', 'node'); } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return Node a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Y.Node || DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** * Applies an event listener to each Node bound to the NodeList. * @method on * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @param {Object} context The context to call the handler with. * param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** Called on each Node instance * @method destroy * @see Node.destroy */ 'destroy', /** Called on each Node instance * @method empty * @see Node.empty */ 'empty', /** Called on each Node instance * @method remove * @see Node.remove */ 'remove', /** Called on each Node instance * @method set * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the first last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ 'removeAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.log('adding: ' + method, 'info', 'node'); Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@' ,{requires:['dom-core', 'selector']}); YUI.add('node-base', function(Y) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Y.Node | HTMLElement | Y.NodeList | HTMLCollection} content The content to insert * @param {Int | Y.Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Y.Node | HTMLElement} content The content to insert * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Y.Node | HTMLElement} content The content to insert * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Y.Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * @method setContent * @param {String | Y.Node | HTMLElement | Y.NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** Called on each Node instance * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** Called on each Node instance * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** Called on each Node instance * @method prepend * @see Node.prepend */ 'prepend', /** Called on each Node instance * @method setContent * @see Node.setContent */ 'setContent', /** Called on each Node instance * @method getContent * @see Node.getContent */ 'getContent' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i][TAG_NAME]) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** * Applies an event listener to each Node bound to the NodeList. * @method on * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @param {Object} context The context to call the handler with. * param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on * @for NodeList */ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll */ 'detachAll' ]); Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, toggleView: function(on, callback) { this._toggleView.apply(this, arguments); }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { Y.log('error focusing node: ' + e.toString(), 'error', 'node'); } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { Y.log('error setting type: ' + val, 'info', 'node'); } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } }, '@VERSION@' ,{requires:['dom-base', 'node-core', 'event-base']}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function(Y) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event */ /** * The X location of the event on the page (including scroll) * @property pageX * @type int */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type int */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type int */ /** * The charCode for key events. Same as keyCode * @property charCode * @type int */ /** * The button that was pushed. * @property button * @type int */ /** * The button that was pushed. Same as button. * @property which * @type int */ /** * Node reference for the targeted element * @propery target * @type Node */ /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type int */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert); } catch(ex) { Y.log("collection check failure", "warn", "event"); return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.subCount && !this.afterCount) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; // Y.log('onAvailable registered for: ' + id); for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); Y.log(type + " attach call failed, invalid callback", "error", "event"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { // Y.log(el + ' not found'); ret = Event.onAvailable(el, function() { // Y.log('lazy attach: ' + args); ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { Y.log("unable to attach event " + type, "warn", "event"); return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return Y.DOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { // Y.log('Load Complete', 'info', 'event'); _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // Y.log.debug("poll"); // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // Y.log('avail: ' + el); executeItem(el, item); _avail[i] = null; } else { // Y.log('NOT avail: ' + el); notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); i = 0; len = children.length; for (; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } add(win, "unload", onUnload); Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); })(); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('pluginhost-base', function(Y) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config this[ns].setAttrs(config); } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } else { Y.log("Attempt to plug in an invalid plugin. Host:" + this + ", Plugin:" + Plugin); } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namepsace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { this[ns].destroy(); delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {boolean} returns true, if the plugin has been plugged into this host, false otherwise. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('pluginhost-config', function(Y) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method Plugin.Host.plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method Plugin.Host.unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@' ,{requires:['pluginhost-base']}); YUI.add('event-delegate', function(Y) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param spec {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, context, filter, ...); // and Y.delegate(['click', 'key'], fn, context, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, context, filter) => // Y.delegate('click', fn, context, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { Y.log("delegate requires type, callback, parent, & filter", "warn"); return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** * Overrides the <code>_notify</code> method on the normal DOM subscription to * inject the filtering logic and only proceed in the case of a match. * * @method delegate.notifySub * @param thisObj {Object} default 'this' object for the callback * @param args {Array} arguments passed to the event's <code>fire()</code> * @param ce {CustomEvent} the custom event managing the DOM subscriptions for * the subscribed event on the subscribing node. * @return {Boolean} false if the event was stopped * @private * @static * @since 3.2.0 */ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** * <p>Compiles a selector string into a filter function to identify whether * Nodes along the parent axis of an event's target should trigger event * notification.</p> * * <p>This function is memoized, so previously compiled filter functions are * returned if the same selector string is provided.</p> * * <p>This function may be useful when defining synthetic events for delegate * handling.</p> * * @method delegate.compileFilter * @param selector {String} the selector string to base the filtration on * @return {Function} * @since 3.2.0 * @static */ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, e.currentTarget._node); }; }); /** * Walks up the parent axis of an event's target, and tests each element * against a supplied filter function. If any Nodes, including the container, * satisfy the filter, the delegated callback will be triggered for each. * * @method delegate._applyFilter * @param filter {Function} boolean function to test for inclusion in event * notification * @param args {Array} the arguments that would be passed to subscribers * @param ce {CustomEvent} the DOM event wrapper * @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter * @protected */ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ?null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('node-event-delegate', function(Y) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@' ,{requires:['node-base', 'event-delegate']}); YUI.add('node-pluginhost', function(Y) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); }; Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); }; }, '@VERSION@' ,{requires:['node-base', 'pluginhost']}); YUI.add('node-screen', function(Y) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config winHeight * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { Y.log('unable to set scrollLeft for ' + node, 'error', 'Node'); } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { Y.log('unable to set scrollTop for ' + node, 'error', 'Node'); } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Y.Node || HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@' ,{requires:['node-base', 'dom-screen']}); YUI.add('node-style', function(Y) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ var methods = [ /** * Returns the style's current value. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ 'getStyle', /** * Returns the computed value for the given style property. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ 'getComputedStyle', /** * Sets a style property of the node. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ 'setStyle', /** * Sets multiple style properties on the node. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ 'setStyles' ]; Y.Node.importMethod(Y.DOM, methods); /** * Returns an array of values for each node. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); })(Y); }, '@VERSION@' ,{requires:['dom-style', 'node-base']}); YUI.add('querystring-stringify-simple', function(Y) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple * @for QueryString * @static */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; /** * <p>Converts a simple object to a Query String representation.</p> * <p>Nested objects, Arrays, and so on, are not supported.</p> * * @method stringify * @for QueryString * @public * @submodule querystring-stringify-simple * @param obj {Object} A single-level object to convert to a querystring. * @param cfg {Object} (optional) Configuration object. In the simple * module, only the arrayKey setting is * supported. When set to true, the key of an * array will have the '[]' notation appended * to the key;. * @static */ QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('io-base', function(Y) { /** * Base IO functionality. Provides basic XHR transport support. * @module io * @submodule io-base */ // Window reference var L = Y.Lang, // List of events that comprise the IO event lifecycle. E = ['start', 'complete', 'end', 'success', 'failure'], // Whitelist of used XHR response object properties. P = ['status', 'statusText', 'responseText', 'responseXML'], aH = 'getAllResponseHeaders', oH = 'getResponseHeader', w = Y.config.win, xhr = w.XMLHttpRequest, xdr = w.XDomainRequest, _i = 0; /** * The io class is a utility that brokers HTTP requests through a simplified * interface. Specifically, it allows JavaScript to make HTTP requests to * a resource without a page reload. The underlying transport for making * same-domain requests is the XMLHttpRequest object. YUI.io can also use * Flash, if specified as a transport, for cross-domain requests. * * @class IO * @constructor * @param {object} c - Object of EventTarget's publish method configurations * used to configure IO's events. */ function IO (c) { var io = this; io._uid = 'io:' + _i++; io._init(c); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * @description A counter that increments for each transaction. * * @property _id * @private * @type int */ _id: 0, /** * @description Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type object */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * @description Object that stores timeout values for any transaction with * a defined "timeout" configuration property. * * @property _timeout * @private * @type object */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(c) { var io = this, i; io.cfg = c || {}; Y.augment(io, Y.EventTarget); for (i = 0; i < 5; i++) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + E[i], Y.merge({ broadcast: 1 }, c)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + E[i], c); } }, /** * @description Method that creates a unique transaction object for each * request. * * @method _create * @private * @param {number} c - configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {number} i - transaction id * @return object */ _create: function(c, i) { var io = this, o = { id: L.isNumber(i) ? i : io._id++, uid: io._uid }, x = c.xdr, u = x ? x.use : c.form && c.form.upload ? 'iframe' : 'xhr', ie = (x && x.use === 'native' && xdr), t = io._transport; switch (u) { case 'native': case 'xhr': o.c = ie ? new xdr() : xhr ? new xhr() : new ActiveXObject('Microsoft.XMLHTTP'); o.t = ie ? true : false; break; default: o.c = t ? t[u] : {}; o.t = true; } return o; }, _destroy: function(o) { if (w) { if (xhr && o.t === true) { o.c.onreadystatechange = null; } else if (Y.UA.ie) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". o.c.abort(); } } o.c = null; o = null; }, /** * @description Method for creating and firing events. * * @method _evt * @private * @param {string} e - event to be published. * @param {object} o - transaction object. * @param {object} c - configuration data subset for event subscription. * * @return void */ _evt: function(e, o, c) { var io = this, a = c['arguments'], eF = io.cfg.emitFacade, // Use old-style parameters or use an Event Facade p = eF ? [{ id: o.id, data: o.c, cfg: c, arguments: a }] : [o.id], // IO Global events namespace. gE = "io:" + e, // IO Transaction events namespace. tE = "io-trn:" + e; if (!eF) { if (e === E[0] || e === E[2]) { if (a) { p.push(a); } } else { a ? p.push(o.c, a) : p.push(o.c); } } p.unshift(gE); io.fire.apply(io, p); if (c.on) { p[0] = tE; io.once(tE, c.on[e], c.context || Y); io.fire.apply(io, p); } }, /** * @description Fires event "io:start" and creates, fires a * transaction-specific start event, if config.on.start is * defined. * * @method start * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ start: function(o, c) { this._evt(E[0], o, c); }, /** * @description Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ complete: function(o, c) { this._evt(E[1], o, c); }, /** * @description Fires event "io:end" and creates, fires a * transaction-specific "end" event, if config.on.end is * defined. * * @method end * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ end: function(o, c) { this._evt(E[2], o, c); this._destroy(o); }, /** * @description Fires event "io:success" and creates, fires a * transaction-specific "success" event, if config.on.success is * defined. * * @method success * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ success: function(o, c) { this._evt(E[3], o, c); this.end(o, c); }, /** * @description Fires event "io:failure" and creates, fires a * transaction-specific "failure" event, if config.on.failure is * defined. * * @method failure * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ failure: function(o, c) { this._evt(E[4], o, c); this.end(o, c); }, /** * @description Retry an XDR transaction, using the Flash tranport, * if the native transport fails. * * @method _retry * @private * @param {object} o - Transaction object generated by _create(). * @param {string} uri - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * * @return void */ _retry: function(o, uri, c) { this._destroy(o); c.xdr.use = 'flash'; return this.send(uri, c, o.id); }, /** * @description Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {string} s - URI or root data. * @param {string} d - data to be concatenated onto URI. * @return int */ _concat: function(s, d) { s += (s.indexOf('?') === -1 ? '?' : '&') + d; return s; }, /** * @description Method that stores default client headers for all transactions. * If a label is passed with no value argument, the header will be deleted. * * @method _setHeader * @private * @param {string} l - HTTP header * @param {string} v - HTTP header value * @return int */ setHeader: function(l, v) { if (v) { this._headers[l] = v; } else { delete this._headers[l]; } }, /** * @description Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {object} o - XHR instance for the specific transaction. * @param {object} h - HTTP headers for the specific transaction, as defined * in the configuration object passed to YUI.io(). * @return void */ _setHeaders: function(o, h) { h = Y.merge(this._headers, h); Y.Object.each(h, function(v, p) { if (v !== 'disable') { o.setRequestHeader(p, h[p]); } }); }, /** * @description Starts timeout count if the configuration object * has a defined timeout property. * * @method _startTimeout * @private * @param {object} o - Transaction object generated by _create(). * @param {object} t - Timeout in milliseconds. * @return void */ _startTimeout: function(o, t) { var io = this; io._timeout[o.id] = w.setTimeout(function() { io._abort(o, 'timeout'); }, t); }, /** * @description Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {number} id - Transaction id. * @return void */ _clearTimeout: function(id) { w.clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * @description Method that determines if a transaction response qualifies * as success or failure, based on the response HTTP status code, and * fires the appropriate success or failure events. * * @method _result * @private * @static * @param {object} o - Transaction object generated by _create(). * @param {object} c - Configuration object passed to io(). * @return void */ _result: function(o, c) { var s = o.c.status; // IE reports HTTP 204 as HTTP 1223. if (s >= 200 && s < 300 || s === 1223) { this.success(o, c); } else { this.failure(o, c); } }, /** * @description Event handler bound to onreadystatechange. * * @method _rS * @private * @param {object} o - Transaction object generated by _create(). * @param {object} c - Configuration object passed to YUI.io(). * @return void */ _rS: function(o, c) { var io = this; if (o.c.readyState === 4) { if (c.timeout) { io._clearTimeout(o.id); } // Yield in the event of request timeout or abort. w.setTimeout(function() { io.complete(o, c); io._result(o, c); }, 0); } }, /** * @description Terminates a transaction due to an explicit abort or * timeout. * * @method _abort * @private * @param {object} o - Transaction object generated by _create(). * @param {string} s - Identifies timed out or aborted transaction. * * @return void */ _abort: function(o, s) { if (o && o.c) { o.e = s; o.c.abort(); } }, /** * @description Method for requesting a transaction. send() is implemented as * yui.io(). Each transaction may include a configuration object. Its * properties are: * * method: HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET. * * data: This is the name-value string that will be sent as the transaction * data. If the request is HTTP GET, the data become part of * querystring. If HTTP POST, the data are sent in the message body. * * xdr: Defines the transport to be used for cross-domain requests. By * setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. * The properties are: * { * use: Specify the transport to be used: 'flash' and 'native' * dataType: Set the value to 'XML' if that is the expected * response content type. * } * * * form: This is a defined object used to process HTML form as data. The * properties are: * { * id: Node object or id of HTML form. * useDisabled: Boolean value to allow disabled HTML form field * values to be sent as part of the data. * } * * on: This is a defined object used to create and handle specific * events during a transaction lifecycle. These events will fire in * addition to the global io events. The events are: * start - This event is fired when a request is sent to a resource. * complete - This event fires when the transaction is complete. * success - This event fires when the response status resolves to * HTTP 2xx. * failure - This event fires when the response status resolves to * HTTP 4xx, 5xx; and, for all transaction exceptions, * including aborted transactions and transaction timeouts. * end - This even is fired at the conclusion of the transaction * lifecycle, after a success or failure resolution. * * The properties are: * { * start: function(id, arguments){}, * complete: function(id, responseobject, arguments){}, * success: function(id, responseobject, arguments){}, * failure: function(id, responseobject, arguments){}, * end: function(id, arguments){} * } * Each property can reference a function or be written as an * inline function. * * sync: To enable synchronous transactions, set the configuration property * "sync" to true. Synchronous requests are limited to same-domain * requests only. * * context: Object reference for all defined transaction event handlers * when it is implemented as a method of a base object. Defining * "context" will set the reference of "this," used in the * event handlers, to the context value. In the case where * different event handlers all have different contexts, * use Y.bind() to set the execution context, instead. * * headers: This is a defined object of client headers, as many as * desired for this specific transaction. The object pattern is: * { 'header': 'value' }. * * timeout: This value, defined as milliseconds, is a time threshold for the * transaction. When this threshold is reached, and the transaction's * Complete event has not yet fired, the transaction will be aborted. * * arguments: User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" * and "end" event handlers. It is the third argument in the * "complete", "success", and "failure" event handlers. * * @method send * @private * @ * @param {string} uri - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * @param {number} i - transaction id, if already set. * @return object */ send: function(uri, c, i) { var o, m, r, s, d, io = this, u = uri; c = c ? Y.Object(c) : {}; o = io._create(c, i); m = c.method ? c.method.toUpperCase() : 'GET'; s = c.sync; d = c.data; // Serialize an object into a key-value string using // querystring-stringify-simple. if (L.isObject(d)) { d = Y.QueryString.stringify(d); } if (c.form) { if (c.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(o, uri, c); } else { // Serialize HTML form data into a key-value string. d = io._serialize(c.form, d); } } if (d) { switch (m) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, d); d = ''; Y.log('HTTP' + m + ' with data. The querystring is: ' + u, 'info', 'io'); break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' c.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, c.headers); break; } } if (o.t) { // Cross-domain request or custom transport configured. return io.xdr(u, o, c); } if (!s) { o.c.onreadystatechange = function() { io._rS(o, c); }; } try { // Determine if request is to be set as // synchronous or asynchronous. o.c.open(m, u, s ? false : true, c.username || null, c.password || null); io._setHeaders(o.c, c.headers || {}); io.start(o, c); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (c.xdr && c.xdr.credentials) { if (!Y.UA.ie) { o.c.withCredentials = true; } } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. o.c.send(d); if (s) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. r = Y.mix({ id: o.id, 'arguments': c['arguments'] }, o.c, false, P); r[aH] = function() { return o.c[aH](); }; r[oH] = function(h) { return o.c[oH](h); }; io.complete(o, c); io._result(o, c); return r; } } catch(e) { if (o.t) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(o, uri, c); } else { io.complete(o, c); io._result(o, c); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (c.timeout) { io._startTimeout(o, c.timeout); Y.log('Configuration timeout set to: ' + c.timeout, 'info', 'io'); } return { id: o.id, abort: function() { return o.c ? io._abort(o, 'abort') : false; }, isInProgress: function() { return o.c ? o.c.readyState !== 4 && o.c.readyState !== 0 : false; }, io: io }; } }; /** * @description Method for requesting a transaction. * * @method io * @public * @static * @param {string} u - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * @return object */ Y.io = function(u, c) { // Calling IO through the static interface will use and reuse // an instance of IO. var o = Y.io._map['io:0'] || new IO(); return o.send.apply(o, [u, c]); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; }, '@VERSION@' ,{requires:['event-custom-base', 'querystring-stringify-simple']}); YUI.add('json-parse', function(Y) { /** * <p>The JSON module adds support for serializing JavaScript objects into * JSON strings and parsing JavaScript objects from strings in JSON format.</p> * * <p>The JSON namespace is added to your YUI instance including static methods * Y.JSON.parse(..) and Y.JSON.stringify(..).</p> * * <p>The functionality and method signatures follow the ECMAScript 5 * specification. In browsers with native JSON support, the native * implementation is used.</p> * * <p>The <code>json</code> module is a rollup of <code>json-parse</code> and * <code>json-stringify</code>.</p> * * <p>As their names suggest, <code>json-parse</code> adds support for parsing * JSON data (Y.JSON.parse) and <code>json-stringify</code> for serializing * JavaScript data into JSON strings (Y.JSON.stringify). You may choose to * include either of the submodules individually if you don't need the * complementary functionality, or include the rollup for both.</p> * * @module json * @class JSON * @static */ /** * Provides Y.JSON.parse method to accept JSON strings and return native * JavaScript objects. * * @module json * @submodule json-parse * @for JSON * @static */ // All internals kept private for security reasons function fromGlobal(ref) { return (Y.config.win || this || {})[ref]; } /** * Alias to native browser implementation of the JSON object if available. * * @property Native * @type {Object} * @private */ var _JSON = fromGlobal('JSON'), Native = (Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON), useNative = !!Native, /** * Replace certain Unicode characters that JavaScript may handle incorrectly * during eval--either by deleting them or treating them as line * endings--with escape sequences. * IMPORTANT NOTE: This regex will be used to modify the input if a match is * found. * * @property _UNICODE_EXCEPTIONS * @type {RegExp} * @private */ _UNICODE_EXCEPTIONS = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, /** * First step in the safety evaluation. Regex used to replace all escape * sequences (i.e. "\\", etc) with '@' characters (a non-JSON character). * * @property _ESCAPES * @type {RegExp} * @private */ _ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, /** * Second step in the safety evaluation. Regex used to replace all simple * values with ']' characters. * * @property _VALUES * @type {RegExp} * @private */ _VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, /** * Third step in the safety evaluation. Regex used to remove all open * square brackets following a colon, comma, or at the beginning of the * string. * * @property _BRACKETS * @type {RegExp} * @private */ _BRACKETS = /(?:^|:|,)(?:\s*\[)+/g, /** * Final step in the safety evaluation. Regex used to test the string left * after all previous replacements for invalid characters. * * @property _UNSAFE * @type {RegExp} * @private */ _UNSAFE = /[^\],:{}\s]/, /** * Replaces specific unicode characters with their appropriate \unnnn * format. Some browsers ignore certain characters during eval. * * @method escapeException * @param c {String} Unicode character * @return {String} the \unnnn escapement of the character * @private */ _escapeException = function (c) { return '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4); }, /** * Traverses nested objects, applying a reviver function to each (key,value) * from the scope if the key:value's containing object. The value returned * from the function will replace the original value in the key:value pair. * If the value returned is undefined, the key will be omitted from the * returned object. * * @method _revive * @param data {MIXED} Any JavaScript data * @param reviver {Function} filter or mutation function * @return {MIXED} The results of the filtered data * @private */ _revive = function (data, reviver) { var walk = function (o,key) { var k,v,value = o[key]; if (value && typeof value === 'object') { for (k in value) { if (value.hasOwnProperty(k)) { v = walk(value, k); if (v === undefined) { delete value[k]; } else { value[k] = v; } } } } return reviver.call(o,key,value); }; return typeof reviver === 'function' ? walk({'':data},'') : data; }, /** * Parse a JSON string, returning the native JavaScript representation. * * @param s {string} JSON string data * @param reviver {function} (optional) function(k,v) passed each key value * pair of object literals, allowing pruning or altering values * @return {MIXED} the native JavaScript representation of the JSON string * @throws SyntaxError * @method parse * @static */ // JavaScript implementation in lieu of native browser support. Based on // the json2.js library from http://json.org _parse = function (s,reviver) { // Replace certain Unicode characters that are otherwise handled // incorrectly by some browser implementations. // NOTE: This modifies the input if such characters are found! s = s.replace(_UNICODE_EXCEPTIONS, _escapeException); // Test for any remaining invalid characters if (!_UNSAFE.test(s.replace(_ESCAPES,'@'). replace(_VALUES,']'). replace(_BRACKETS,''))) { // Eval the text into a JavaScript data structure, apply any // reviver function, and return return _revive( eval('(' + s + ')'), reviver ); } throw new SyntaxError('JSON.parse'); }; Y.namespace('JSON').parse = function (s,reviver) { if (typeof s !== 'string') { s += ''; } return Native && Y.JSON.useNativeParse ? Native.parse(s,reviver) : _parse(s,reviver); }; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( Native ) { try { useNative = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { useNative = false; } } /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeParse * @type Boolean * @default true * @static */ Y.JSON.useNativeParse = useNative; }, '@VERSION@' ); YUI.add('transition', function(Y) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', TRANSITION = 'transition', TRANSITION_CAMEL = 'Transition', TRANSITION_PROPERTY_CAMEL, TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, TRANSFORM_CAMEL, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + TRANSITION_CAMEL; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + TRANSITION_CAMEL; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; TRANSFORM_CAMEL = CAMEL_VENDOR_PREFIX + 'Transform'; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration != 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay != 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[TRANSFORM_CAMEL]) { config[TRANSFORM_CAMEL] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; //anim._node.fire('transition:start', data); if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur); return dur + 's'; }, _runNative: function(time) { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { //anim._detach = Y.on(TRANSITION_END, anim._onNativeEnd, node); //node[ON_TRANSITION_END] = anim._onNativeEnd; node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } //setTimeout(function() { // allow updates to apply (size fix, onstart, etc) style.cssText += transitionText + duration + easing + delay + cssText; //}, 1); }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } //node.fire('transition:end', data); } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); } } }, destroy: function() { var anim = this, node = anim._node; /* if (anim._detach) { anim._detach.detach(); } */ //anim._node[ON_TRANSITION_END] = null; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } else if (name && !Y.Transition) { Y.log('unable to transition show; missing transition module', 'warn', 'node'); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback) { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else if (name && !Y.Transition) { Y.log('unable to transition hide; missing transition module', 'warn', 'node'); // end if on nex } else { this._hide(); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name == 'boolean') { // no transition, just toggle on = name; name = null; } name = name || Y.Transition.DEFAULT_TOGGLE; if (typeof on == 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).toggleView(name, on, callback); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); Transition.DEFAULT_TOGGLE = 'fade'; }, '@VERSION@' ,{requires:['node-style']}); YUI.add('selector-css2', function(Y) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /** * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, // TODO: move? SORT_RESULTS: true, _children: function(node, tag) { var ret = node.children, i, children = [], childNodes, child; if (node.children && tag && node.children.tags) { children = node.children.tags(tag); } else if ((!ret && node[TAG_NAME]) || (ret && tag)) { // only HTMLElements have children childNodes = ret || node.childNodes; ret = []; for (i = 0; (child = childNodes[i++]);) { if (child.tagName) { if (!tag || tag === child.tagName) { ret.push(child); } } } } return ret || []; }, _re: { attr: /(\[[^\]]*\])/g, esc: /\\[:\[\]\(\)#\.\'\>+~"]/gi, pseudos: /(\([^\)]*\))/g }, /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute //'': '.+', //'=': '^{val}$', // equality '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.Selector._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; // if we have an initial ID, set to root when in document /* if (tokens[0] && rootDoc === root && (id = tokens[0].id) && rootDoc.getElementById(id)) { root = rootDoc.getElementById(id); } */ if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) // TODO: move to allById? if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName('*') child = root.firstChild; while (child) { if (child.tagName) { // only collect HTMLElements nodes.push(child); } child = child.nextSilbing || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, //FUNCTION = 'function', value, tests, test; //do { for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; // use getAttribute for non-standard attributes if (value === undefined && tmpNode.getAttribute) { value = tmpNode.getAttribute(test[0]); } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } }// while (tmpNode = node = nodes[++i]); node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1].toUpperCase(); token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /** Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._replaceShorthand(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector'); tokens = []; } return tokens; }, _replaceShorthand: function(selector) { var shorthand = Selector.shorthand, esc = selector.match(Selector._re.esc), // pull escaped colon, brackets, etc. attrs, pseudos, re, i, len; if (esc) { selector = selector.replace(Selector._re.esc, '\uE000'); } attrs = selector.match(Selector._re.attr); pseudos = selector.match(Selector._re.pseudos); if (attrs) { selector = selector.replace(Selector._re.attr, '\uE001'); } if (pseudos) { selector = selector.replace(Selector._re.pseudos, '\uE002'); } for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } if (attrs) { for (i = 0, len = attrs.length; i < len; ++i) { selector = selector.replace(/\uE001/, attrs[i]); } } if (pseudos) { for (i = 0, len = pseudos.length; i < len; ++i) { selector = selector.replace(/\uE002/, pseudos[i]); } } selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); if (esc) { for (i = 0, len = esc.length; i < len; ++i) { selector = selector.replace('\uE000', esc[i]); } } return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@' ,{requires:['selector-native']}); YUI.add('selector-css3', function(Y) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.Selector._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.Selector._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.Selector._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.Selector._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.Selector._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.Selector._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@' ,{requires:['selector-native', 'selector-css2']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('dump', function(Y) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@' ); YUI.add('transition-timer', function(Y) { /* * The Transition Utility provides an API for creating advanced transitions. * @module transition */ /* * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@' ,{requires:['transition']}); YUI.add('simpleyui', function(Y) { // empty }, '@VERSION@' ,{use:['yui','oop','dom','event-custom-base','event-base','pluginhost','node','event-delegate','io-base','json-parse','transition','selector-css3','dom-style-ie','querystring-stringify-simple']}); var Y = YUI().use('*');
'use strict'; module.exports = { app: { title: 'Joshua Wilborn - Full Stack Engineer', description: 'Full-Stack Engineer Joshua Wilborn and Projects', keywords: 'mongodb, express, angularjs, node.js, mongoose, passport, resume, projects, whotweet, whotweet?, react', googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID' }, db: { promise: global.Promise }, port: process.env.PORT || 3000, host: process.env.HOST || '0.0.0.0', // DOMAIN config should be set to the fully qualified application accessible // URL. For example: https://www.myapp.com (including port if required). domain: process.env.DOMAIN, // Session Cookie settings sessionCookie: { // session expiration is set by default to 24 hours maxAge: 24 * (60 * 60 * 1000), // httpOnly flag makes sure the cookie is only accessed // through the HTTP protocol and not JS/browser httpOnly: true, // secure cookie should be turned to true to provide additional // layer of security so that the cookie is set only when working // in HTTPS mode. secure: false }, // sessionSecret should be changed for security measures and concerns sessionSecret: process.env.SESSION_SECRET || 'MEAN', // sessionKey is the cookie session name sessionKey: 'sessionId', sessionCollection: 'sessions', // Lusca config csrf: { csrf: false, csp: false, xframe: 'SAMEORIGIN', p3p: 'ABCDEF', xssProtection: true }, logo: 'modules/core/client/img/brand/logo.png', favicon: 'modules/core/client/img/brand/favicon.ico', illegalUsernames: ['meanjs', 'administrator', 'password', 'admin', 'user', 'unknown', 'anonymous', 'null', 'undefined', 'api' ], uploads: { profile: { image: { dest: './modules/users/client/img/profile/uploads/', limits: { fileSize: 1 * 1024 * 1024 // Max file size in bytes (1 MB) } } } }, shared: { owasp: { allowPassphrases: true, maxLength: 128, minLength: 10, minPhraseLength: 20, minOptionalTestsToPass: 4 } } };
/*! jQuery v2.1.4 | (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=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,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=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.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},n.extend=n.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||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},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=s(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(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;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=s(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&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=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);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(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&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.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?n.extend(a,d):d}},e={};return d.pipe=d.then,n.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&&n.isFunction(a.promise)?e:0,g=1===f?a:n.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]&&n.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;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(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};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){ return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.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.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.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 L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.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=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!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(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.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=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.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(g in a)this.on(g,b,c,a[g],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=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.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,n(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=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ia={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,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=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=ja(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=ja(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?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(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,n.cleanData(oa(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,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qa[0].contentDocument,b.write(),b.close(),c=sa(a,b),qa.detach()),ra[a]=c),c}var ua=/^margin/,va=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wa=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};function xa(a,b,c){var d,e,f,g,h=a.style;return c=c||wa(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),va.test(g)&&ua.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}function ya(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.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",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),f.removeChild(c),b}})}}(),n.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 za=/^(none|table(?!-c[ea]).+)/,Aa=new RegExp("^("+Q+")(.*)$","i"),Ba=new RegExp("^([+-])=("+Q+")","i"),Ca={position:"absolute",visibility:"hidden",display:"block"},Da={letterSpacing:"0",fontWeight:"400"},Ea=["Webkit","O","Moz","ms"];function Fa(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Ea.length;while(e--)if(b=Ea[e]+c,b in a)return b;return d}function Ga(a,b,c){var d=Aa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Ha(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+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ia(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wa(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xa(a,b,f),(0>e||null==e)&&(e=a.style[b]),va.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Ha(a,b,c||(g?"border":"content"),d,f)+"px"}function Ja(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",ta(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.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}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xa(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":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fa(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Ba.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.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))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fa(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xa(a,b,d)),"normal"===e&&b in Da&&(e=Da[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?za.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Ca,function(){return Ia(a,b,d)}):Ia(a,b,d):void 0},set:function(a,c,d){var e=d&&wa(a);return Ga(a,c,d?Ha(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=ya(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ua.test(a)||(n.cssHooks[a+b].set=Ga)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wa(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Ja(this,!0)},hide:function(){return Ja(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Ka(a,b,c,d,e){return new Ka.prototype.init(a,b,c,d,e)}n.Tween=Ka,Ka.prototype={constructor:Ka,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||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ka.propHooks[this.prop];return a&&a.get?a.get(this):Ka.propHooks._default.get(this)},run:function(a){var b,c=Ka.propHooks[this.prop];return this.options.duration?this.pos=b=n.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):Ka.propHooks._default.set(this),this}},Ka.prototype.init.prototype=Ka.prototype,Ka.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Ka.propHooks.scrollTop=Ka.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Ka.prototype.init,n.fx.step={};var La,Ma,Na=/^(?:toggle|show|hide)$/,Oa=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pa=/queueHooks$/,Qa=[Va],Ra={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Oa.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Oa.exec(n.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,n.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 Sa(){return setTimeout(function(){La=void 0}),La=n.now()}function Ta(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ua(a,b,c){for(var d,e=(Ra[b]||[]).concat(Ra["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Va(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||ta(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Na.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?ta(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ua(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wa(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.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 Xa(a,b,c){var d,e,f=0,g=Qa.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=La||Sa(),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:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:La||Sa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.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(Wa(k,j.opts.specialEasing);g>f;f++)if(d=Qa[f].call(j,a,k,j.opts))return d;return n.map(k,Ua,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.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)}n.Animation=n.extend(Xa,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Ra[c]=Ra[c]||[],Ra[c].unshift(b)},prefilter:function(a,b){b?Qa.unshift(a):Qa.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xa(this,n.extend({},a),f);(e||L.get(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=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pa.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)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.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})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Ta(b,!0),a,d,e)}}),n.each({slideDown:Ta("show"),slideUp:Ta("hide"),slideToggle:Ta("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(La=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),La=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ma||(Ma=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Ma),Ma=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.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=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Ya,Za,$a=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Za:Ya)), void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.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 n.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=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Za={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.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||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.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){return a.hasAttribute("tabindex")||_a.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ab=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.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(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(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(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.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&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.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 cb=n.now(),db=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var eb=/#.*$/,fb=/([?&])_=[^&]*/,gb=/^(.*?):[ \t]*([^\r\n]*)$/gm,hb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,ib=/^(?:GET|HEAD)$/,jb=/^\/\//,kb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,lb={},mb={},nb="*/".concat("*"),ob=a.location.href,pb=kb.exec(ob.toLowerCase())||[];function qb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function rb(a,b,c,d){var e={},f=a===mb;function g(h){var i;return e[h]=!0,n.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 sb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function tb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function ub(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}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ob,type:"GET",isLocal:hb.test(pb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":nb,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?sb(sb(a,n.ajaxSettings),b):sb(n.ajaxSettings,a)},ajaxPrefilter:qb(lb),ajaxTransport:qb(mb),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=gb.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e: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 c&&c.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||ob)+"").replace(eb,"").replace(jb,pb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=kb.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===pb[1]&&h[2]===pb[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(pb[3]||("http:"===pb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),rb(lb,k,b,v),2===t)return v;i=n.event&&k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!ib.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(db.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=fb.test(d)?d.replace(fb,"$1_="+cb++):d+(db.test(d)?"&":"?")+"_="+cb++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(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]?", "+nb+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=rb(mb,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=tb(k,v,f)),u=ub(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=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,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var vb=/%20/g,wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&").replace(vb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Bb=0,Cb={},Db={0:200,1223:204},Eb=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Cb)Cb[a]()}),k.cors=!!Eb&&"withCredentials"in Eb,k.ajax=Eb=!!Eb,n.ajaxTransport(function(a){var b;return k.cors||Eb&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Bb;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)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Cb[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Db[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Cb[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Fb=[],Gb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Fb.pop()||n.expando+"_"+cb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Gb.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Gb,"$1"+e):b.jsonp!==!1&&(b.url+=(db.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.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,Fb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Hb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Hb)return Hb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Ib=a.document.documentElement;function Jb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Jb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Ib;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ib})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Jb(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=ya(k.pixelPosition,function(a,c){return c?(c=xa(a,b),va.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.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?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Kb=a.jQuery,Lb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Lb),b&&a.jQuery===n&&(a.jQuery=Kb),n},typeof b===U&&(a.jQuery=a.$=n),n}); // Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])<u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e<arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this); (function(t){var e=typeof self=="object"&&self.self==self&&self||typeof global=="object"&&global.global==global&&global;if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,n){e.Backbone=t(e,n,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore"),r;try{r=require("jquery")}catch(n){}t(e,exports,i,r)}else{e.Backbone=t(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}})(function(t,e,i,r){var n=t.Backbone;var s=Array.prototype.slice;e.VERSION="1.2.3";e.$=r;e.noConflict=function(){t.Backbone=n;return this};e.emulateHTTP=false;e.emulateJSON=false;var a=function(t,e,r){switch(t){case 1:return function(){return i[e](this[r])};case 2:return function(t){return i[e](this[r],t)};case 3:return function(t,n){return i[e](this[r],h(t,this),n)};case 4:return function(t,n,s){return i[e](this[r],h(t,this),n,s)};default:return function(){var t=s.call(arguments);t.unshift(this[r]);return i[e].apply(i,t)}}};var o=function(t,e,r){i.each(e,function(e,n){if(i[n])t.prototype[n]=a(e,n,r)})};var h=function(t,e){if(i.isFunction(t))return t;if(i.isObject(t)&&!e._isModel(t))return u(t);if(i.isString(t))return function(e){return e.get(t)};return t};var u=function(t){var e=i.matches(t);return function(t){return e(t.attributes)}};var l=e.Events={};var c=/\s+/;var f=function(t,e,r,n,s){var a=0,o;if(r&&typeof r==="object"){if(n!==void 0&&"context"in s&&s.context===void 0)s.context=n;for(o=i.keys(r);a<o.length;a++){e=f(t,e,o[a],r[o[a]],s)}}else if(r&&c.test(r)){for(o=r.split(c);a<o.length;a++){e=t(e,o[a],n,s)}}else{e=t(e,r,n,s)}return e};l.on=function(t,e,i){return d(this,t,e,i)};var d=function(t,e,i,r,n){t._events=f(v,t._events||{},e,i,{context:r,ctx:t,listening:n});if(n){var s=t._listeners||(t._listeners={});s[n.id]=n}return t};l.listenTo=function(t,e,r){if(!t)return this;var n=t._listenId||(t._listenId=i.uniqueId("l"));var s=this._listeningTo||(this._listeningTo={});var a=s[n];if(!a){var o=this._listenId||(this._listenId=i.uniqueId("l"));a=s[n]={obj:t,objId:n,id:o,listeningTo:s,count:0}}d(t,e,r,this,a);return this};var v=function(t,e,i,r){if(i){var n=t[e]||(t[e]=[]);var s=r.context,a=r.ctx,o=r.listening;if(o)o.count++;n.push({callback:i,context:s,ctx:s||a,listening:o})}return t};l.off=function(t,e,i){if(!this._events)return this;this._events=f(g,this._events,t,e,{context:i,listeners:this._listeners});return this};l.stopListening=function(t,e,r){var n=this._listeningTo;if(!n)return this;var s=t?[t._listenId]:i.keys(n);for(var a=0;a<s.length;a++){var o=n[s[a]];if(!o)break;o.obj.off(e,r,this)}if(i.isEmpty(n))this._listeningTo=void 0;return this};var g=function(t,e,r,n){if(!t)return;var s=0,a;var o=n.context,h=n.listeners;if(!e&&!r&&!o){var u=i.keys(h);for(;s<u.length;s++){a=h[u[s]];delete h[a.id];delete a.listeningTo[a.objId]}return}var l=e?[e]:i.keys(t);for(;s<l.length;s++){e=l[s];var c=t[e];if(!c)break;var f=[];for(var d=0;d<c.length;d++){var v=c[d];if(r&&r!==v.callback&&r!==v.callback._callback||o&&o!==v.context){f.push(v)}else{a=v.listening;if(a&&--a.count===0){delete h[a.id];delete a.listeningTo[a.objId]}}}if(f.length){t[e]=f}else{delete t[e]}}if(i.size(t))return t};l.once=function(t,e,r){var n=f(p,{},t,e,i.bind(this.off,this));return this.on(n,void 0,r)};l.listenToOnce=function(t,e,r){var n=f(p,{},e,r,i.bind(this.stopListening,this,t));return this.listenTo(t,n)};var p=function(t,e,r,n){if(r){var s=t[e]=i.once(function(){n(e,s);r.apply(this,arguments)});s._callback=r}return t};l.trigger=function(t){if(!this._events)return this;var e=Math.max(0,arguments.length-1);var i=Array(e);for(var r=0;r<e;r++)i[r]=arguments[r+1];f(m,this._events,t,void 0,i);return this};var m=function(t,e,i,r){if(t){var n=t[e];var s=t.all;if(n&&s)s=s.slice();if(n)_(n,r);if(s)_(s,[e].concat(r))}return t};var _=function(t,e){var i,r=-1,n=t.length,s=e[0],a=e[1],o=e[2];switch(e.length){case 0:while(++r<n)(i=t[r]).callback.call(i.ctx);return;case 1:while(++r<n)(i=t[r]).callback.call(i.ctx,s);return;case 2:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a);return;case 3:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a,o);return;default:while(++r<n)(i=t[r]).callback.apply(i.ctx,e);return}};l.bind=l.on;l.unbind=l.off;i.extend(e,l);var y=e.Model=function(t,e){var r=t||{};e||(e={});this.cid=i.uniqueId(this.cidPrefix);this.attributes={};if(e.collection)this.collection=e.collection;if(e.parse)r=this.parse(r,e)||{};r=i.defaults({},r,i.result(this,"defaults"));this.set(r,e);this.changed={};this.initialize.apply(this,arguments)};i.extend(y.prototype,l,{changed:null,validationError:null,idAttribute:"id",cidPrefix:"c",initialize:function(){},toJSON:function(t){return i.clone(this.attributes)},sync:function(){return e.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return i.escape(this.get(t))},has:function(t){return this.get(t)!=null},matches:function(t){return!!i.iteratee(t,this)(this.attributes)},set:function(t,e,r){if(t==null)return this;var n;if(typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r||(r={});if(!this._validate(n,r))return false;var s=r.unset;var a=r.silent;var o=[];var h=this._changing;this._changing=true;if(!h){this._previousAttributes=i.clone(this.attributes);this.changed={}}var u=this.attributes;var l=this.changed;var c=this._previousAttributes;for(var f in n){e=n[f];if(!i.isEqual(u[f],e))o.push(f);if(!i.isEqual(c[f],e)){l[f]=e}else{delete l[f]}s?delete u[f]:u[f]=e}this.id=this.get(this.idAttribute);if(!a){if(o.length)this._pending=r;for(var d=0;d<o.length;d++){this.trigger("change:"+o[d],this,u[o[d]],r)}}if(h)return this;if(!a){while(this._pending){r=this._pending;this._pending=false;this.trigger("change",this,r)}}this._pending=false;this._changing=false;return this},unset:function(t,e){return this.set(t,void 0,i.extend({},e,{unset:true}))},clear:function(t){var e={};for(var r in this.attributes)e[r]=void 0;return this.set(e,i.extend({},t,{unset:true}))},hasChanged:function(t){if(t==null)return!i.isEmpty(this.changed);return i.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?i.clone(this.changed):false;var e=this._changing?this._previousAttributes:this.attributes;var r={};for(var n in t){var s=t[n];if(i.isEqual(e[n],s))continue;r[n]=s}return i.size(r)?r:false},previous:function(t){if(t==null||!this._previousAttributes)return null;return this._previousAttributes[t]},previousAttributes:function(){return i.clone(this._previousAttributes)},fetch:function(t){t=i.extend({parse:true},t);var e=this;var r=t.success;t.success=function(i){var n=t.parse?e.parse(i,t):i;if(!e.set(n,t))return false;if(r)r.call(t.context,e,i,t);e.trigger("sync",e,i,t)};z(this,t);return this.sync("read",this,t)},save:function(t,e,r){var n;if(t==null||typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r=i.extend({validate:true,parse:true},r);var s=r.wait;if(n&&!s){if(!this.set(n,r))return false}else{if(!this._validate(n,r))return false}var a=this;var o=r.success;var h=this.attributes;r.success=function(t){a.attributes=h;var e=r.parse?a.parse(t,r):t;if(s)e=i.extend({},n,e);if(e&&!a.set(e,r))return false;if(o)o.call(r.context,a,t,r);a.trigger("sync",a,t,r)};z(this,r);if(n&&s)this.attributes=i.extend({},h,n);var u=this.isNew()?"create":r.patch?"patch":"update";if(u==="patch"&&!r.attrs)r.attrs=n;var l=this.sync(u,this,r);this.attributes=h;return l},destroy:function(t){t=t?i.clone(t):{};var e=this;var r=t.success;var n=t.wait;var s=function(){e.stopListening();e.trigger("destroy",e,e.collection,t)};t.success=function(i){if(n)s();if(r)r.call(t.context,e,i,t);if(!e.isNew())e.trigger("sync",e,i,t)};var a=false;if(this.isNew()){i.defer(t.success)}else{z(this,t);a=this.sync("delete",this,t)}if(!n)s();return a},url:function(){var t=i.result(this,"urlRoot")||i.result(this.collection,"url")||F();if(this.isNew())return t;var e=this.get(this.idAttribute);return t.replace(/[^\/]$/,"$&/")+encodeURIComponent(e)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(t){return this._validate({},i.defaults({validate:true},t))},_validate:function(t,e){if(!e.validate||!this.validate)return true;t=i.extend({},this.attributes,t);var r=this.validationError=this.validate(t,e)||null;if(!r)return true;this.trigger("invalid",this,r,i.extend(e,{validationError:r}));return false}});var b={keys:1,values:1,pairs:1,invert:1,pick:0,omit:0,chain:1,isEmpty:1};o(y,b,"attributes");var x=e.Collection=function(t,e){e||(e={});if(e.model)this.model=e.model;if(e.comparator!==void 0)this.comparator=e.comparator;this._reset();this.initialize.apply(this,arguments);if(t)this.reset(t,i.extend({silent:true},e))};var w={add:true,remove:true,merge:true};var E={add:true,remove:false};var k=function(t,e,i){i=Math.min(Math.max(i,0),t.length);var r=Array(t.length-i);var n=e.length;for(var s=0;s<r.length;s++)r[s]=t[s+i];for(s=0;s<n;s++)t[s+i]=e[s];for(s=0;s<r.length;s++)t[s+n+i]=r[s]};i.extend(x.prototype,l,{model:y,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return e.sync.apply(this,arguments)},add:function(t,e){return this.set(t,i.extend({merge:false},e,E))},remove:function(t,e){e=i.extend({},e);var r=!i.isArray(t);t=r?[t]:i.clone(t);var n=this._removeModels(t,e);if(!e.silent&&n)this.trigger("update",this,e);return r?n[0]:n},set:function(t,e){if(t==null)return;e=i.defaults({},e,w);if(e.parse&&!this._isModel(t))t=this.parse(t,e);var r=!i.isArray(t);t=r?[t]:t.slice();var n=e.at;if(n!=null)n=+n;if(n<0)n+=this.length+1;var s=[];var a=[];var o=[];var h={};var u=e.add;var l=e.merge;var c=e.remove;var f=false;var d=this.comparator&&n==null&&e.sort!==false;var v=i.isString(this.comparator)?this.comparator:null;var g;for(var p=0;p<t.length;p++){g=t[p];var m=this.get(g);if(m){if(l&&g!==m){var _=this._isModel(g)?g.attributes:g;if(e.parse)_=m.parse(_,e);m.set(_,e);if(d&&!f)f=m.hasChanged(v)}if(!h[m.cid]){h[m.cid]=true;s.push(m)}t[p]=m}else if(u){g=t[p]=this._prepareModel(g,e);if(g){a.push(g);this._addReference(g,e);h[g.cid]=true;s.push(g)}}}if(c){for(p=0;p<this.length;p++){g=this.models[p];if(!h[g.cid])o.push(g)}if(o.length)this._removeModels(o,e)}var y=false;var b=!d&&u&&c;if(s.length&&b){y=this.length!=s.length||i.some(this.models,function(t,e){return t!==s[e]});this.models.length=0;k(this.models,s,0);this.length=this.models.length}else if(a.length){if(d)f=true;k(this.models,a,n==null?this.length:n);this.length=this.models.length}if(f)this.sort({silent:true});if(!e.silent){for(p=0;p<a.length;p++){if(n!=null)e.index=n+p;g=a[p];g.trigger("add",g,this,e)}if(f||y)this.trigger("sort",this,e);if(a.length||o.length)this.trigger("update",this,e)}return r?t[0]:t},reset:function(t,e){e=e?i.clone(e):{};for(var r=0;r<this.models.length;r++){this._removeReference(this.models[r],e)}e.previousModels=this.models;this._reset();t=this.add(t,i.extend({silent:true},e));if(!e.silent)this.trigger("reset",this,e);return t},push:function(t,e){return this.add(t,i.extend({at:this.length},e))},pop:function(t){var e=this.at(this.length-1);return this.remove(e,t)},unshift:function(t,e){return this.add(t,i.extend({at:0},e))},shift:function(t){var e=this.at(0);return this.remove(e,t)},slice:function(){return s.apply(this.models,arguments)},get:function(t){if(t==null)return void 0;var e=this.modelId(this._isModel(t)?t.attributes:t);return this._byId[t]||this._byId[e]||this._byId[t.cid]},at:function(t){if(t<0)t+=this.length;return this.models[t]},where:function(t,e){return this[e?"find":"filter"](t)},findWhere:function(t){return this.where(t,true)},sort:function(t){var e=this.comparator;if(!e)throw new Error("Cannot sort a set without a comparator");t||(t={});var r=e.length;if(i.isFunction(e))e=i.bind(e,this);if(r===1||i.isString(e)){this.models=this.sortBy(e)}else{this.models.sort(e)}if(!t.silent)this.trigger("sort",this,t);return this},pluck:function(t){return i.invoke(this.models,"get",t)},fetch:function(t){t=i.extend({parse:true},t);var e=t.success;var r=this;t.success=function(i){var n=t.reset?"reset":"set";r[n](i,t);if(e)e.call(t.context,r,i,t);r.trigger("sync",r,i,t)};z(this,t);return this.sync("read",this,t)},create:function(t,e){e=e?i.clone(e):{};var r=e.wait;t=this._prepareModel(t,e);if(!t)return false;if(!r)this.add(t,e);var n=this;var s=e.success;e.success=function(t,e,i){if(r)n.add(t,i);if(s)s.call(i.context,t,e,i)};t.save(null,e);return t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models,{model:this.model,comparator:this.comparator})},modelId:function(t){return t[this.model.prototype.idAttribute||"id"]},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(t,e){if(this._isModel(t)){if(!t.collection)t.collection=this;return t}e=e?i.clone(e):{};e.collection=this;var r=new this.model(t,e);if(!r.validationError)return r;this.trigger("invalid",this,r.validationError,e);return false},_removeModels:function(t,e){var i=[];for(var r=0;r<t.length;r++){var n=this.get(t[r]);if(!n)continue;var s=this.indexOf(n);this.models.splice(s,1);this.length--;if(!e.silent){e.index=s;n.trigger("remove",n,this,e)}i.push(n);this._removeReference(n,e)}return i.length?i:false},_isModel:function(t){return t instanceof y},_addReference:function(t,e){this._byId[t.cid]=t;var i=this.modelId(t.attributes);if(i!=null)this._byId[i]=t;t.on("all",this._onModelEvent,this)},_removeReference:function(t,e){delete this._byId[t.cid];var i=this.modelId(t.attributes);if(i!=null)delete this._byId[i];if(this===t.collection)delete t.collection;t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,r){if((t==="add"||t==="remove")&&i!==this)return;if(t==="destroy")this.remove(e,r);if(t==="change"){var n=this.modelId(e.previousAttributes());var s=this.modelId(e.attributes);if(n!==s){if(n!=null)delete this._byId[n];if(s!=null)this._byId[s]=e}}this.trigger.apply(this,arguments)}});var S={forEach:3,each:3,map:3,collect:3,reduce:4,foldl:4,inject:4,reduceRight:4,foldr:4,find:3,detect:3,filter:3,select:3,reject:3,every:3,all:3,some:3,any:3,include:3,includes:3,contains:3,invoke:0,max:3,min:3,toArray:1,size:1,first:3,head:3,take:3,initial:3,rest:3,tail:3,drop:3,last:3,without:0,difference:0,indexOf:3,shuffle:1,lastIndexOf:3,isEmpty:1,chain:1,sample:3,partition:3,groupBy:3,countBy:3,sortBy:3,indexBy:3};o(x,S,"models");var I=e.View=function(t){this.cid=i.uniqueId("view");i.extend(this,i.pick(t,P));this._ensureElement();this.initialize.apply(this,arguments)};var T=/^(\S+)\s*(.*)$/;var P=["model","collection","el","id","attributes","className","tagName","events"];i.extend(I.prototype,l,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){this._removeElement();this.stopListening();return this},_removeElement:function(){this.$el.remove()},setElement:function(t){this.undelegateEvents();this._setElement(t);this.delegateEvents();return this},_setElement:function(t){this.$el=t instanceof e.$?t:e.$(t);this.el=this.$el[0]},delegateEvents:function(t){t||(t=i.result(this,"events"));if(!t)return this;this.undelegateEvents();for(var e in t){var r=t[e];if(!i.isFunction(r))r=this[r];if(!r)continue;var n=e.match(T);this.delegate(n[1],n[2],i.bind(r,this))}return this},delegate:function(t,e,i){this.$el.on(t+".delegateEvents"+this.cid,e,i);return this},undelegateEvents:function(){if(this.$el)this.$el.off(".delegateEvents"+this.cid);return this},undelegate:function(t,e,i){this.$el.off(t+".delegateEvents"+this.cid,e,i);return this},_createElement:function(t){return document.createElement(t)},_ensureElement:function(){if(!this.el){var t=i.extend({},i.result(this,"attributes"));if(this.id)t.id=i.result(this,"id");if(this.className)t["class"]=i.result(this,"className");this.setElement(this._createElement(i.result(this,"tagName")));this._setAttributes(t)}else{this.setElement(i.result(this,"el"))}},_setAttributes:function(t){this.$el.attr(t)}});e.sync=function(t,r,n){var s=H[t];i.defaults(n||(n={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:s,dataType:"json"};if(!n.url){a.url=i.result(r,"url")||F()}if(n.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(n.attrs||r.toJSON(n))}if(n.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(n.emulateHTTP&&(s==="PUT"||s==="DELETE"||s==="PATCH")){a.type="POST";if(n.emulateJSON)a.data._method=s;var o=n.beforeSend;n.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",s);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!n.emulateJSON){a.processData=false}var h=n.error;n.error=function(t,e,i){n.textStatus=e;n.errorThrown=i;if(h)h.call(n.context,t,e,i)};var u=n.xhr=e.ajax(i.extend(a,n));r.trigger("request",r,u,n);return u};var H={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var A=/\((.*?)\)/g;var C=/(\(\?)?:\w+/g;var R=/\*\w+/g;var j=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,l,{initialize:function(){},route:function(t,r,n){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){n=r;r=""}if(!n)n=this[r];var s=this;e.history.route(t,function(i){var a=s._extractParameters(t,i);if(s.execute(n,a,r)!==false){s.trigger.apply(s,["route:"+r].concat(a));s.trigger("route",r,a);e.history.trigger("route",s,r,a)}});return this},execute:function(t,e,i){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(j,"\\$&").replace(A,"(?:$1)?").replace(C,function(t,e){return e?t:"([^/?]+)"}).replace(R,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var M=e.History=function(){this.handlers=[];this.checkUrl=i.bind(this.checkUrl,this);if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var N=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var U=/#.*$/;M.started=false;i.extend(M.prototype,l,{interval:50,atRoot:function(){var t=this.location.pathname.replace(/[^\/]$/,"$&/");return t===this.root&&!this.getSearch()},matchRoot:function(){var t=this.decodeFragment(this.location.pathname);var e=t.slice(0,this.root.length-1)+"/";return e===this.root},decodeFragment:function(t){return decodeURI(t.replace(/%25/g,"%2525"))},getSearch:function(){var t=this.location.href.replace(/#.*/,"").match(/\?.+/);return t?t[0]:""},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getPath:function(){var t=this.decodeFragment(this.location.pathname+this.getSearch()).slice(this.root.length-1);return t.charAt(0)==="/"?t.slice(1):t},getFragment:function(t){if(t==null){if(this._usePushState||!this._wantsHashChange){t=this.getPath()}else{t=this.getHash()}}return t.replace(N,"")},start:function(t){if(M.started)throw new Error("Backbone.history has already been started");M.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._hasHashChange="onhashchange"in window&&(document.documentMode===void 0||document.documentMode>7);this._useHashChange=this._wantsHashChange&&this._hasHashChange;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.history&&this.history.pushState);this._usePushState=this._wantsPushState&&this._hasPushState;this.fragment=this.getFragment();this.root=("/"+this.root+"/").replace(O,"/");if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||"/";this.location.replace(e+"#"+this.getPath());return true}else if(this._hasPushState&&this.atRoot()){this.navigate(this.getHash(),{replace:true})}}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe");this.iframe.src="javascript:0";this.iframe.style.display="none";this.iframe.tabIndex=-1;var r=document.body;var n=r.insertBefore(this.iframe,r.firstChild).contentWindow;n.document.open();n.document.close();n.location.hash="#"+this.fragment}var s=window.addEventListener||function(t,e){return attachEvent("on"+t,e)};if(this._usePushState){s("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){s("hashchange",this.checkUrl,false)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}if(!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent("on"+t,e)};if(this._usePushState){t("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){t("hashchange",this.checkUrl,false)}if(this.iframe){document.body.removeChild(this.iframe);this.iframe=null}if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);M.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getHash(this.iframe.contentWindow)}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){if(!this.matchRoot())return false;t=this.fragment=this.getFragment(t);return i.some(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!M.started)return false;if(!e||e===true)e={trigger:!!e};t=this.getFragment(t||"");var i=this.root;if(t===""||t.charAt(0)==="?"){i=i.slice(0,-1)||"/"}var r=i+t;t=this.decodeFragment(t.replace(U,""));if(this.fragment===t)return;this.fragment=t;if(this._usePushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,r)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var n=this.iframe.contentWindow;if(!e.replace){n.document.open();n.document.close()}this._updateHash(n.location,t,e.replace)}}else{return this.location.assign(r)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});e.history=new M;var q=function(t,e){var r=this;var n;if(t&&i.has(t,"constructor")){n=t.constructor}else{n=function(){return r.apply(this,arguments)}}i.extend(n,r,e);var s=function(){this.constructor=n};s.prototype=r.prototype;n.prototype=new s;if(t)i.extend(n.prototype,t);n.__super__=r.prototype;return n};y.extend=x.extend=$.extend=I.extend=M.extend=q;var F=function(){throw new Error('A "url" property or function must be specified')};var z=function(t,e){var i=e.error;e.error=function(r){if(i)i.call(e.context,t,r,e);t.trigger("error",t,r,e)}};return e}); /*! * jQuery Once v2.1.1 - http://github.com/robloach/jquery-once * @license MIT, GPL-2.0 * http://opensource.org/licenses/MIT * http://opensource.org/licenses/GPL-2.0 */ (function(e){"use strict";if(typeof exports==="object"){e(require("jquery"))}else if(typeof define==="function"&&define.amd){define(["jquery"],e)}else{e(jQuery)}})(function(e){"use strict";var n=function(e){e=e||"once";if(typeof e!=="string"){throw new Error("The jQuery Once id parameter must be a string")}return e};e.fn.once=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)!==true}).data(r,true)};e.fn.removeOnce=function(e){return this.findOnce(e).removeData("jquery-once-"+n(e))};e.fn.findOnce=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)===true})}}); /** * @file * Parse inline JSON and initialize the drupalSettings global object. */ (function () { 'use strict'; // Use direct child elements to harden against XSS exploits when CSP is on. var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]'); /** * Variable generated by Drupal with all the configuration created from PHP. * * @global * * @type {object} */ window.drupalSettings = {}; if (settingsElement !== null) { window.drupalSettings = JSON.parse(settingsElement.textContent); } })(); ; /** * @file * Defines the Drupal JavaScript API. */ /** * A jQuery object, typically the return value from a `$(selector)` call. * * Holds an HTMLElement or a collection of HTMLElements. * * @typedef {object} jQuery * * @prop {number} length=0 * Number of elements contained in the jQuery object. */ /** * Variable generated by Drupal that holds all translated strings from PHP. * * Content of this variable is automatically created by Drupal when using the * Interface Translation module. It holds the translation of strings used on * the page. * * This variable is used to pass data from the backend to the frontend. Data * contained in `drupalSettings` is used during behavior initialization. * * @global * * @var {object} drupalTranslations */ /** * Global Drupal object. * * All Drupal JavaScript APIs are contained in this namespace. * * @global * * @namespace */ window.Drupal = {behaviors: {}, locale: {}}; // Class indicating that JavaScript is enabled; used for styling purpose. document.documentElement.className += ' js'; // Allow other JavaScript libraries to use $. if (window.jQuery) { jQuery.noConflict(); } // JavaScript should be made compatible with libraries other than jQuery by // wrapping it in an anonymous closure. (function (domready, Drupal, drupalSettings, drupalTranslations) { 'use strict'; /** * Helper to rethrow errors asynchronously. * * This way Errors bubbles up outside of the original callstack, making it * easier to debug errors in the browser. * * @param {Error|string} error * The error to be thrown. */ Drupal.throwError = function (error) { setTimeout(function () { throw error; }, 0); }; /** * Custom error thrown after attach/detach if one or more behaviors failed. * Initializes the JavaScript behaviors for page loads and Ajax requests. * * @callback Drupal~behaviorAttach * * @param {HTMLDocument|HTMLElement} context * An element to detach behaviors from. * @param {?object} settings * An object containing settings for the current context. It is rarely used. * * @see Drupal.attachBehaviors */ /** * Reverts and cleans up JavaScript behavior initialization. * * @callback Drupal~behaviorDetach * * @param {HTMLDocument|HTMLElement} context * An element to attach behaviors to. * @param {object} settings * An object containing settings for the current context. * @param {string} trigger * One of `'unload'`, `'move'`, or `'serialize'`. * * @see Drupal.detachBehaviors */ /** * @typedef {object} Drupal~behavior * * @prop {Drupal~behaviorAttach} attach * Function run on page load and after an Ajax call. * @prop {Drupal~behaviorDetach} detach * Function run when content is serialized or removed from the page. */ /** * Holds all initialization methods. * * @namespace Drupal.behaviors * * @type {Object.<string, Drupal~behavior>} */ /** * Defines a behavior to be run during attach and detach phases. * * Attaches all registered behaviors to a page element. * * Behaviors are event-triggered actions that attach to page elements, * enhancing default non-JavaScript UIs. Behaviors are registered in the * {@link Drupal.behaviors} object using the method 'attach' and optionally * also 'detach'. * * {@link Drupal.attachBehaviors} is added below to the `jQuery.ready` event * and therefore runs on initial page load. Developers implementing Ajax in * their solutions should also call this function after new page content has * been loaded, feeding in an element to be processed, in order to attach all * behaviors to the new content. * * Behaviors should use `var elements = * $(context).find(selector).once('behavior-name');` to ensure the behavior is * attached only once to a given element. (Doing so enables the reprocessing * of given elements, which may be needed on occasion despite the ability to * limit behavior attachment to a particular element.) * * @example * Drupal.behaviors.behaviorName = { * attach: function (context, settings) { * // ... * }, * detach: function (context, settings, trigger) { * // ... * } * }; * * @param {HTMLDocument|HTMLElement} [context=document] * An element to attach behaviors to. * @param {object} [settings=drupalSettings] * An object containing settings for the current context. If none is given, * the global {@link drupalSettings} object is used. * * @see Drupal~behaviorAttach * @see Drupal.detachBehaviors * * @throws {Drupal~DrupalBehaviorError} */ Drupal.attachBehaviors = function (context, settings) { context = context || document; settings = settings || drupalSettings; var behaviors = Drupal.behaviors; // Execute all of them. for (var i in behaviors) { if (behaviors.hasOwnProperty(i) && typeof behaviors[i].attach === 'function') { // Don't stop the execution of behaviors in case of an error. try { behaviors[i].attach(context, settings); } catch (e) { Drupal.throwError(e); } } } }; // Attach all behaviors. domready(function () { Drupal.attachBehaviors(document, drupalSettings); }); /** * Detaches registered behaviors from a page element. * * Developers implementing Ajax in their solutions should call this function * before page content is about to be removed, feeding in an element to be * processed, in order to allow special behaviors to detach from the content. * * Such implementations should use `.findOnce()` and `.removeOnce()` to find * elements with their corresponding `Drupal.behaviors.behaviorName.attach` * implementation, i.e. `.removeOnce('behaviorName')`, to ensure the behavior * is detached only from previously processed elements. * * @param {HTMLDocument|HTMLElement} [context=document] * An element to detach behaviors from. * @param {object} [settings=drupalSettings] * An object containing settings for the current context. If none given, * the global {@link drupalSettings} object is used. * @param {string} [trigger='unload'] * A string containing what's causing the behaviors to be detached. The * possible triggers are: * - `'unload'`: The context element is being removed from the DOM. * - `'move'`: The element is about to be moved within the DOM (for example, * during a tabledrag row swap). After the move is completed, * {@link Drupal.attachBehaviors} is called, so that the behavior can undo * whatever it did in response to the move. Many behaviors won't need to * do anything simply in response to the element being moved, but because * IFRAME elements reload their "src" when being moved within the DOM, * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to * take some action. * - `'serialize'`: When an Ajax form is submitted, this is called with the * form as the context. This provides every behavior within the form an * opportunity to ensure that the field elements have correct content * in them before the form is serialized. The canonical use-case is so * that WYSIWYG editors can update the hidden textarea to which they are * bound. * * @throws {Drupal~DrupalBehaviorError} * * @see Drupal~behaviorDetach * @see Drupal.attachBehaviors */ Drupal.detachBehaviors = function (context, settings, trigger) { context = context || document; settings = settings || drupalSettings; trigger = trigger || 'unload'; var behaviors = Drupal.behaviors; // Execute all of them. for (var i in behaviors) { if (behaviors.hasOwnProperty(i) && typeof behaviors[i].detach === 'function') { // Don't stop the execution of behaviors in case of an error. try { behaviors[i].detach(context, settings, trigger); } catch (e) { Drupal.throwError(e); } } } }; /** * Encodes special characters in a plain-text string for display as HTML. * * @param {string} str * The string to be encoded. * * @return {string} * The encoded string. * * @ingroup sanitization */ Drupal.checkPlain = function (str) { str = str.toString() .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); return str; }; /** * Replaces placeholders with sanitized values in a string. * * @param {string} str * A string with placeholders. * @param {object} args * An object of replacements pairs to make. Incidences of any key in this * array are replaced with the corresponding value. Based on the first * character of the key, the value is escaped and/or themed: * - `'!variable'`: inserted as is. * - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}). * - `'%variable'`: escape text and theme as a placeholder for user- * submitted content ({@link Drupal.checkPlain} + * `{@link Drupal.theme}('placeholder')`). * * @return {string} * The formatted string. * * @see Drupal.t */ Drupal.formatString = function (str, args) { // Keep args intact. var processedArgs = {}; // Transform arguments before inserting them. for (var key in args) { if (args.hasOwnProperty(key)) { switch (key.charAt(0)) { // Escaped only. case '@': processedArgs[key] = Drupal.checkPlain(args[key]); break; // Pass-through. case '!': processedArgs[key] = args[key]; break; // Escaped and placeholder. default: processedArgs[key] = Drupal.theme('placeholder', args[key]); break; } } } return Drupal.stringReplace(str, processedArgs, null); }; /** * Replaces substring. * * The longest keys will be tried first. Once a substring has been replaced, * its new value will not be searched again. * * @param {string} str * A string with placeholders. * @param {object} args * Key-value pairs. * @param {Array|null} keys * Array of keys from `args`. Internal use only. * * @return {string} * The replaced string. */ Drupal.stringReplace = function (str, args, keys) { if (str.length === 0) { return str; } // If the array of keys is not passed then collect the keys from the args. if (!Array.isArray(keys)) { keys = []; for (var k in args) { if (args.hasOwnProperty(k)) { keys.push(k); } } // Order the keys by the character length. The shortest one is the first. keys.sort(function (a, b) { return a.length - b.length; }); } if (keys.length === 0) { return str; } // Take next longest one from the end. var key = keys.pop(); var fragments = str.split(key); if (keys.length) { for (var i = 0; i < fragments.length; i++) { // Process each fragment with a copy of remaining keys. fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0)); } } return fragments.join(args[key]); }; /** * Translates strings to the page language, or a given language. * * See the documentation of the server-side t() function for further details. * * @param {string} str * A string containing the English text to translate. * @param {Object.<string, string>} [args] * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * See {@link Drupal.formatString}. * @param {object} [options] * Additional options for translation. * @param {string} [options.context=''] * The context the source string belongs to. * * @return {string} * The formatted string. * The translated string. */ Drupal.t = function (str, args, options) { options = options || {}; options.context = options.context || ''; // Fetch the localized version of the string. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) { str = drupalTranslations.strings[options.context][str]; } if (args) { str = Drupal.formatString(str, args); } return str; }; /** * Returns the URL to a Drupal page. * * @param {string} path * Drupal path to transform to URL. * * @return {string} * The full URL. */ Drupal.url = function (path) { return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path; }; /** * Returns the passed in URL as an absolute URL. * * @param {string} url * The URL string to be normalized to an absolute URL. * * @return {string} * The normalized, absolute URL. * * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53 */ Drupal.url.toAbsolute = function (url) { var urlParsingNode = document.createElement('a'); // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8 // strings may throw an exception. try { url = decodeURIComponent(url); } catch (e) { // Empty. } urlParsingNode.setAttribute('href', url); // IE <= 7 normalizes the URL when assigned to the anchor node similar to // the other browsers. return urlParsingNode.cloneNode(false).href; }; /** * Returns true if the URL is within Drupal's base path. * * @param {string} url * The URL string to be tested. * * @return {bool} * `true` if local. * * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58 */ Drupal.url.isLocal = function (url) { // Always use browser-derived absolute URLs in the comparison, to avoid // attempts to break out of the base path using directory traversal. var absoluteUrl = Drupal.url.toAbsolute(url); var protocol = location.protocol; // Consider URLs that match this site's base URL but use HTTPS instead of HTTP // as local as well. if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) { protocol = 'https:'; } var baseUrl = protocol + '//' + location.host + drupalSettings.path.baseUrl.slice(0, -1); // Decoding non-UTF-8 strings may throw an exception. try { absoluteUrl = decodeURIComponent(absoluteUrl); } catch (e) { // Empty. } try { baseUrl = decodeURIComponent(baseUrl); } catch (e) { // Empty. } // The given URL matches the site's base URL, or has a path under the site's // base URL. return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0; }; /** * Formats a string containing a count of items. * * This function ensures that the string is pluralized correctly. Since * {@link Drupal.t} is called by this function, make sure not to pass * already-localized strings to it. * * See the documentation of the server-side * \Drupal\Core\StringTranslation\TranslationInterface::formatPlural() * function for more details. * * @param {number} count * The item count to display. * @param {string} singular * The string for the singular case. Please make sure it is clear this is * singular, to ease translation (e.g. use "1 new comment" instead of "1 * new"). Do not use @count in the singular string. * @param {string} plural * The string for the plural case. Please make sure it is clear this is * plural, to ease translation. Use @count in place of the item count, as in * "@count new comments". * @param {object} [args] * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * See {@link Drupal.formatString}. * Note that you do not need to include @count in this array. * This replacement is done automatically for the plural case. * @param {object} [options] * The options to pass to the {@link Drupal.t} function. * * @return {string} * A translated string. */ Drupal.formatPlural = function (count, singular, plural, args, options) { args = args || {}; args['@count'] = count; var pluralDelimiter = drupalSettings.pluralDelimiter; var translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter); var index = 0; // Determine the index of the plural form. if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) { index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula['default']; } else if (args['@count'] !== 1) { index = 1; } return translations[index]; }; /** * Encodes a Drupal path for use in a URL. * * For aesthetic reasons slashes are not escaped. * * @param {string} item * Unencoded path. * * @return {string} * The encoded path. */ Drupal.encodePath = function (item) { return window.encodeURIComponent(item).replace(/%2F/g, '/'); }; /** * Generates the themed representation of a Drupal object. * * All requests for themed output must go through this function. It examines * the request and routes it to the appropriate theme function. If the current * theme does not provide an override function, the generic theme function is * called. * * @example * <caption>To retrieve the HTML for text that should be emphasized and * displayed as a placeholder inside a sentence.</caption> * Drupal.theme('placeholder', text); * * @namespace * * @param {function} func * The name of the theme function to call. * @param {...args} * Additional arguments to pass along to the theme function. * * @return {string|object|HTMLElement|jQuery} * Any data the theme function returns. This could be a plain HTML string, * but also a complex object. */ Drupal.theme = function (func) { var args = Array.prototype.slice.apply(arguments, [1]); if (func in Drupal.theme) { return Drupal.theme[func].apply(this, args); } }; /** * Formats text for emphasized display in a placeholder inside a sentence. * * @param {string} str * The text to format (plain-text). * * @return {string} * The formatted text (html). */ Drupal.theme.placeholder = function (str) { return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>'; }; })(domready, Drupal, window.drupalSettings, window.drupalTranslations); ; /*! * jQuery UI Core 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,r){var i,s,o,u=t.nodeName.toLowerCase();return"area"===u?(i=t.parentNode,s=i.name,!t.href||!s||i.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap='#"+s+"']")[0],!!o&&n(o))):(/^(input|select|textarea|button|object)$/.test(u)?!t.disabled:"a"===u?t.href||r:r)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return e.css(this,"visibility")==="hidden"}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var n=this.css("position"),r=n==="absolute",i=t?/(auto|scroll|hidden)/:/(auto|scroll)/,s=this.parents().filter(function(){var t=e(this);return r&&t.css("position")==="static"?!1:i.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return n==="fixed"||!s.length?e(this[0].ownerDocument||document):s},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(n){return t(n,!isNaN(e.attr(n,"tabindex")))},tabbable:function(n){var r=e.attr(n,"tabindex"),i=isNaN(r);return(i||r>=0)&&t(n,!i)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,n){function o(t,n,i,s){return e.each(r,function(){n-=parseFloat(e.css(t,"padding"+this))||0,i&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var r=n==="Width"?["Left","Right"]:["Top","Bottom"],i=n.toLowerCase(),s={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(t){return t===undefined?s["inner"+n].call(this):this.each(function(){e(this).css(i,o(this,t)+"px")})},e.fn["outer"+n]=function(t,r){return typeof t!="number"?s["outer"+n].call(this,t):this.each(function(){e(this).css(i,o(this,t,!0,r)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(n,r){return typeof n=="number"?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(t!==undefined)return this.css("zIndex",t);if(this.length){var n=e(this[0]),r,i;while(n.length&&n[0]!==document){r=n.css("position");if(r==="absolute"||r==="relative"||r==="fixed"){i=parseInt(n.css("zIndex"),10);if(!isNaN(i)&&i!==0)return i}n=n.parent()}}return 0}}),e.ui.plugin={add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n,r){var i,s=e.plugins[t];if(!s)return;if(!r&&(!e.element[0].parentNode||e.element[0].parentNode.nodeType===11))return;for(i=0;i<s.length;i++)e.options[s[i][0]]&&s[i][1].apply(e.element,n)}}});; /** * @file * Attaches behaviors for the Contextual module. */ (function ($, Drupal, drupalSettings, _, Backbone, JSON, storage) { 'use strict'; var options = $.extend(drupalSettings.contextual, // Merge strings on top of drupalSettings so that they are not mutable. { strings: { open: Drupal.t('Open'), close: Drupal.t('Close') } } ); // Clear the cached contextual links whenever the current user's set of // permissions changes. var cachedPermissionsHash = storage.getItem('Drupal.contextual.permissionsHash'); var permissionsHash = drupalSettings.user.permissionsHash; if (cachedPermissionsHash !== permissionsHash) { if (typeof permissionsHash === 'string') { _.chain(storage).keys().each(function (key) { if (key.substring(0, 18) === 'Drupal.contextual.') { storage.removeItem(key); } }); } storage.setItem('Drupal.contextual.permissionsHash', permissionsHash); } /** * Initializes a contextual link: updates its DOM, sets up model and views. * * @param {jQuery} $contextual * A contextual links placeholder DOM element, containing the actual * contextual links as rendered by the server. * @param {string} html * The server-side rendered HTML for this contextual link. */ function initContextual($contextual, html) { var $region = $contextual.closest('.contextual-region'); var contextual = Drupal.contextual; $contextual // Update the placeholder to contain its rendered contextual links. .html(html) // Use the placeholder as a wrapper with a specific class to provide // positioning and behavior attachment context. .addClass('contextual') // Ensure a trigger element exists before the actual contextual links. .prepend(Drupal.theme('contextualTrigger')); // Set the destination parameter on each of the contextual links. var destination = 'destination=' + Drupal.encodePath(drupalSettings.path.currentPath); $contextual.find('.contextual-links a').each(function () { var url = this.getAttribute('href'); var glue = (url.indexOf('?') === -1) ? '?' : '&'; this.setAttribute('href', url + glue + destination); }); // Create a model and the appropriate views. var model = new contextual.StateModel({ title: $region.find('h2').eq(0).text().trim() }); var viewOptions = $.extend({el: $contextual, model: model}, options); contextual.views.push({ visual: new contextual.VisualView(viewOptions), aural: new contextual.AuralView(viewOptions), keyboard: new contextual.KeyboardView(viewOptions) }); contextual.regionViews.push(new contextual.RegionView( $.extend({el: $region, model: model}, options)) ); // Add the model to the collection. This must happen after the views have // been associated with it, otherwise collection change event handlers can't // trigger the model change event handler in its views. contextual.collection.add(model); // Let other JavaScript react to the adding of a new contextual link. $(document).trigger('drupalContextualLinkAdded', { $el: $contextual, $region: $region, model: model }); // Fix visual collisions between contextual link triggers. adjustIfNestedAndOverlapping($contextual); } /** * Determines if a contextual link is nested & overlapping, if so: adjusts it. * * This only deals with two levels of nesting; deeper levels are not touched. * * @param {jQuery} $contextual * A contextual links placeholder DOM element, containing the actual * contextual links as rendered by the server. */ function adjustIfNestedAndOverlapping($contextual) { var $contextuals = $contextual // @todo confirm that .closest() is not sufficient .parents('.contextual-region').eq(-1) .find('.contextual'); // Early-return when there's no nesting. if ($contextuals.length === 1) { return; } // If the two contextual links overlap, then we move the second one. var firstTop = $contextuals.eq(0).offset().top; var secondTop = $contextuals.eq(1).offset().top; if (firstTop === secondTop) { var $nestedContextual = $contextuals.eq(1); // Retrieve height of nested contextual link. var height = 0; var $trigger = $nestedContextual.find('.trigger'); // Elements with the .visually-hidden class have no dimensions, so this // class must be temporarily removed to the calculate the height. $trigger.removeClass('visually-hidden'); height = $nestedContextual.height(); $trigger.addClass('visually-hidden'); // Adjust nested contextual link's position. $nestedContextual.css({top: $nestedContextual.position().top + height}); } } /** * Attaches outline behavior for regions associated with contextual links. * * Events * Contextual triggers an event that can be used by other scripts. * - drupalContextualLinkAdded: Triggered when a contextual link is added. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the outline behavior to the right context. */ Drupal.behaviors.contextual = { attach: function (context) { var $context = $(context); // Find all contextual links placeholders, if any. var $placeholders = $context.find('[data-contextual-id]').once('contextual-render'); if ($placeholders.length === 0) { return; } // Collect the IDs for all contextual links placeholders. var ids = []; $placeholders.each(function () { ids.push($(this).attr('data-contextual-id')); }); // Update all contextual links placeholders whose HTML is cached. var uncachedIDs = _.filter(ids, function initIfCached(contextualID) { var html = storage.getItem('Drupal.contextual.' + contextualID); if (html !== null) { // Initialize after the current execution cycle, to make the AJAX // request for retrieving the uncached contextual links as soon as // possible, but also to ensure that other Drupal behaviors have had // the chance to set up an event listener on the Backbone collection // Drupal.contextual.collection. window.setTimeout(function () { initContextual($context.find('[data-contextual-id="' + contextualID + '"]'), html); }); return false; } return true; }); // Perform an AJAX request to let the server render the contextual links // for each of the placeholders. if (uncachedIDs.length > 0) { $.ajax({ url: Drupal.url('contextual/render'), type: 'POST', data: {'ids[]': uncachedIDs}, dataType: 'json', success: function (results) { _.each(results, function (html, contextualID) { // Store the metadata. storage.setItem('Drupal.contextual.' + contextualID, html); // If the rendered contextual links are empty, then the current // user does not have permission to access the associated links: // don't render anything. if (html.length > 0) { // Update the placeholders to contain its rendered contextual // links. Usually there will only be one placeholder, but it's // possible for multiple identical placeholders exist on the // page (probably because the same content appears more than // once). $placeholders = $context.find('[data-contextual-id="' + contextualID + '"]'); // Initialize the contextual links. for (var i = 0; i < $placeholders.length; i++) { initContextual($placeholders.eq(i), html); } } }); } }); } } }; /** * Namespace for contextual related functionality. * * @namespace */ Drupal.contextual = { /** * The {@link Drupal.contextual.View} instances associated with each list * element of contextual links. * * @type {Array} */ views: [], /** * The {@link Drupal.contextual.RegionView} instances associated with each * contextual region element. * * @type {Array} */ regionViews: [] }; /** * A Backbone.Collection of {@link Drupal.contextual.StateModel} instances. * * @type {Backbone.Collection} */ Drupal.contextual.collection = new Backbone.Collection([], {model: Drupal.contextual.StateModel}); /** * A trigger is an interactive element often bound to a click handler. * * @return {string} * A string representing a DOM fragment. */ Drupal.theme.contextualTrigger = function () { return '<button class="trigger visually-hidden focusable" type="button"></button>'; }; })(jQuery, Drupal, drupalSettings, _, Backbone, window.JSON, window.sessionStorage); ; /** * @file * A Backbone Model for the state of a contextual link's trigger, list & region. */ (function (Drupal, Backbone) { 'use strict'; /** * Models the state of a contextual link's trigger, list & region. * * @constructor * * @augments Backbone.Model */ Drupal.contextual.StateModel = Backbone.Model.extend(/** @lends Drupal.contextual.StateModel# */{ /** * @type {object} * * @prop {string} title * @prop {bool} regionIsHovered * @prop {bool} hasFocus * @prop {bool} isOpen * @prop {bool} isLocked */ defaults: /** @lends Drupal.contextual.StateModel# */{ /** * The title of the entity to which these contextual links apply. * * @type {string} */ title: '', /** * Represents if the contextual region is being hovered. * * @type {bool} */ regionIsHovered: false, /** * Represents if the contextual trigger or options have focus. * * @type {bool} */ hasFocus: false, /** * Represents if the contextual options for an entity are available to * be selected (i.e. whether the list of options is visible). * * @type {bool} */ isOpen: false, /** * When the model is locked, the trigger remains active. * * @type {bool} */ isLocked: false }, /** * Opens or closes the contextual link. * * If it is opened, then also give focus. * * @return {Drupal.contextual.StateModel} * The current contextual state model. */ toggleOpen: function () { var newIsOpen = !this.get('isOpen'); this.set('isOpen', newIsOpen); if (newIsOpen) { this.focus(); } return this; }, /** * Closes this contextual link. * * Does not call blur() because we want to allow a contextual link to have * focus, yet be closed for example when hovering. * * @return {Drupal.contextual.StateModel} * The current contextual state model. */ close: function () { this.set('isOpen', false); return this; }, /** * Gives focus to this contextual link. * * Also closes + removes focus from every other contextual link. * * @return {Drupal.contextual.StateModel} * The current contextual state model. */ focus: function () { this.set('hasFocus', true); var cid = this.cid; this.collection.each(function (model) { if (model.cid !== cid) { model.close().blur(); } }); return this; }, /** * Removes focus from this contextual link, unless it is open. * * @return {Drupal.contextual.StateModel} * The current contextual state model. */ blur: function () { if (!this.get('isOpen')) { this.set('hasFocus', false); } return this; } }); })(Drupal, Backbone); ; /** * @file * A Backbone View that provides the aural view of a contextual link. */ (function (Drupal, Backbone) { 'use strict'; Drupal.contextual.AuralView = Backbone.View.extend(/** @lends Drupal.contextual.AuralView# */{ /** * Renders the aural view of a contextual link (i.e. screen reader support). * * @constructs * * @augments Backbone.View * * @param {object} options * Options for the view. */ initialize: function (options) { this.options = options; this.listenTo(this.model, 'change', this.render); // Use aria-role form so that the number of items in the list is spoken. this.$el.attr('role', 'form'); // Initial render. this.render(); }, /** * @inheritdoc */ render: function () { var isOpen = this.model.get('isOpen'); // Set the hidden property of the links. this.$el.find('.contextual-links') .prop('hidden', !isOpen); // Update the view of the trigger. this.$el.find('.trigger') .text(Drupal.t('@action @title configuration options', { '@action': (!isOpen) ? this.options.strings.open : this.options.strings.close, '@title': this.model.get('title') })) .attr('aria-pressed', isOpen); } }); })(Drupal, Backbone); ; /** * @file * A Backbone View that provides keyboard interaction for a contextual link. */ (function (Drupal, Backbone) { 'use strict'; Drupal.contextual.KeyboardView = Backbone.View.extend(/** @lends Drupal.contextual.KeyboardView# */{ /** * @type {object} */ events: { 'focus .trigger': 'focus', 'focus .contextual-links a': 'focus', 'blur .trigger': function () { this.model.blur(); }, 'blur .contextual-links a': function () { // Set up a timeout to allow a user to tab between the trigger and the // contextual links without the menu dismissing. var that = this; this.timer = window.setTimeout(function () { that.model.close().blur(); }, 150); } }, /** * Provides keyboard interaction for a contextual link. * * @constructs * * @augments Backbone.View */ initialize: function () { /** * The timer is used to create a delay before dismissing the contextual * links on blur. This is only necessary when keyboard users tab into * contextual links without edit mode (i.e. without TabbingManager). * That means that if we decide to disable tabbing of contextual links * without edit mode, all this timer logic can go away. * * @type {NaN|number} */ this.timer = NaN; }, /** * Sets focus on the model; Clears the timer that dismisses the links. */ focus: function () { // Clear the timeout that might have been set by blurring a link. window.clearTimeout(this.timer); this.model.focus(); } }); })(Drupal, Backbone); ; /** * @file * A Backbone View that renders the visual view of a contextual region element. */ (function (Drupal, Backbone, Modernizr) { 'use strict'; Drupal.contextual.RegionView = Backbone.View.extend(/** @lends Drupal.contextual.RegionView# */{ /** * Events for the Backbone view. * * @return {object} * A mapping of events to be used in the view. */ events: function () { var mapping = { mouseenter: function () { this.model.set('regionIsHovered', true); }, mouseleave: function () { this.model.close().blur().set('regionIsHovered', false); } }; // We don't want mouse hover events on touch. if (Modernizr.touchevents) { mapping = {}; } return mapping; }, /** * Renders the visual view of a contextual region element. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change:hasFocus', this.render); }, /** * @inheritdoc * * @return {Drupal.contextual.RegionView} * The current contextual region view. */ render: function () { this.$el.toggleClass('focus', this.model.get('hasFocus')); return this; } }); })(Drupal, Backbone, Modernizr); ; /** * @file * A Backbone View that provides the visual view of a contextual link. */ (function (Drupal, Backbone, Modernizr) { 'use strict'; Drupal.contextual.VisualView = Backbone.View.extend(/** @lends Drupal.contextual.VisualView# */{ /** * Events for the Backbone view. * * @return {object} * A mapping of events to be used in the view. */ events: function () { // Prevents delay and simulated mouse events. var touchEndToClick = function (event) { event.preventDefault(); event.target.click(); }; var mapping = { 'click .trigger': function () { this.model.toggleOpen(); }, 'touchend .trigger': touchEndToClick, 'click .contextual-links a': function () { this.model.close().blur(); }, 'touchend .contextual-links a': touchEndToClick }; // We only want mouse hover events on non-touch. if (!Modernizr.touchevents) { mapping.mouseenter = function () { this.model.focus(); }; } return mapping; }, /** * Renders the visual view of a contextual link. Listens to mouse & touch. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change', this.render); }, /** * @inheritdoc * * @return {Drupal.contextual.VisualView} * The current contextual visual view. */ render: function () { var isOpen = this.model.get('isOpen'); // The trigger should be visible when: // - the mouse hovered over the region, // - the trigger is locked, // - and for as long as the contextual menu is open. var isVisible = this.model.get('isLocked') || this.model.get('regionIsHovered') || isOpen; this.$el // The open state determines if the links are visible. .toggleClass('open', isOpen) // Update the visibility of the trigger. .find('.trigger').toggleClass('visually-hidden', !isVisible); // Nested contextual region handling: hide any nested contextual triggers. if ('isOpen' in this.model.changed) { this.$el.closest('.contextual-region') .find('.contextual .trigger:not(:first)') .toggle(!isOpen); } return this; } }); })(Drupal, Backbone, Modernizr); ; /** * @file * Attaches behaviors for Drupal's active link marking. */ (function (Drupal, drupalSettings) { 'use strict'; /** * Append is-active class. * * The link is only active if its path corresponds to the current path, the * language of the linked path is equal to the current language, and if the * query parameters of the link equal those of the current request, since the * same request with different query parameters may yield a different page * (e.g. pagers, exposed View filters). * * Does not discriminate based on element type, so allows you to set the * is-active class on any element: a, li… * * @type {Drupal~behavior} */ Drupal.behaviors.activeLinks = { attach: function (context) { // Start by finding all potentially active links. var path = drupalSettings.path; var queryString = JSON.stringify(path.currentQuery); var querySelector = path.currentQuery ? "[data-drupal-link-query='" + queryString + "']" : ':not([data-drupal-link-query])'; var originalSelectors = ['[data-drupal-link-system-path="' + path.currentPath + '"]']; var selectors; // If this is the front page, we have to check for the <front> path as // well. if (path.isFront) { originalSelectors.push('[data-drupal-link-system-path="<front>"]'); } // Add language filtering. selectors = [].concat( // Links without any hreflang attributes (most of them). originalSelectors.map(function (selector) { return selector + ':not([hreflang])'; }), // Links with hreflang equals to the current language. originalSelectors.map(function (selector) { return selector + '[hreflang="' + path.currentLanguage + '"]'; }) ); // Add query string selector for pagers, exposed filters. selectors = selectors.map(function (current) { return current + querySelector; }); // Query the DOM. var activeLinks = context.querySelectorAll(selectors.join(',')); var il = activeLinks.length; for (var i = 0; i < il; i++) { activeLinks[i].classList.add('is-active'); } }, detach: function (context, settings, trigger) { if (trigger === 'unload') { var activeLinks = context.querySelectorAll('[data-drupal-link-system-path].is-active'); var il = activeLinks.length; for (var i = 0; i < il; i++) { activeLinks[i].classList.remove('is-active'); } } } }; })(Drupal, drupalSettings); ; /** * @file * Drupal's states library. */ (function ($, Drupal) { 'use strict'; /** * The base States namespace. * * Having the local states variable allows us to use the States namespace * without having to always declare "Drupal.states". * * @namespace Drupal.states */ var states = Drupal.states = { /** * An array of functions that should be postponed. */ postponed: [] }; /** * Attaches the states. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches states behaviors. */ Drupal.behaviors.states = { attach: function (context, settings) { var $states = $(context).find('[data-drupal-states]'); var config; var state; var il = $states.length; for (var i = 0; i < il; i++) { config = JSON.parse($states[i].getAttribute('data-drupal-states')); for (state in config) { if (config.hasOwnProperty(state)) { new states.Dependent({ element: $($states[i]), state: states.State.sanitize(state), constraints: config[state] }); } } } // Execute all postponed functions now. while (states.postponed.length) { (states.postponed.shift())(); } } }; /** * Object representing an element that depends on other elements. * * @constructor Drupal.states.Dependent * * @param {object} args * Object with the following keys (all of which are required) * @param {jQuery} args.element * A jQuery object of the dependent element * @param {Drupal.states.State} args.state * A State object describing the state that is dependent * @param {object} args.constraints * An object with dependency specifications. Lists all elements that this * element depends on. It can be nested and can contain * arbitrary AND and OR clauses. */ states.Dependent = function (args) { $.extend(this, {values: {}, oldValue: null}, args); this.dependees = this.getDependees(); for (var selector in this.dependees) { if (this.dependees.hasOwnProperty(selector)) { this.initializeDependee(selector, this.dependees[selector]); } } }; /** * Comparison functions for comparing the value of an element with the * specification from the dependency settings. If the object type can't be * found in this list, the === operator is used by default. * * @name Drupal.states.Dependent.comparisons * * @prop {function} RegExp * @prop {function} Function * @prop {function} Number */ states.Dependent.comparisons = { RegExp: function (reference, value) { return reference.test(value); }, Function: function (reference, value) { // The "reference" variable is a comparison function. return reference(value); }, Number: function (reference, value) { // If "reference" is a number and "value" is a string, then cast // reference as a string before applying the strict comparison in // compare(). // Otherwise numeric keys in the form's #states array fail to match // string values returned from jQuery's val(). return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value); } }; states.Dependent.prototype = { /** * Initializes one of the elements this dependent depends on. * * @memberof Drupal.states.Dependent# * * @param {string} selector * The CSS selector describing the dependee. * @param {object} dependeeStates * The list of states that have to be monitored for tracking the * dependee's compliance status. */ initializeDependee: function (selector, dependeeStates) { var state; var self = this; function stateEventHandler(e) { self.update(e.data.selector, e.data.state, e.value); } // Cache for the states of this dependee. this.values[selector] = {}; for (var i in dependeeStates) { if (dependeeStates.hasOwnProperty(i)) { state = dependeeStates[i]; // Make sure we're not initializing this selector/state combination // twice. if ($.inArray(state, dependeeStates) === -1) { continue; } state = states.State.sanitize(state); // Initialize the value of this state. this.values[selector][state.name] = null; // Monitor state changes of the specified state for this dependee. $(selector).on('state:' + state, {selector: selector, state: state}, stateEventHandler); // Make sure the event we just bound ourselves to is actually fired. new states.Trigger({selector: selector, state: state}); } } }, /** * Compares a value with a reference value. * * @memberof Drupal.states.Dependent# * * @param {object} reference * The value used for reference. * @param {string} selector * CSS selector describing the dependee. * @param {Drupal.states.State} state * A State object describing the dependee's updated state. * * @return {bool} * true or false. */ compare: function (reference, selector, state) { var value = this.values[selector][state.name]; if (reference.constructor.name in states.Dependent.comparisons) { // Use a custom compare function for certain reference value types. return states.Dependent.comparisons[reference.constructor.name](reference, value); } else { // Do a plain comparison otherwise. return compare(reference, value); } }, /** * Update the value of a dependee's state. * * @memberof Drupal.states.Dependent# * * @param {string} selector * CSS selector describing the dependee. * @param {Drupal.states.state} state * A State object describing the dependee's updated state. * @param {string} value * The new value for the dependee's updated state. */ update: function (selector, state, value) { // Only act when the 'new' value is actually new. if (value !== this.values[selector][state.name]) { this.values[selector][state.name] = value; this.reevaluate(); } }, /** * Triggers change events in case a state changed. * * @memberof Drupal.states.Dependent# */ reevaluate: function () { // Check whether any constraint for this dependent state is satisfied. var value = this.verifyConstraints(this.constraints); // Only invoke a state change event when the value actually changed. if (value !== this.oldValue) { // Store the new value so that we can compare later whether the value // actually changed. this.oldValue = value; // Normalize the value to match the normalized state name. value = invert(value, this.state.invert); // By adding "trigger: true", we ensure that state changes don't go into // infinite loops. this.element.trigger({type: 'state:' + this.state, value: value, trigger: true}); } }, /** * Evaluates child constraints to determine if a constraint is satisfied. * * @memberof Drupal.states.Dependent# * * @param {object|Array} constraints * A constraint object or an array of constraints. * @param {string} selector * The selector for these constraints. If undefined, there isn't yet a * selector that these constraints apply to. In that case, the keys of the * object are interpreted as the selector if encountered. * * @return {bool} * true or false, depending on whether these constraints are satisfied. */ verifyConstraints: function (constraints, selector) { var result; if ($.isArray(constraints)) { // This constraint is an array (OR or XOR). var hasXor = $.inArray('xor', constraints) === -1; var len = constraints.length; for (var i = 0; i < len; i++) { if (constraints[i] !== 'xor') { var constraint = this.checkConstraints(constraints[i], selector, i); // Return if this is OR and we have a satisfied constraint or if // this is XOR and we have a second satisfied constraint. if (constraint && (hasXor || result)) { return hasXor; } result = result || constraint; } } } // Make sure we don't try to iterate over things other than objects. This // shouldn't normally occur, but in case the condition definition is // bogus, we don't want to end up with an infinite loop. else if ($.isPlainObject(constraints)) { // This constraint is an object (AND). for (var n in constraints) { if (constraints.hasOwnProperty(n)) { result = ternary(result, this.checkConstraints(constraints[n], selector, n)); // False and anything else will evaluate to false, so return when // any false condition is found. if (result === false) { return false; } } } } return result; }, /** * Checks whether the value matches the requirements for this constraint. * * @memberof Drupal.states.Dependent# * * @param {string|Array|object} value * Either the value of a state or an array/object of constraints. In the * latter case, resolving the constraint continues. * @param {string} [selector] * The selector for this constraint. If undefined, there isn't yet a * selector that this constraint applies to. In that case, the state key * is propagates to a selector and resolving continues. * @param {Drupal.states.State} [state] * The state to check for this constraint. If undefined, resolving * continues. If both selector and state aren't undefined and valid * non-numeric strings, a lookup for the actual value of that selector's * state is performed. This parameter is not a State object but a pristine * state string. * * @return {bool} * true or false, depending on whether this constraint is satisfied. */ checkConstraints: function (value, selector, state) { // Normalize the last parameter. If it's non-numeric, we treat it either // as a selector (in case there isn't one yet) or as a trigger/state. if (typeof state !== 'string' || (/[0-9]/).test(state[0])) { state = null; } else if (typeof selector === 'undefined') { // Propagate the state to the selector when there isn't one yet. selector = state; state = null; } if (state !== null) { // Constraints is the actual constraints of an element to check for. state = states.State.sanitize(state); return invert(this.compare(value, selector, state), state.invert); } else { // Resolve this constraint as an AND/OR operator. return this.verifyConstraints(value, selector); } }, /** * Gathers information about all required triggers. * * @memberof Drupal.states.Dependent# * * @return {object} * An object describing the required triggers. */ getDependees: function () { var cache = {}; // Swivel the lookup function so that we can record all available // selector- state combinations for initialization. var _compare = this.compare; this.compare = function (reference, selector, state) { (cache[selector] || (cache[selector] = [])).push(state.name); // Return nothing (=== undefined) so that the constraint loops are not // broken. }; // This call doesn't actually verify anything but uses the resolving // mechanism to go through the constraints array, trying to look up each // value. Since we swivelled the compare function, this comparison returns // undefined and lookup continues until the very end. Instead of lookup up // the value, we record that combination of selector and state so that we // can initialize all triggers. this.verifyConstraints(this.constraints); // Restore the original function. this.compare = _compare; return cache; } }; /** * @constructor Drupal.states.Trigger * * @param {object} args * Trigger arguments. */ states.Trigger = function (args) { $.extend(this, args); if (this.state in states.Trigger.states) { this.element = $(this.selector); // Only call the trigger initializer when it wasn't yet attached to this // element. Otherwise we'd end up with duplicate events. if (!this.element.data('trigger:' + this.state)) { this.initialize(); } } }; states.Trigger.prototype = { /** * @memberof Drupal.states.Trigger# */ initialize: function () { var trigger = states.Trigger.states[this.state]; if (typeof trigger === 'function') { // We have a custom trigger initialization function. trigger.call(window, this.element); } else { for (var event in trigger) { if (trigger.hasOwnProperty(event)) { this.defaultTrigger(event, trigger[event]); } } } // Mark this trigger as initialized for this element. this.element.data('trigger:' + this.state, true); }, /** * @memberof Drupal.states.Trigger# * * @param {jQuery.Event} event * The event triggered. * @param {function} valueFn * The function to call. */ defaultTrigger: function (event, valueFn) { var oldValue = valueFn.call(this.element); // Attach the event callback. this.element.on(event, $.proxy(function (e) { var value = valueFn.call(this.element, e); // Only trigger the event if the value has actually changed. if (oldValue !== value) { this.element.trigger({type: 'state:' + this.state, value: value, oldValue: oldValue}); oldValue = value; } }, this)); states.postponed.push($.proxy(function () { // Trigger the event once for initialization purposes. this.element.trigger({type: 'state:' + this.state, value: oldValue, oldValue: null}); }, this)); } }; /** * This list of states contains functions that are used to monitor the state * of an element. Whenever an element depends on the state of another element, * one of these trigger functions is added to the dependee so that the * dependent element can be updated. * * @name Drupal.states.Trigger.states * * @prop empty * @prop checked * @prop value * @prop collapsed */ states.Trigger.states = { // 'empty' describes the state to be monitored. empty: { // 'keyup' is the (native DOM) event that we watch for. keyup: function () { // The function associated with that trigger returns the new value for // the state. return this.val() === ''; } }, checked: { change: function () { // prop() and attr() only takes the first element into account. To // support selectors matching multiple checkboxes, iterate over all and // return whether any is checked. var checked = false; this.each(function () { // Use prop() here as we want a boolean of the checkbox state. // @see http://api.jquery.com/prop/ checked = $(this).prop('checked'); // Break the each() loop if this is checked. return !checked; }); return checked; } }, // For radio buttons, only return the value if the radio button is selected. value: { keyup: function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); }, change: function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); } }, collapsed: { collapsed: function (e) { return (typeof e !== 'undefined' && 'value' in e) ? e.value : !this.is('[open]'); } } }; /** * A state object is used for describing the state and performing aliasing. * * @constructor Drupal.states.State * * @param {string} state * The name of the state. */ states.State = function (state) { /** * Original unresolved name. */ this.pristine = this.name = state; // Normalize the state name. var process = true; do { // Iteratively remove exclamation marks and invert the value. while (this.name.charAt(0) === '!') { this.name = this.name.substring(1); this.invert = !this.invert; } // Replace the state with its normalized name. if (this.name in states.State.aliases) { this.name = states.State.aliases[this.name]; } else { process = false; } } while (process); }; /** * Creates a new State object by sanitizing the passed value. * * @name Drupal.states.State.sanitize * * @param {string|Drupal.states.State} state * A state object or the name of a state. * * @return {Drupal.states.state} * A state object. */ states.State.sanitize = function (state) { if (state instanceof states.State) { return state; } else { return new states.State(state); } }; /** * This list of aliases is used to normalize states and associates negated * names with their respective inverse state. * * @name Drupal.states.State.aliases */ states.State.aliases = { enabled: '!disabled', invisible: '!visible', invalid: '!valid', untouched: '!touched', optional: '!required', filled: '!empty', unchecked: '!checked', irrelevant: '!relevant', expanded: '!collapsed', open: '!collapsed', closed: 'collapsed', readwrite: '!readonly' }; states.State.prototype = { /** * @memberof Drupal.states.State# */ invert: false, /** * Ensures that just using the state object returns the name. * * @memberof Drupal.states.State# * * @return {string} * The name of the state. */ toString: function () { return this.name; } }; /** * Global state change handlers. These are bound to "document" to cover all * elements whose state changes. Events sent to elements within the page * bubble up to these handlers. We use this system so that themes and modules * can override these state change handlers for particular parts of a page. */ var $document = $(document); $document.on('state:disabled', function (e) { // Only act when this change was triggered by a dependency and not by the // element monitoring itself. if (e.trigger) { $(e.target) .prop('disabled', e.value) .closest('.js-form-item, .js-form-submit, .js-form-wrapper').toggleClass('form-disabled', e.value) .find('select, input, textarea').prop('disabled', e.value); // Note: WebKit nightlies don't reflect that change correctly. // See https://bugs.webkit.org/show_bug.cgi?id=23789 } }); $document.on('state:required', function (e) { if (e.trigger) { if (e.value) { var label = 'label' + (e.target.id ? '[for=' + e.target.id + ']' : ''); var $label = $(e.target).attr({'required': 'required', 'aria-required': 'aria-required'}).closest('.js-form-item, .js-form-wrapper').find(label); // Avoids duplicate required markers on initialization. if (!$label.hasClass('js-form-required').length) { $label.addClass('js-form-required form-required'); } } else { $(e.target).removeAttr('required aria-required').closest('.js-form-item, .js-form-wrapper').find('label.js-form-required').removeClass('js-form-required form-required'); } } }); $document.on('state:visible', function (e) { if (e.trigger) { $(e.target).closest('.js-form-item, .js-form-submit, .js-form-wrapper').toggle(e.value); } }); $document.on('state:checked', function (e) { if (e.trigger) { $(e.target).prop('checked', e.value); } }); $document.on('state:collapsed', function (e) { if (e.trigger) { if ($(e.target).is('[open]') === e.value) { $(e.target).find('> summary').trigger('click'); } } }); /** * These are helper functions implementing addition "operators" and don't * implement any logic that is particular to states. */ /** * Bitwise AND with a third undefined state. * * @function Drupal.states~ternary * * @param {*} a * Value a. * @param {*} b * Value b * * @return {bool} * The result. */ function ternary(a, b) { if (typeof a === 'undefined') { return b; } else if (typeof b === 'undefined') { return a; } else { return a && b; } } /** * Inverts a (if it's not undefined) when invertState is true. * * @function Drupal.states~invert * * @param {*} a * The value to maybe invert. * @param {bool} invertState * Whether to invert state or not. * * @return {bool} * The result. */ function invert(a, invertState) { return (invertState && typeof a !== 'undefined') ? !a : a; } /** * Compares two values while ignoring undefined values. * * @function Drupal.states~compare * * @param {*} a * Value a. * @param {*} b * Value b. * * @return {bool} * The comparison result. */ function compare(a, b) { if (a === b) { return typeof a === 'undefined' ? a : true; } else { return typeof a === 'undefined' || typeof b === 'undefined'; } } })(jQuery, Drupal); ; /** * @file * Adapted from underscore.js with the addition Drupal namespace. */ /** * Limits the invocations of a function in a given time frame. * * The debounce function wrapper should be used sparingly. One clear use case * is limiting the invocation of a callback attached to the window resize event. * * Before using the debounce function wrapper, consider first whether the * callback could be attached to an event that fires less frequently or if the * function can be written in such a way that it is only invoked under specific * conditions. * * @param {function} func * The function to be invoked. * @param {number} wait * The time period within which the callback function should only be * invoked once. For example if the wait period is 250ms, then the callback * will only be called at most 4 times per second. * @param {bool} immediate * Whether we wait at the beginning or end to execute the function. * * @return {function} * The debounced function. */ Drupal.debounce = function (func, wait, immediate) { 'use strict'; var timeout; var result; return function () { var context = this; var args = arguments; var later = function () { timeout = null; if (!immediate) { result = func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; }; }; ; /*! jquery.cookie v1.4.1 | MIT */ !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});; /** * @file * Form features. */ /** * Triggers when a value in the form changed. * * The event triggers when content is typed or pasted in a text field, before * the change event triggers. * * @event formUpdated */ (function ($, Drupal, debounce) { 'use strict'; /** * Retrieves the summary for the first element. * * @return {string} * The text of the summary. */ $.fn.drupalGetSummary = function () { var callback = this.data('summaryCallback'); return (this[0] && callback) ? $.trim(callback(this[0])) : ''; }; /** * Sets the summary for all matched elements. * * @param {function} callback * Either a function that will be called each time the summary is * retrieved or a string (which is returned each time). * * @return {jQuery} * jQuery collection of the current element. * * @fires event:summaryUpdated * * @listens event:formUpdated */ $.fn.drupalSetSummary = function (callback) { var self = this; // To facilitate things, the callback should always be a function. If it's // not, we wrap it into an anonymous function which just returns the value. if (typeof callback !== 'function') { var val = callback; callback = function () { return val; }; } return this .data('summaryCallback', callback) // To prevent duplicate events, the handlers are first removed and then // (re-)added. .off('formUpdated.summary') .on('formUpdated.summary', function () { self.trigger('summaryUpdated'); }) // The actual summaryUpdated handler doesn't fire when the callback is // changed, so we have to do this manually. .trigger('summaryUpdated'); }; /** * Prevents consecutive form submissions of identical form values. * * Repetitive form submissions that would submit the identical form values * are prevented, unless the form values are different to the previously * submitted values. * * This is a simplified re-implementation of a user-agent behavior that * should be natively supported by major web browsers, but at this time, only * Firefox has a built-in protection. * * A form value-based approach ensures that the constraint is triggered for * consecutive, identical form submissions only. Compared to that, a form * button-based approach would (1) rely on [visible] buttons to exist where * technically not required and (2) require more complex state management if * there are multiple buttons in a form. * * This implementation is based on form-level submit events only and relies * on jQuery's serialize() method to determine submitted form values. As such, * the following limitations exist: * * - Event handlers on form buttons that preventDefault() do not receive a * double-submit protection. That is deemed to be fine, since such button * events typically trigger reversible client-side or server-side * operations that are local to the context of a form only. * - Changed values in advanced form controls, such as file inputs, are not * part of the form values being compared between consecutive form submits * (due to limitations of jQuery.serialize()). That is deemed to be * acceptable, because if the user forgot to attach a file, then the size of * HTTP payload will most likely be small enough to be fully passed to the * server endpoint within (milli)seconds. If a user mistakenly attached a * wrong file and is technically versed enough to cancel the form submission * (and HTTP payload) in order to attach a different file, then that * edge-case is not supported here. * * Lastly, all forms submitted via HTTP GET are idempotent by definition of * HTTP standards, so excluded in this implementation. * * @type {Drupal~behavior} */ Drupal.behaviors.formSingleSubmit = { attach: function () { function onFormSubmit(e) { var $form = $(e.currentTarget); var formValues = $form.serialize(); var previousValues = $form.attr('data-drupal-form-submit-last'); if (previousValues === formValues) { e.preventDefault(); } else { $form.attr('data-drupal-form-submit-last', formValues); } } $('body').once('form-single-submit') .on('submit.singleSubmit', 'form:not([method~="GET"])', onFormSubmit); } }; /** * Sends a 'formUpdated' event each time a form element is modified. * * @param {HTMLElement} element * The element to trigger a form updated event on. * * @fires event:formUpdated */ function triggerFormUpdated(element) { $(element).trigger('formUpdated'); } /** * Collects the IDs of all form fields in the given form. * * @param {HTMLFormElement} form * The form element to search. * * @return {Array} * Array of IDs for form fields. */ function fieldsList(form) { var $fieldList = $(form).find('[name]').map(function (index, element) { // We use id to avoid name duplicates on radio fields and filter out // elements with a name but no id. return element.getAttribute('id'); }); // Return a true array. return $.makeArray($fieldList); } /** * Triggers the 'formUpdated' event on form elements when they are modified. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches formUpdated behaviors. * @prop {Drupal~behaviorDetach} detach * Detaches formUpdated behaviors. * * @fires event:formUpdated */ Drupal.behaviors.formUpdated = { attach: function (context) { var $context = $(context); var contextIsForm = $context.is('form'); var $forms = (contextIsForm ? $context : $context.find('form')).once('form-updated'); var formFields; if ($forms.length) { // Initialize form behaviors, use $.makeArray to be able to use native // forEach array method and have the callback parameters in the right // order. $.makeArray($forms).forEach(function (form) { var events = 'change.formUpdated input.formUpdated '; var eventHandler = debounce(function (event) { triggerFormUpdated(event.target); }, 300); formFields = fieldsList(form).join(','); form.setAttribute('data-drupal-form-fields', formFields); $(form).on(events, eventHandler); }); } // On ajax requests context is the form element. if (contextIsForm) { formFields = fieldsList(context).join(','); // @todo replace with form.getAttribute() when #1979468 is in. var currentFields = $(context).attr('data-drupal-form-fields'); // If there has been a change in the fields or their order, trigger // formUpdated. if (formFields !== currentFields) { triggerFormUpdated(context); } } }, detach: function (context, settings, trigger) { var $context = $(context); var contextIsForm = $context.is('form'); if (trigger === 'unload') { var $forms = (contextIsForm ? $context : $context.find('form')).removeOnce('form-updated'); if ($forms.length) { $.makeArray($forms).forEach(function (form) { form.removeAttribute('data-drupal-form-fields'); $(form).off('.formUpdated'); }); } } } }; /** * Prepopulate form fields with information from the visitor browser. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the behavior for filling user info from browser. */ Drupal.behaviors.fillUserInfoFromBrowser = { attach: function (context, settings) { var userInfo = ['name', 'mail', 'homepage']; var $forms = $('[data-user-info-from-browser]').once('user-info-from-browser'); if ($forms.length) { userInfo.map(function (info) { var $element = $forms.find('[name=' + info + ']'); var browserData = localStorage.getItem('Drupal.visitor.' + info); var emptyOrDefault = ($element.val() === '' || ($element.attr('data-drupal-default-value') === $element.val())); if ($element.length && emptyOrDefault && browserData) { $element.val(browserData); } }); } $forms.on('submit', function () { userInfo.map(function (info) { var $element = $forms.find('[name=' + info + ']'); if ($element.length) { localStorage.setItem('Drupal.visitor.' + info, $element.val()); } }); }); } }; })(jQuery, Drupal, Drupal.debounce); ; /** * @file * Add aria attribute handling for details and summary elements. */ (function ($, Drupal) { 'use strict'; /** * Handles `aria-expanded` and `aria-pressed` attributes on details elements. * * @type {Drupal~behavior} */ Drupal.behaviors.detailsAria = { attach: function () { $('body').once('detailsAria').on('click.detailsAria', 'summary', function (event) { var $summary = $(event.currentTarget); var open = $(event.currentTarget.parentNode).attr('open') === 'open' ? 'false' : 'true'; $summary.attr({ 'aria-expanded': open, 'aria-pressed': open }); }); } }; })(jQuery, Drupal); ; /** * @file * Polyfill for HTML5 details elements. */ (function ($, Modernizr, Drupal) { 'use strict'; /** * The collapsible details object represents a single details element. * * @constructor Drupal.CollapsibleDetails * * @param {HTMLElement} node * The details element. */ function CollapsibleDetails(node) { this.$node = $(node); this.$node.data('details', this); // Expand details if there are errors inside, or if it contains an // element that is targeted by the URI fragment identifier. var anchor = location.hash && location.hash !== '#' ? ', ' + location.hash : ''; if (this.$node.find('.error' + anchor).length) { this.$node.attr('open', true); } // Initialize and setup the summary, this.setupSummary(); // Initialize and setup the legend. this.setupLegend(); } $.extend(CollapsibleDetails, /** @lends Drupal.CollapsibleDetails */{ /** * Holds references to instantiated CollapsibleDetails objects. * * @type {Array.<Drupal.CollapsibleDetails>} */ instances: [] }); $.extend(CollapsibleDetails.prototype, /** @lends Drupal.CollapsibleDetails# */{ /** * Initialize and setup summary events and markup. * * @fires event:summaryUpdated * * @listens event:summaryUpdated */ setupSummary: function () { this.$summary = $('<span class="summary"></span>'); this.$node .on('summaryUpdated', $.proxy(this.onSummaryUpdated, this)) .trigger('summaryUpdated'); }, /** * Initialize and setup legend markup. */ setupLegend: function () { // Turn the summary into a clickable link. var $legend = this.$node.find('> summary'); $('<span class="details-summary-prefix visually-hidden"></span>') .append(this.$node.attr('open') ? Drupal.t('Hide') : Drupal.t('Show')) .prependTo($legend) .after(document.createTextNode(' ')); // .wrapInner() does not retain bound events. $('<a class="details-title"></a>') .attr('href', '#' + this.$node.attr('id')) .prepend($legend.contents()) .appendTo($legend); $legend .append(this.$summary) .on('click', $.proxy(this.onLegendClick, this)); }, /** * Handle legend clicks. * * @param {jQuery.Event} e * The event triggered. */ onLegendClick: function (e) { this.toggle(); e.preventDefault(); }, /** * Update summary. */ onSummaryUpdated: function () { var text = $.trim(this.$node.drupalGetSummary()); this.$summary.html(text ? ' (' + text + ')' : ''); }, /** * Toggle the visibility of a details element using smooth animations. */ toggle: function () { var isOpen = !!this.$node.attr('open'); var $summaryPrefix = this.$node.find('> summary span.details-summary-prefix'); if (isOpen) { $summaryPrefix.html(Drupal.t('Show')); } else { $summaryPrefix.html(Drupal.t('Hide')); } // Delay setting the attribute to emulate chrome behavior and make // details-aria.js work as expected with this polyfill. setTimeout(function () { this.$node.attr('open', !isOpen); }.bind(this), 0); } }); /** * Polyfill HTML5 details element. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches behavior for the details element. */ Drupal.behaviors.collapse = { attach: function (context) { if (Modernizr.details) { return; } var $collapsibleDetails = $(context).find('details').once('collapse').addClass('collapse-processed'); if ($collapsibleDetails.length) { for (var i = 0; i < $collapsibleDetails.length; i++) { CollapsibleDetails.instances.push(new CollapsibleDetails($collapsibleDetails[i])); } } } }; // Expose constructor in the public space. Drupal.CollapsibleDetails = CollapsibleDetails; })(jQuery, Modernizr, Drupal); ; /** * @file * Provides JavaScript additions to the managed file field type. * * This file provides progress bar support (if available), popup windows for * file previews, and disabling of other file fields during Ajax uploads (which * prevents separate file fields from accidentally uploading files). */ (function ($, Drupal) { 'use strict'; /** * Attach behaviors to the file fields passed in the settings. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches validation for file extensions. * @prop {Drupal~behaviorDetach} detach * Detaches validation for file extensions. */ Drupal.behaviors.fileValidateAutoAttach = { attach: function (context, settings) { var $context = $(context); var elements; function initFileValidation(selector) { $context.find(selector) .once('fileValidate') .on('change.fileValidate', {extensions: elements[selector]}, Drupal.file.validateExtension); } if (settings.file && settings.file.elements) { elements = settings.file.elements; Object.keys(elements).forEach(initFileValidation); } }, detach: function (context, settings, trigger) { var $context = $(context); var elements; function removeFileValidation(selector) { $context.find(selector) .removeOnce('fileValidate') .off('change.fileValidate', Drupal.file.validateExtension); } if (trigger === 'unload' && settings.file && settings.file.elements) { elements = settings.file.elements; Object.keys(elements).forEach(removeFileValidation); } } }; /** * Attach behaviors to file element auto upload. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches triggers for the upload button. * @prop {Drupal~behaviorDetach} detach * Detaches auto file upload trigger. */ Drupal.behaviors.fileAutoUpload = { attach: function (context) { $(context).find('input[type="file"]').once('auto-file-upload').on('change.autoFileUpload', Drupal.file.triggerUploadButton); }, detach: function (context, setting, trigger) { if (trigger === 'unload') { $(context).find('input[type="file"]').removeOnce('auto-file-upload').off('.autoFileUpload'); } } }; /** * Attach behaviors to the file upload and remove buttons. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches form submit events. * @prop {Drupal~behaviorDetach} detach * Detaches form submit events. */ Drupal.behaviors.fileButtons = { attach: function (context) { var $context = $(context); $context.find('.js-form-submit').on('mousedown', Drupal.file.disableFields); $context.find('.js-form-managed-file .js-form-submit').on('mousedown', Drupal.file.progressBar); }, detach: function (context) { var $context = $(context); $context.find('.js-form-submit').off('mousedown', Drupal.file.disableFields); $context.find('.js-form-managed-file .js-form-submit').off('mousedown', Drupal.file.progressBar); } }; /** * Attach behaviors to links within managed file elements for preview windows. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches triggers. * @prop {Drupal~behaviorDetach} detach * Detaches triggers. */ Drupal.behaviors.filePreviewLinks = { attach: function (context) { $(context).find('div.js-form-managed-file .file a').on('click', Drupal.file.openInNewWindow); }, detach: function (context) { $(context).find('div.js-form-managed-file .file a').off('click', Drupal.file.openInNewWindow); } }; /** * File upload utility functions. * * @namespace */ Drupal.file = Drupal.file || { /** * Client-side file input validation of file extensions. * * @name Drupal.file.validateExtension * * @param {jQuery.Event} event * The event triggered. For example `change.fileValidate`. */ validateExtension: function (event) { event.preventDefault(); // Remove any previous errors. $('.file-upload-js-error').remove(); // Add client side validation for the input[type=file]. var extensionPattern = event.data.extensions.replace(/,\s*/g, '|'); if (extensionPattern.length > 1 && this.value.length > 0) { var acceptableMatch = new RegExp('\\.(' + extensionPattern + ')$', 'gi'); if (!acceptableMatch.test(this.value)) { var error = Drupal.t('The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.', { // According to the specifications of HTML5, a file upload control // should not reveal the real local path to the file that a user // has selected. Some web browsers implement this restriction by // replacing the local path with "C:\fakepath\", which can cause // confusion by leaving the user thinking perhaps Drupal could not // find the file because it messed up the file path. To avoid this // confusion, therefore, we strip out the bogus fakepath string. '%filename': this.value.replace('C:\\fakepath\\', ''), '%extensions': extensionPattern.replace(/\|/g, ', ') }); $(this).closest('div.js-form-managed-file').prepend('<div class="messages messages--error file-upload-js-error" aria-live="polite">' + error + '</div>'); this.value = ''; // Cancel all other change event handlers. event.stopImmediatePropagation(); } } }, /** * Trigger the upload_button mouse event to auto-upload as a managed file. * * @name Drupal.file.triggerUploadButton * * @param {jQuery.Event} event * The event triggered. For example `change.autoFileUpload`. */ triggerUploadButton: function (event) { $(event.target).closest('.js-form-managed-file').find('.js-form-submit').trigger('mousedown'); }, /** * Prevent file uploads when using buttons not intended to upload. * * @name Drupal.file.disableFields * * @param {jQuery.Event} event * The event triggered, most likely a `mousedown` event. */ disableFields: function (event) { var $clickedButton = $(this).findOnce('ajax'); // Only disable upload fields for Ajax buttons. if (!$clickedButton.length) { return; } // Check if we're working with an "Upload" button. var $enabledFields = []; if ($clickedButton.closest('div.js-form-managed-file').length > 0) { $enabledFields = $clickedButton.closest('div.js-form-managed-file').find('input.js-form-file'); } // Temporarily disable upload fields other than the one we're currently // working with. Filter out fields that are already disabled so that they // do not get enabled when we re-enable these fields at the end of // behavior processing. Re-enable in a setTimeout set to a relatively // short amount of time (1 second). All the other mousedown handlers // (like Drupal's Ajax behaviors) are executed before any timeout // functions are called, so we don't have to worry about the fields being // re-enabled too soon. @todo If the previous sentence is true, why not // set the timeout to 0? var $fieldsToTemporarilyDisable = $('div.js-form-managed-file input.js-form-file').not($enabledFields).not(':disabled'); $fieldsToTemporarilyDisable.prop('disabled', true); setTimeout(function () { $fieldsToTemporarilyDisable.prop('disabled', false); }, 1000); }, /** * Add progress bar support if possible. * * @name Drupal.file.progressBar * * @param {jQuery.Event} event * The event triggered, most likely a `mousedown` event. */ progressBar: function (event) { var $clickedButton = $(this); var $progressId = $clickedButton.closest('div.js-form-managed-file').find('input.file-progress'); if ($progressId.length) { var originalName = $progressId.attr('name'); // Replace the name with the required identifier. $progressId.attr('name', originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0]); // Restore the original name after the upload begins. setTimeout(function () { $progressId.attr('name', originalName); }, 1000); } // Show the progress bar if the upload takes longer than half a second. setTimeout(function () { $clickedButton.closest('div.js-form-managed-file').find('div.ajax-progress-bar').slideDown(); }, 500); }, /** * Open links to files within forms in a new window. * * @name Drupal.file.openInNewWindow * * @param {jQuery.Event} event * The event triggered, most likely a `click` event. */ openInNewWindow: function (event) { event.preventDefault(); $(this).attr('target', '_blank'); window.open(this.href, 'filePreview', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550'); } }; })(jQuery, Drupal); ; /*! * jQuery Form Plugin * version: 3.51.0-2014.06.20 * Requires jQuery v1.5 or later * Copyright (c) 2014 M. Alsup * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses. * https://github.com/malsup/form#copyright-and-license */ !function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):e("undefined"!=typeof jQuery?jQuery:window.Zepto)}(function(e){"use strict";function t(t){var r=t.data;t.isDefaultPrevented()||(t.preventDefault(),e(t.target).ajaxSubmit(r))}function r(t){var r=t.target,a=e(r);if(!a.is("[type=submit],[type=image]")){var n=a.closest("[type=submit]");if(0===n.length)return;r=n[0]}var i=this;if(i.clk=r,"image"==r.type)if(void 0!==t.offsetX)i.clk_x=t.offsetX,i.clk_y=t.offsetY;else if("function"==typeof e.fn.offset){var o=a.offset();i.clk_x=t.pageX-o.left,i.clk_y=t.pageY-o.top}else i.clk_x=t.pageX-r.offsetLeft,i.clk_y=t.pageY-r.offsetTop;setTimeout(function(){i.clk=i.clk_x=i.clk_y=null},100)}function a(){if(e.fn.ajaxSubmit.debug){var t="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(t):window.opera&&window.opera.postError&&window.opera.postError(t)}}var n={};n.fileapi=void 0!==e("<input type='file'/>").get(0).files,n.formdata=void 0!==window.FormData;var i=!!e.fn.prop;e.fn.attr2=function(){if(!i)return this.attr.apply(this,arguments);var e=this.prop.apply(this,arguments);return e&&e.jquery||"string"==typeof e?e:this.attr.apply(this,arguments)},e.fn.ajaxSubmit=function(t){function r(r){var a,n,i=e.param(r,t.traditional).split("&"),o=i.length,s=[];for(a=0;o>a;a++)i[a]=i[a].replace(/\+/g," "),n=i[a].split("="),s.push([decodeURIComponent(n[0]),decodeURIComponent(n[1])]);return s}function o(a){for(var n=new FormData,i=0;i<a.length;i++)n.append(a[i].name,a[i].value);if(t.extraData){var o=r(t.extraData);for(i=0;i<o.length;i++)o[i]&&n.append(o[i][0],o[i][1])}t.data=null;var s=e.extend(!0,{},e.ajaxSettings,t,{contentType:!1,processData:!1,cache:!1,type:u||"POST"});t.uploadProgress&&(s.xhr=function(){var r=e.ajaxSettings.xhr();return r.upload&&r.upload.addEventListener("progress",function(e){var r=0,a=e.loaded||e.position,n=e.total;e.lengthComputable&&(r=Math.ceil(a/n*100)),t.uploadProgress(e,a,n,r)},!1),r}),s.data=null;var c=s.beforeSend;return s.beforeSend=function(e,r){r.data=t.formData?t.formData:n,c&&c.call(this,e,r)},e.ajax(s)}function s(r){function n(e){var t=null;try{e.contentWindow&&(t=e.contentWindow.document)}catch(r){a("cannot get iframe.contentWindow document: "+r)}if(t)return t;try{t=e.contentDocument?e.contentDocument:e.document}catch(r){a("cannot get iframe.contentDocument: "+r),t=e.document}return t}function o(){function t(){try{var e=n(g).readyState;a("state = "+e),e&&"uninitialized"==e.toLowerCase()&&setTimeout(t,50)}catch(r){a("Server abort: ",r," (",r.name,")"),s(k),j&&clearTimeout(j),j=void 0}}var r=f.attr2("target"),i=f.attr2("action"),o="multipart/form-data",c=f.attr("enctype")||f.attr("encoding")||o;w.setAttribute("target",p),(!u||/post/i.test(u))&&w.setAttribute("method","POST"),i!=m.url&&w.setAttribute("action",m.url),m.skipEncodingOverride||u&&!/post/i.test(u)||f.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"}),m.timeout&&(j=setTimeout(function(){T=!0,s(D)},m.timeout));var l=[];try{if(m.extraData)for(var d in m.extraData)m.extraData.hasOwnProperty(d)&&l.push(e.isPlainObject(m.extraData[d])&&m.extraData[d].hasOwnProperty("name")&&m.extraData[d].hasOwnProperty("value")?e('<input type="hidden" name="'+m.extraData[d].name+'">').val(m.extraData[d].value).appendTo(w)[0]:e('<input type="hidden" name="'+d+'">').val(m.extraData[d]).appendTo(w)[0]);m.iframeTarget||v.appendTo("body"),g.attachEvent?g.attachEvent("onload",s):g.addEventListener("load",s,!1),setTimeout(t,15);try{w.submit()}catch(h){var x=document.createElement("form").submit;x.apply(w)}}finally{w.setAttribute("action",i),w.setAttribute("enctype",c),r?w.setAttribute("target",r):f.removeAttr("target"),e(l).remove()}}function s(t){if(!x.aborted&&!F){if(M=n(g),M||(a("cannot access response document"),t=k),t===D&&x)return x.abort("timeout"),void S.reject(x,"timeout");if(t==k&&x)return x.abort("server abort"),void S.reject(x,"error","server abort");if(M&&M.location.href!=m.iframeSrc||T){g.detachEvent?g.detachEvent("onload",s):g.removeEventListener("load",s,!1);var r,i="success";try{if(T)throw"timeout";var o="xml"==m.dataType||M.XMLDocument||e.isXMLDoc(M);if(a("isXml="+o),!o&&window.opera&&(null===M.body||!M.body.innerHTML)&&--O)return a("requeing onLoad callback, DOM not available"),void setTimeout(s,250);var u=M.body?M.body:M.documentElement;x.responseText=u?u.innerHTML:null,x.responseXML=M.XMLDocument?M.XMLDocument:M,o&&(m.dataType="xml"),x.getResponseHeader=function(e){var t={"content-type":m.dataType};return t[e.toLowerCase()]},u&&(x.status=Number(u.getAttribute("status"))||x.status,x.statusText=u.getAttribute("statusText")||x.statusText);var c=(m.dataType||"").toLowerCase(),l=/(json|script|text)/.test(c);if(l||m.textarea){var f=M.getElementsByTagName("textarea")[0];if(f)x.responseText=f.value,x.status=Number(f.getAttribute("status"))||x.status,x.statusText=f.getAttribute("statusText")||x.statusText;else if(l){var p=M.getElementsByTagName("pre")[0],h=M.getElementsByTagName("body")[0];p?x.responseText=p.textContent?p.textContent:p.innerText:h&&(x.responseText=h.textContent?h.textContent:h.innerText)}}else"xml"==c&&!x.responseXML&&x.responseText&&(x.responseXML=X(x.responseText));try{E=_(x,c,m)}catch(y){i="parsererror",x.error=r=y||i}}catch(y){a("error caught: ",y),i="error",x.error=r=y||i}x.aborted&&(a("upload aborted"),i=null),x.status&&(i=x.status>=200&&x.status<300||304===x.status?"success":"error"),"success"===i?(m.success&&m.success.call(m.context,E,"success",x),S.resolve(x.responseText,"success",x),d&&e.event.trigger("ajaxSuccess",[x,m])):i&&(void 0===r&&(r=x.statusText),m.error&&m.error.call(m.context,x,i,r),S.reject(x,"error",r),d&&e.event.trigger("ajaxError",[x,m,r])),d&&e.event.trigger("ajaxComplete",[x,m]),d&&!--e.active&&e.event.trigger("ajaxStop"),m.complete&&m.complete.call(m.context,x,i),F=!0,m.timeout&&clearTimeout(j),setTimeout(function(){m.iframeTarget?v.attr("src",m.iframeSrc):v.remove(),x.responseXML=null},100)}}}var c,l,m,d,p,v,g,x,y,b,T,j,w=f[0],S=e.Deferred();if(S.abort=function(e){x.abort(e)},r)for(l=0;l<h.length;l++)c=e(h[l]),i?c.prop("disabled",!1):c.removeAttr("disabled");if(m=e.extend(!0,{},e.ajaxSettings,t),m.context=m.context||m,p="jqFormIO"+(new Date).getTime(),m.iframeTarget?(v=e(m.iframeTarget),b=v.attr2("name"),b?p=b:v.attr2("name",p)):(v=e('<iframe name="'+p+'" src="'+m.iframeSrc+'" />'),v.css({position:"absolute",top:"-1000px",left:"-1000px"})),g=v[0],x={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(t){var r="timeout"===t?"timeout":"aborted";a("aborting upload... "+r),this.aborted=1;try{g.contentWindow.document.execCommand&&g.contentWindow.document.execCommand("Stop")}catch(n){}v.attr("src",m.iframeSrc),x.error=r,m.error&&m.error.call(m.context,x,r,t),d&&e.event.trigger("ajaxError",[x,m,r]),m.complete&&m.complete.call(m.context,x,r)}},d=m.global,d&&0===e.active++&&e.event.trigger("ajaxStart"),d&&e.event.trigger("ajaxSend",[x,m]),m.beforeSend&&m.beforeSend.call(m.context,x,m)===!1)return m.global&&e.active--,S.reject(),S;if(x.aborted)return S.reject(),S;y=w.clk,y&&(b=y.name,b&&!y.disabled&&(m.extraData=m.extraData||{},m.extraData[b]=y.value,"image"==y.type&&(m.extraData[b+".x"]=w.clk_x,m.extraData[b+".y"]=w.clk_y)));var D=1,k=2,A=e("meta[name=csrf-token]").attr("content"),L=e("meta[name=csrf-param]").attr("content");L&&A&&(m.extraData=m.extraData||{},m.extraData[L]=A),m.forceSync?o():setTimeout(o,10);var E,M,F,O=50,X=e.parseXML||function(e,t){return window.ActiveXObject?(t=new ActiveXObject("Microsoft.XMLDOM"),t.async="false",t.loadXML(e)):t=(new DOMParser).parseFromString(e,"text/xml"),t&&t.documentElement&&"parsererror"!=t.documentElement.nodeName?t:null},C=e.parseJSON||function(e){return window.eval("("+e+")")},_=function(t,r,a){var n=t.getResponseHeader("content-type")||"",i="xml"===r||!r&&n.indexOf("xml")>=0,o=i?t.responseXML:t.responseText;return i&&"parsererror"===o.documentElement.nodeName&&e.error&&e.error("parsererror"),a&&a.dataFilter&&(o=a.dataFilter(o,r)),"string"==typeof o&&("json"===r||!r&&n.indexOf("json")>=0?o=C(o):("script"===r||!r&&n.indexOf("javascript")>=0)&&e.globalEval(o)),o};return S}if(!this.length)return a("ajaxSubmit: skipping submit process - no element selected"),this;var u,c,l,f=this;"function"==typeof t?t={success:t}:void 0===t&&(t={}),u=t.type||this.attr2("method"),c=t.url||this.attr2("action"),l="string"==typeof c?e.trim(c):"",l=l||window.location.href||"",l&&(l=(l.match(/^([^#]+)/)||[])[1]),t=e.extend(!0,{url:l,success:e.ajaxSettings.success,type:u||e.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},t);var m={};if(this.trigger("form-pre-serialize",[this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(t.beforeSerialize&&t.beforeSerialize(this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSerialize callback"),this;var d=t.traditional;void 0===d&&(d=e.ajaxSettings.traditional);var p,h=[],v=this.formToArray(t.semantic,h);if(t.data&&(t.extraData=t.data,p=e.param(t.data,d)),t.beforeSubmit&&t.beforeSubmit(v,this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSubmit callback"),this;if(this.trigger("form-submit-validate",[v,this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;var g=e.param(v,d);p&&(g=g?g+"&"+p:p),"GET"==t.type.toUpperCase()?(t.url+=(t.url.indexOf("?")>=0?"&":"?")+g,t.data=null):t.data=g;var x=[];if(t.resetForm&&x.push(function(){f.resetForm()}),t.clearForm&&x.push(function(){f.clearForm(t.includeHidden)}),!t.dataType&&t.target){var y=t.success||function(){};x.push(function(r){var a=t.replaceTarget?"replaceWith":"html";e(t.target)[a](r).each(y,arguments)})}else t.success&&x.push(t.success);if(t.success=function(e,r,a){for(var n=t.context||this,i=0,o=x.length;o>i;i++)x[i].apply(n,[e,r,a||f,f])},t.error){var b=t.error;t.error=function(e,r,a){var n=t.context||this;b.apply(n,[e,r,a,f])}}if(t.complete){var T=t.complete;t.complete=function(e,r){var a=t.context||this;T.apply(a,[e,r,f])}}var j=e("input[type=file]:enabled",this).filter(function(){return""!==e(this).val()}),w=j.length>0,S="multipart/form-data",D=f.attr("enctype")==S||f.attr("encoding")==S,k=n.fileapi&&n.formdata;a("fileAPI :"+k);var A,L=(w||D)&&!k;t.iframe!==!1&&(t.iframe||L)?t.closeKeepAlive?e.get(t.closeKeepAlive,function(){A=s(v)}):A=s(v):A=(w||D)&&k?o(v):e.ajax(t),f.removeData("jqxhr").data("jqxhr",A);for(var E=0;E<h.length;E++)h[E]=null;return this.trigger("form-submit-notify",[this,t]),this},e.fn.ajaxForm=function(n){if(n=n||{},n.delegation=n.delegation&&e.isFunction(e.fn.on),!n.delegation&&0===this.length){var i={s:this.selector,c:this.context};return!e.isReady&&i.s?(a("DOM not ready, queuing ajaxForm"),e(function(){e(i.s,i.c).ajaxForm(n)}),this):(a("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)")),this)}return n.delegation?(e(document).off("submit.form-plugin",this.selector,t).off("click.form-plugin",this.selector,r).on("submit.form-plugin",this.selector,n,t).on("click.form-plugin",this.selector,n,r),this):this.ajaxFormUnbind().bind("submit.form-plugin",n,t).bind("click.form-plugin",n,r)},e.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")},e.fn.formToArray=function(t,r){var a=[];if(0===this.length)return a;var i,o=this[0],s=this.attr("id"),u=t?o.getElementsByTagName("*"):o.elements;if(u&&!/MSIE [678]/.test(navigator.userAgent)&&(u=e(u).get()),s&&(i=e(':input[form="'+s+'"]').get(),i.length&&(u=(u||[]).concat(i))),!u||!u.length)return a;var c,l,f,m,d,p,h;for(c=0,p=u.length;p>c;c++)if(d=u[c],f=d.name,f&&!d.disabled)if(t&&o.clk&&"image"==d.type)o.clk==d&&(a.push({name:f,value:e(d).val(),type:d.type}),a.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}));else if(m=e.fieldValue(d,!0),m&&m.constructor==Array)for(r&&r.push(d),l=0,h=m.length;h>l;l++)a.push({name:f,value:m[l]});else if(n.fileapi&&"file"==d.type){r&&r.push(d);var v=d.files;if(v.length)for(l=0;l<v.length;l++)a.push({name:f,value:v[l],type:d.type});else a.push({name:f,value:"",type:d.type})}else null!==m&&"undefined"!=typeof m&&(r&&r.push(d),a.push({name:f,value:m,type:d.type,required:d.required}));if(!t&&o.clk){var g=e(o.clk),x=g[0];f=x.name,f&&!x.disabled&&"image"==x.type&&(a.push({name:f,value:g.val()}),a.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}))}return a},e.fn.formSerialize=function(t){return e.param(this.formToArray(t))},e.fn.fieldSerialize=function(t){var r=[];return this.each(function(){var a=this.name;if(a){var n=e.fieldValue(this,t);if(n&&n.constructor==Array)for(var i=0,o=n.length;o>i;i++)r.push({name:a,value:n[i]});else null!==n&&"undefined"!=typeof n&&r.push({name:this.name,value:n})}}),e.param(r)},e.fn.fieldValue=function(t){for(var r=[],a=0,n=this.length;n>a;a++){var i=this[a],o=e.fieldValue(i,t);null===o||"undefined"==typeof o||o.constructor==Array&&!o.length||(o.constructor==Array?e.merge(r,o):r.push(o))}return r},e.fieldValue=function(t,r){var a=t.name,n=t.type,i=t.tagName.toLowerCase();if(void 0===r&&(r=!0),r&&(!a||t.disabled||"reset"==n||"button"==n||("checkbox"==n||"radio"==n)&&!t.checked||("submit"==n||"image"==n)&&t.form&&t.form.clk!=t||"select"==i&&-1==t.selectedIndex))return null;if("select"==i){var o=t.selectedIndex;if(0>o)return null;for(var s=[],u=t.options,c="select-one"==n,l=c?o+1:u.length,f=c?o:0;l>f;f++){var m=u[f];if(m.selected){var d=m.value;if(d||(d=m.attributes&&m.attributes.value&&!m.attributes.value.specified?m.text:m.value),c)return d;s.push(d)}}return s}return e(t).val()},e.fn.clearForm=function(t){return this.each(function(){e("input,select,textarea",this).clearFields(t)})},e.fn.clearFields=e.fn.clearInputs=function(t){var r=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var a=this.type,n=this.tagName.toLowerCase();r.test(a)||"textarea"==n?this.value="":"checkbox"==a||"radio"==a?this.checked=!1:"select"==n?this.selectedIndex=-1:"file"==a?/MSIE/.test(navigator.userAgent)?e(this).replaceWith(e(this).clone(!0)):e(this).val(""):t&&(t===!0&&/hidden/.test(a)||"string"==typeof t&&e(this).is(t))&&(this.value="")})},e.fn.resetForm=function(){return this.each(function(){("function"==typeof this.reset||"object"==typeof this.reset&&!this.reset.nodeType)&&this.reset()})},e.fn.enable=function(e){return void 0===e&&(e=!0),this.each(function(){this.disabled=!e})},e.fn.selected=function(t){return void 0===t&&(t=!0),this.each(function(){var r=this.type;if("checkbox"==r||"radio"==r)this.checked=t;else if("option"==this.tagName.toLowerCase()){var a=e(this).parent("select");t&&a[0]&&"select-one"==a[0].type&&a.find("option").selected(!1),this.selected=t}})},e.fn.ajaxSubmit.debug=!1}); ; /** * @file * Progress bar. */ (function ($, Drupal) { 'use strict'; /** * Theme function for the progress bar. * * @param {string} id * The id for the progress bar. * * @return {string} * The HTML for the progress bar. */ Drupal.theme.progressBar = function (id) { return '<div id="' + id + '" class="progress" aria-live="polite">' + '<div class="progress__label">&nbsp;</div>' + '<div class="progress__track"><div class="progress__bar"></div></div>' + '<div class="progress__percentage"></div>' + '<div class="progress__description">&nbsp;</div>' + '</div>'; }; /** * A progressbar object. Initialized with the given id. Must be inserted into * the DOM afterwards through progressBar.element. * * Method is the function which will perform the HTTP request to get the * progress bar state. Either "GET" or "POST". * * @example * pb = new Drupal.ProgressBar('myProgressBar'); * some_element.appendChild(pb.element); * * @constructor * * @param {string} id * The id for the progressbar. * @param {function} updateCallback * Callback to run on update. * @param {string} method * HTTP method to use. * @param {function} errorCallback * Callback to call on error. */ Drupal.ProgressBar = function (id, updateCallback, method, errorCallback) { this.id = id; this.method = method || 'GET'; this.updateCallback = updateCallback; this.errorCallback = errorCallback; // The WAI-ARIA setting aria-live="polite" will announce changes after // users // have completed their current activity and not interrupt the screen // reader. this.element = $(Drupal.theme('progressBar', id)); }; $.extend(Drupal.ProgressBar.prototype, /** @lends Drupal.ProgressBar# */{ /** * Set the percentage and status message for the progressbar. * * @param {number} percentage * The progress percentage. * @param {string} message * The message to show the user. * @param {string} label * The text for the progressbar label. */ setProgress: function (percentage, message, label) { if (percentage >= 0 && percentage <= 100) { $(this.element).find('div.progress__bar').css('width', percentage + '%'); $(this.element).find('div.progress__percentage').html(percentage + '%'); } $('div.progress__description', this.element).html(message); $('div.progress__label', this.element).html(label); if (this.updateCallback) { this.updateCallback(percentage, message, this); } }, /** * Start monitoring progress via Ajax. * * @param {string} uri * The URI to use for monitoring. * @param {number} delay * The delay for calling the monitoring URI. */ startMonitoring: function (uri, delay) { this.delay = delay; this.uri = uri; this.sendPing(); }, /** * Stop monitoring progress via Ajax. */ stopMonitoring: function () { clearTimeout(this.timer); // This allows monitoring to be stopped from within the callback. this.uri = null; }, /** * Request progress data from server. */ sendPing: function () { if (this.timer) { clearTimeout(this.timer); } if (this.uri) { var pb = this; // When doing a post request, you need non-null data. Otherwise a // HTTP 411 or HTTP 406 (with Apache mod_security) error may result. var uri = this.uri; if (uri.indexOf('?') === -1) { uri += '?'; } else { uri += '&'; } uri += '_format=json'; $.ajax({ type: this.method, url: uri, data: '', dataType: 'json', success: function (progress) { // Display errors. if (progress.status === 0) { pb.displayError(progress.data); return; } // Update display. pb.setProgress(progress.percentage, progress.message, progress.label); // Schedule next timer. pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay); }, error: function (xmlhttp) { var e = new Drupal.AjaxError(xmlhttp, pb.uri); pb.displayError('<pre>' + e.message + '</pre>'); } }); } }, /** * Display errors on the page. * * @param {string} string * The error message to show the user. */ displayError: function (string) { var error = $('<div class="messages messages--error"></div>').html(string); $(this.element).before(error).hide(); if (this.errorCallback) { this.errorCallback(this); } } }); })(jQuery, Drupal); ; /** * @file * Provides Ajax page updating via jQuery $.ajax. * * Ajax is a method of making a request via JavaScript while viewing an HTML * page. The request returns an array of commands encoded in JSON, which is * then executed to make any changes that are necessary to the page. * * Drupal uses this file to enhance form elements with `#ajax['url']` and * `#ajax['wrapper']` properties. If set, this file will automatically be * included to provide Ajax capabilities. */ (function ($, window, Drupal, drupalSettings) { 'use strict'; /** * Attaches the Ajax behavior to each Ajax form element. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Initialize all {@link Drupal.Ajax} objects declared in * `drupalSettings.ajax` or initialize {@link Drupal.Ajax} objects from * DOM elements having the `use-ajax-submit` or `use-ajax` css class. * @prop {Drupal~behaviorDetach} detach * During `unload` remove all {@link Drupal.Ajax} objects related to * the removed content. */ Drupal.behaviors.AJAX = { attach: function (context, settings) { function loadAjaxBehavior(base) { var element_settings = settings.ajax[base]; if (typeof element_settings.selector === 'undefined') { element_settings.selector = '#' + base; } $(element_settings.selector).once('drupal-ajax').each(function () { element_settings.element = this; element_settings.base = base; Drupal.ajax(element_settings); }); } // Load all Ajax behaviors specified in the settings. for (var base in settings.ajax) { if (settings.ajax.hasOwnProperty(base)) { loadAjaxBehavior(base); } } // Bind Ajax behaviors to all items showing the class. $('.use-ajax').once('ajax').each(function () { var element_settings = {}; // Clicked links look better with the throbber than the progress bar. element_settings.progress = {type: 'throbber'}; // For anchor tags, these will go to the target of the anchor rather // than the usual location. var href = $(this).attr('href'); if (href) { element_settings.url = href; element_settings.event = 'click'; } element_settings.dialogType = $(this).data('dialog-type'); element_settings.dialog = $(this).data('dialog-options'); element_settings.base = $(this).attr('id'); element_settings.element = this; Drupal.ajax(element_settings); }); // This class means to submit the form to the action using Ajax. $('.use-ajax-submit').once('ajax').each(function () { var element_settings = {}; // Ajax submits specified in this manner automatically submit to the // normal form action. element_settings.url = $(this.form).attr('action'); // Form submit button clicks need to tell the form what was clicked so // it gets passed in the POST request. element_settings.setClick = true; // Form buttons use the 'click' event rather than mousedown. element_settings.event = 'click'; // Clicked form buttons look better with the throbber than the progress // bar. element_settings.progress = {type: 'throbber'}; element_settings.base = $(this).attr('id'); element_settings.element = this; Drupal.ajax(element_settings); }); }, detach: function (context, settings, trigger) { if (trigger === 'unload') { Drupal.ajax.expired().forEach(function (instance) { // Set this to null and allow garbage collection to reclaim // the memory. Drupal.ajax.instances[instance.instanceIndex] = null; }); } } }; /** * Extends Error to provide handling for Errors in Ajax. * * @constructor * * @augments Error * * @param {XMLHttpRequest} xmlhttp * XMLHttpRequest object used for the failed request. * @param {string} uri * The URI where the error occurred. * @param {string} customMessage * The custom message. */ Drupal.AjaxError = function (xmlhttp, uri, customMessage) { var statusCode; var statusText; var pathText; var responseText; var readyStateText; if (xmlhttp.status) { statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', {'!status': xmlhttp.status}); } else { statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.'); } statusCode += '\n' + Drupal.t('Debugging information follows.'); pathText = '\n' + Drupal.t('Path: !uri', {'!uri': uri}); statusText = ''; // In some cases, when statusCode === 0, xmlhttp.statusText may not be // defined. Unfortunately, testing for it with typeof, etc, doesn't seem to // catch that and the test causes an exception. So we need to catch the // exception here. try { statusText = '\n' + Drupal.t('StatusText: !statusText', {'!statusText': $.trim(xmlhttp.statusText)}); } catch (e) { // Empty. } responseText = ''; // Again, we don't have a way to know for sure whether accessing // xmlhttp.responseText is going to throw an exception. So we'll catch it. try { responseText = '\n' + Drupal.t('ResponseText: !responseText', {'!responseText': $.trim(xmlhttp.responseText)}); } catch (e) { // Empty. } // Make the responseText more readable by stripping HTML tags and newlines. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, ''); responseText = responseText.replace(/[\n]+\s+/g, '\n'); // We don't need readyState except for status == 0. readyStateText = xmlhttp.status === 0 ? ('\n' + Drupal.t('ReadyState: !readyState', {'!readyState': xmlhttp.readyState})) : ''; customMessage = customMessage ? ('\n' + Drupal.t('CustomMessage: !customMessage', {'!customMessage': customMessage})) : ''; /** * Formatted and translated error message. * * @type {string} */ this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText; /** * Used by some browsers to display a more accurate stack trace. * * @type {string} */ this.name = 'AjaxError'; }; Drupal.AjaxError.prototype = new Error(); Drupal.AjaxError.prototype.constructor = Drupal.AjaxError; /** * Provides Ajax page updating via jQuery $.ajax. * * This function is designed to improve developer experience by wrapping the * initialization of {@link Drupal.Ajax} objects and storing all created * objects in the {@link Drupal.ajax.instances} array. * * @example * Drupal.behaviors.myCustomAJAXStuff = { * attach: function (context, settings) { * * var ajaxSettings = { * url: 'my/url/path', * // If the old version of Drupal.ajax() needs to be used those * // properties can be added * base: 'myBase', * element: $(context).find('.someElement') * }; * * var myAjaxObject = Drupal.ajax(ajaxSettings); * * // Declare a new Ajax command specifically for this Ajax object. * myAjaxObject.commands.insert = function (ajax, response, status) { * $('#my-wrapper').append(response.data); * alert('New content was appended to #my-wrapper'); * }; * * // This command will remove this Ajax object from the page. * myAjaxObject.commands.destroyObject = function (ajax, response, status) { * Drupal.ajax.instances[this.instanceIndex] = null; * }; * * // Programmatically trigger the Ajax request. * myAjaxObject.execute(); * } * }; * * @param {object} settings * The settings object passed to {@link Drupal.Ajax} constructor. * @param {string} [settings.base] * Base is passed to {@link Drupal.Ajax} constructor as the 'base' * parameter. * @param {HTMLElement} [settings.element] * Element parameter of {@link Drupal.Ajax} constructor, element on which * event listeners will be bound. * * @return {Drupal.Ajax} * The created Ajax object. * * @see Drupal.AjaxCommands */ Drupal.ajax = function (settings) { if (arguments.length !== 1) { throw new Error('Drupal.ajax() function must be called with one configuration object only'); } // Map those config keys to variables for the old Drupal.ajax function. var base = settings.base || false; var element = settings.element || false; delete settings.base; delete settings.element; // By default do not display progress for ajax calls without an element. if (!settings.progress && !element) { settings.progress = false; } var ajax = new Drupal.Ajax(base, element, settings); ajax.instanceIndex = Drupal.ajax.instances.length; Drupal.ajax.instances.push(ajax); return ajax; }; /** * Contains all created Ajax objects. * * @type {Array.<Drupal.Ajax|null>} */ Drupal.ajax.instances = []; /** * List all objects where the associated element is not in the DOM * * This method ignores {@link Drupal.Ajax} objects not bound to DOM elements * when created with {@link Drupal.ajax}. * * @return {Array.<Drupal.Ajax>} * The list of expired {@link Drupal.Ajax} objects. */ Drupal.ajax.expired = function () { return Drupal.ajax.instances.filter(function (instance) { return instance && instance.element !== false && !document.body.contains(instance.element); }); }; /** * Settings for an Ajax object. * * @typedef {object} Drupal.Ajax~element_settings * * @prop {string} url * Target of the Ajax request. * @prop {?string} [event] * Event bound to settings.element which will trigger the Ajax request. * @prop {bool} [keypress=true] * Triggers a request on keypress events. * @prop {?string} selector * jQuery selector targeting the element to bind events to or used with * {@link Drupal.AjaxCommands}. * @prop {string} [effect='none'] * Name of the jQuery method to use for displaying new Ajax content. * @prop {string|number} [speed='none'] * Speed with which to apply the effect. * @prop {string} [method] * Name of the jQuery method used to insert new content in the targeted * element. * @prop {object} [progress] * Settings for the display of a user-friendly loader. * @prop {string} [progress.type='throbber'] * Type of progress element, core provides `'bar'`, `'throbber'` and * `'fullscreen'`. * @prop {string} [progress.message=Drupal.t('Please wait...')] * Custom message to be used with the bar indicator. * @prop {object} [submit] * Extra data to be sent with the Ajax request. * @prop {bool} [submit.js=true] * Allows the PHP side to know this comes from an Ajax request. * @prop {object} [dialog] * Options for {@link Drupal.dialog}. * @prop {string} [dialogType] * One of `'modal'` or `'dialog'`. * @prop {string} [prevent] * List of events on which to stop default action and stop propagation. */ /** * Ajax constructor. * * The Ajax request returns an array of commands encoded in JSON, which is * then executed to make any changes that are necessary to the page. * * Drupal uses this file to enhance form elements with `#ajax['url']` and * `#ajax['wrapper']` properties. If set, this file will automatically be * included to provide Ajax capabilities. * * @constructor * * @param {string} [base] * Base parameter of {@link Drupal.Ajax} constructor * @param {HTMLElement} [element] * Element parameter of {@link Drupal.Ajax} constructor, element on which * event listeners will be bound. * @param {Drupal.Ajax~element_settings} element_settings * Settings for this Ajax object. */ Drupal.Ajax = function (base, element, element_settings) { var defaults = { event: element ? 'mousedown' : null, keypress: true, selector: base ? '#' + base : null, effect: 'none', speed: 'none', method: 'replaceWith', progress: { type: 'throbber', message: Drupal.t('Please wait...') }, submit: { js: true } }; $.extend(this, defaults, element_settings); /** * @type {Drupal.AjaxCommands} */ this.commands = new Drupal.AjaxCommands(); /** * @type {bool|number} */ this.instanceIndex = false; // @todo Remove this after refactoring the PHP code to: // - Call this 'selector'. // - Include the '#' for ID-based selectors. // - Support non-ID-based selectors. if (this.wrapper) { /** * @type {string} */ this.wrapper = '#' + this.wrapper; } /** * @type {HTMLElement} */ this.element = element; /** * @type {Drupal.Ajax~element_settings} */ this.element_settings = element_settings; // If there isn't a form, jQuery.ajax() will be used instead, allowing us to // bind Ajax to links as well. if (this.element && this.element.form) { /** * @type {jQuery} */ this.$form = $(this.element.form); } // If no Ajax callback URL was given, use the link href or form action. if (!this.url) { var $element = $(this.element); if ($element.is('a')) { this.url = $element.attr('href'); } else if (this.element && element.form) { this.url = this.$form.attr('action'); } } // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let // the server detect when it needs to degrade gracefully. // There are four scenarios to check for: // 1. /nojs/ // 2. /nojs$ - The end of a URL string. // 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar). // 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment). var originalUrl = this.url; /** * Processed Ajax URL. * * @type {string} */ this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1'); // If the 'nojs' version of the URL is trusted, also trust the 'ajax' // version. if (drupalSettings.ajaxTrustedUrl[originalUrl]) { drupalSettings.ajaxTrustedUrl[this.url] = true; } // Set the options for the ajaxSubmit function. // The 'this' variable will not persist inside of the options object. var ajax = this; /** * Options for the jQuery.ajax function. * * @name Drupal.Ajax#options * * @type {object} * * @prop {string} url * Ajax URL to be called. * @prop {object} data * Ajax payload. * @prop {function} beforeSerialize * Implement jQuery beforeSerialize function to call * {@link Drupal.Ajax#beforeSerialize}. * @prop {function} beforeSubmit * Implement jQuery beforeSubmit function to call * {@link Drupal.Ajax#beforeSubmit}. * @prop {function} beforeSend * Implement jQuery beforeSend function to call * {@link Drupal.Ajax#beforeSend}. * @prop {function} success * Implement jQuery success function to call * {@link Drupal.Ajax#success}. * @prop {function} complete * Implement jQuery success function to clean up ajax state and trigger an * error if needed. * @prop {string} dataType='json' * Type of the response expected. * @prop {string} type='POST' * HTTP method to use for the Ajax request. */ ajax.options = { url: ajax.url, data: ajax.submit, beforeSerialize: function (element_settings, options) { return ajax.beforeSerialize(element_settings, options); }, beforeSubmit: function (form_values, element_settings, options) { ajax.ajaxing = true; return ajax.beforeSubmit(form_values, element_settings, options); }, beforeSend: function (xmlhttprequest, options) { ajax.ajaxing = true; return ajax.beforeSend(xmlhttprequest, options); }, success: function (response, status, xmlhttprequest) { // Sanity check for browser support (object expected). // When using iFrame uploads, responses must be returned as a string. if (typeof response === 'string') { response = $.parseJSON(response); } // Prior to invoking the response's commands, verify that they can be // trusted by checking for a response header. See // \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details. // - Empty responses are harmless so can bypass verification. This // avoids an alert message for server-generated no-op responses that // skip Ajax rendering. // - Ajax objects with trusted URLs (e.g., ones defined server-side via // #ajax) can bypass header verification. This is especially useful // for Ajax with multipart forms. Because IFRAME transport is used, // the response headers cannot be accessed for verification. if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) { if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') { var customMessage = Drupal.t('The response failed verification so will not be processed.'); return ajax.error(xmlhttprequest, ajax.url, customMessage); } } return ajax.success(response, status); }, complete: function (xmlhttprequest, status) { ajax.ajaxing = false; if (status === 'error' || status === 'parsererror') { return ajax.error(xmlhttprequest, ajax.url); } }, dataType: 'json', type: 'POST' }; if (element_settings.dialog) { ajax.options.data.dialogOptions = element_settings.dialog; } // Ensure that we have a valid URL by adding ? when no query parameter is // yet available, otherwise append using &. if (ajax.options.url.indexOf('?') === -1) { ajax.options.url += '?'; } else { ajax.options.url += '&'; } ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=drupal_' + (element_settings.dialogType || 'ajax'); // Bind the ajaxSubmit function to the element event. $(ajax.element).on(element_settings.event, function (event) { if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) { throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url})); } return ajax.eventResponse(this, event); }); // If necessary, enable keyboard submission so that Ajax behaviors // can be triggered through keyboard input as well as e.g. a mousedown // action. if (element_settings.keypress) { $(ajax.element).on('keypress', function (event) { return ajax.keypressResponse(this, event); }); } // If necessary, prevent the browser default action of an additional event. // For example, prevent the browser default action of a click, even if the // Ajax behavior binds to mousedown. if (element_settings.prevent) { $(ajax.element).on(element_settings.prevent, false); } }; /** * URL query attribute to indicate the wrapper used to render a request. * * The wrapper format determines how the HTML is wrapped, for example in a * modal dialog. * * @const {string} * * @default */ Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format'; /** * Request parameter to indicate that a request is a Drupal Ajax request. * * @const {string} * * @default */ Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax'; /** * Execute the ajax request. * * Allows developers to execute an Ajax request manually without specifying * an event to respond to. * * @return {object} * Returns the jQuery.Deferred object underlying the Ajax request. If * pre-serialization fails, the Deferred will be returned in the rejected * state. */ Drupal.Ajax.prototype.execute = function () { // Do not perform another ajax command if one is already in progress. if (this.ajaxing) { return; } try { this.beforeSerialize(this.element, this.options); // Return the jqXHR so that external code can hook into the Deferred API. return $.ajax(this.options); } catch (e) { // Unset the ajax.ajaxing flag here because it won't be unset during // the complete response. this.ajaxing = false; window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message); // For consistency, return a rejected Deferred (i.e., jqXHR's superclass) // so that calling code can take appropriate action. return $.Deferred().reject(); } }; /** * Handle a key press. * * The Ajax object will, if instructed, bind to a key press response. This * will test to see if the key press is valid to trigger this event and * if it is, trigger it for us and prevent other keypresses from triggering. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13 * and 32. RETURN is often used to submit a form when in a textfield, and * SPACE is often used to activate an element without submitting. * * @param {HTMLElement} element * Element the event was triggered on. * @param {jQuery.Event} event * Triggered event. */ Drupal.Ajax.prototype.keypressResponse = function (element, event) { // Create a synonym for this to reduce code confusion. var ajax = this; // Detect enter key and space bar and allow the standard response for them, // except for form elements of type 'text', 'tel', 'number' and 'textarea', // where the spacebar activation causes inappropriate activation if // #ajax['keypress'] is TRUE. On a text-type widget a space should always // be a space. if (event.which === 13 || (event.which === 32 && element.type !== 'text' && element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number')) { event.preventDefault(); event.stopPropagation(); $(ajax.element_settings.element).trigger(ajax.element_settings.event); } }; /** * Handle an event that triggers an Ajax response. * * When an event that triggers an Ajax response happens, this method will * perform the actual Ajax call. It is bound to the event using * bind() in the constructor, and it uses the options specified on the * Ajax object. * * @param {HTMLElement} element * Element the event was triggered on. * @param {jQuery.Event} event * Triggered event. */ Drupal.Ajax.prototype.eventResponse = function (element, event) { event.preventDefault(); event.stopPropagation(); // Create a synonym for this to reduce code confusion. var ajax = this; // Do not perform another Ajax command if one is already in progress. if (ajax.ajaxing) { return; } try { if (ajax.$form) { // If setClick is set, we must set this to ensure that the button's // value is passed. if (ajax.setClick) { // Mark the clicked button. 'form.clk' is a special variable for // ajaxSubmit that tells the system which element got clicked to // trigger the submit. Without it there would be no 'op' or // equivalent. element.form.clk = element; } ajax.$form.ajaxSubmit(ajax.options); } else { ajax.beforeSerialize(ajax.element, ajax.options); $.ajax(ajax.options); } } catch (e) { // Unset the ajax.ajaxing flag here because it won't be unset during // the complete response. ajax.ajaxing = false; window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message); } }; /** * Handler for the form serialization. * * Runs before the beforeSend() handler (see below), and unlike that one, runs * before field data is collected. * * @param {object} [element] * Ajax object's `element_settings`. * @param {object} options * jQuery.ajax options. */ Drupal.Ajax.prototype.beforeSerialize = function (element, options) { // Allow detaching behaviors to update field values before collecting them. // This is only needed when field values are added to the POST data, so only // when there is a form such that this.$form.ajaxSubmit() is used instead of // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize() // isn't called, but don't rely on that: explicitly check this.$form. if (this.$form) { var settings = this.settings || drupalSettings; Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize'); } // Inform Drupal that this is an AJAX request. options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1; // Allow Drupal to return new JavaScript and CSS files to load without // returning the ones already loaded. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator // @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset() // @see system_js_settings_alter() var pageState = drupalSettings.ajaxPageState; options.data['ajax_page_state[theme]'] = pageState.theme; options.data['ajax_page_state[theme_token]'] = pageState.theme_token; options.data['ajax_page_state[libraries]'] = pageState.libraries; }; /** * Modify form values prior to form submission. * * @param {Array.<object>} form_values * Processed form values. * @param {jQuery} element * The form node as a jQuery object. * @param {object} options * jQuery.ajax options. */ Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) { // This function is left empty to make it simple to override for modules // that wish to add functionality here. }; /** * Prepare the Ajax request before it is sent. * * @param {XMLHttpRequest} xmlhttprequest * Native Ajax object. * @param {object} options * jQuery.ajax options. */ Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) { // For forms without file inputs, the jQuery Form plugin serializes the // form values, and then calls jQuery's $.ajax() function, which invokes // this handler. In this circumstance, options.extraData is never used. For // forms with file inputs, the jQuery Form plugin uses the browser's normal // form submission mechanism, but captures the response in a hidden IFRAME. // In this circumstance, it calls this handler first, and then appends // hidden fields to the form to submit the values in options.extraData. // There is no simple way to know which submission mechanism will be used, // so we add to extraData regardless, and allow it to be ignored in the // former case. if (this.$form) { options.extraData = options.extraData || {}; // Let the server know when the IFRAME submission mechanism is used. The // server can use this information to wrap the JSON response in a // TEXTAREA, as per http://jquery.malsup.com/form/#file-upload. options.extraData.ajax_iframe_upload = '1'; // The triggering element is about to be disabled (see below), but if it // contains a value (e.g., a checkbox, textfield, select, etc.), ensure // that value is included in the submission. As per above, submissions // that use $.ajax() are already serialized prior to the element being // disabled, so this is only needed for IFRAME submissions. var v = $.fieldValue(this.element); if (v !== null) { options.extraData[this.element.name] = v; } } // Disable the element that received the change to prevent user interface // interaction while the Ajax request is in progress. ajax.ajaxing prevents // the element from triggering a new request, but does not prevent the user // from changing its value. $(this.element).prop('disabled', true); if (!this.progress || !this.progress.type) { return; } // Insert progress indicator. var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase(); if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') { this[progressIndicatorMethod].call(this); } }; /** * Sets the progress bar progress indicator. */ Drupal.Ajax.prototype.setProgressIndicatorBar = function () { var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop); if (this.progress.message) { progressBar.setProgress(-1, this.progress.message); } if (this.progress.url) { progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500); } this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar'); this.progress.object = progressBar; $(this.element).after(this.progress.element); }; /** * Sets the throbber progress indicator. */ Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () { this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>'); if (this.progress.message) { this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>'); } $(this.element).after(this.progress.element); }; /** * Sets the fullscreen progress indicator. */ Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () { this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen">&nbsp;</div>'); $('body').after(this.progress.element); }; /** * Handler for the form redirection completion. * * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response * Drupal Ajax response. * @param {number} status * XMLHttpRequest status. */ Drupal.Ajax.prototype.success = function (response, status) { // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } $(this.element).prop('disabled', false); // Save element's ancestors tree so if the element is removed from the dom // we can try to refocus one of its parents. Using addBack reverse the // result array, meaning that index 0 is the highest parent in the hierarchy // in this situation it is usually a <form> element. var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray(); // Track if any command is altering the focus so we can avoid changing the // focus set by the Ajax command. var focusChanged = false; for (var i in response) { if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) { this.commands[response[i].command](this, response[i], status); if (response[i].command === 'invoke' && response[i].method === 'focus') { focusChanged = true; } } } // If the focus hasn't be changed by the ajax commands, try to refocus the // triggering element or one of its parents if that element does not exist // anymore. if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) { var target = false; for (var n = elementParents.length - 1; !target && n > 0; n--) { target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]'); } if (target) { $(target).trigger('focus'); } } // Reattach behaviors, if they were detached in beforeSerialize(). The // attachBehaviors() called on the new content from processing the response // commands is not sufficient, because behaviors from the entire form need // to be reattached. if (this.$form) { var settings = this.settings || drupalSettings; Drupal.attachBehaviors(this.$form.get(0), settings); } // Remove any response-specific settings so they don't get used on the next // call by mistake. this.settings = null; }; /** * Build an effect object to apply an effect when adding new HTML. * * @param {object} response * Drupal Ajax response. * @param {string} [response.effect] * Override the default value of {@link Drupal.Ajax#element_settings}. * @param {string|number} [response.speed] * Override the default value of {@link Drupal.Ajax#element_settings}. * * @return {object} * Returns an object with `showEffect`, `hideEffect` and `showSpeed` * properties. */ Drupal.Ajax.prototype.getEffect = function (response) { var type = response.effect || this.effect; var speed = response.speed || this.speed; var effect = {}; if (type === 'none') { effect.showEffect = 'show'; effect.hideEffect = 'hide'; effect.showSpeed = ''; } else if (type === 'fade') { effect.showEffect = 'fadeIn'; effect.hideEffect = 'fadeOut'; effect.showSpeed = speed; } else { effect.showEffect = type + 'Toggle'; effect.hideEffect = type + 'Toggle'; effect.showSpeed = speed; } return effect; }; /** * Handler for the form redirection error. * * @param {object} xmlhttprequest * Native XMLHttpRequest object. * @param {string} uri * Ajax Request URI. * @param {string} [customMessage] * Extra message to print with the Ajax error. */ Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) { // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } // Undo hide. $(this.wrapper).show(); // Re-enable the element. $(this.element).prop('disabled', false); // Reattach behaviors, if they were detached in beforeSerialize(). if (this.$form) { var settings = this.settings || drupalSettings; Drupal.attachBehaviors(this.$form.get(0), settings); } throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage); }; /** * @typedef {object} Drupal.AjaxCommands~commandDefinition * * @prop {string} command * @prop {string} [method] * @prop {string} [selector] * @prop {string} [data] * @prop {object} [settings] * @prop {bool} [asterisk] * @prop {string} [text] * @prop {string} [title] * @prop {string} [url] * @prop {object} [argument] * @prop {string} [name] * @prop {string} [value] * @prop {string} [old] * @prop {string} [new] * @prop {bool} [merge] * @prop {Array} [args] * * @see Drupal.AjaxCommands */ /** * Provide a series of commands that the client will perform. * * @constructor */ Drupal.AjaxCommands = function () {}; Drupal.AjaxCommands.prototype = { /** * Command to insert new content into the DOM. * * @param {Drupal.Ajax} ajax * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.data * The data to use with the jQuery method. * @param {string} [response.method] * The jQuery DOM manipulation method to be used. * @param {string} [response.selector] * A optional jQuery selector string. * @param {object} [response.settings] * An optional array of settings that will be used. * @param {number} [status] * The XMLHttpRequest status. */ insert: function (ajax, response, status) { // Get information from the response. If it is not there, default to // our presets. var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper); var method = response.method || ajax.method; var effect = ajax.getEffect(response); var settings; // We don't know what response.data contains: it might be a string of text // without HTML, so don't rely on jQuery correctly interpreting // $(response.data) as new HTML rather than a CSS selector. Also, if // response.data contains top-level text nodes, they get lost with either // $(response.data) or $('<div></div>').replaceWith(response.data). var $new_content_wrapped = $('<div></div>').html(response.data); var $new_content = $new_content_wrapped.contents(); // For legacy reasons, the effects processing code assumes that // $new_content consists of a single top-level element. Also, it has not // been sufficiently tested whether attachBehaviors() can be successfully // called with a context object that includes top-level text nodes. // However, to give developers full control of the HTML appearing in the // page, and to enable Ajax content to be inserted in places where <div> // elements are not allowed (e.g., within <table>, <tr>, and <span> // parents), we check if the new content satisfies the requirement // of a single top-level element, and only use the container <div> created // above when it doesn't. For more information, please see // https://www.drupal.org/node/736066. if ($new_content.length !== 1 || $new_content.get(0).nodeType !== 1) { $new_content = $new_content_wrapped; } // If removing content from the wrapper, detach behaviors first. switch (method) { case 'html': case 'replaceWith': case 'replaceAll': case 'empty': case 'remove': settings = response.settings || ajax.settings || drupalSettings; Drupal.detachBehaviors($wrapper.get(0), settings); } // Add the new content to the page. $wrapper[method]($new_content); // Immediately hide the new content if we're using any effects. if (effect.showEffect !== 'show') { $new_content.hide(); } // Determine which effect to use and what content will receive the // effect, then show the new content. if ($new_content.find('.ajax-new-content').length > 0) { $new_content.find('.ajax-new-content').hide(); $new_content.show(); $new_content.find('.ajax-new-content')[effect.showEffect](effect.showSpeed); } else if (effect.showEffect !== 'show') { $new_content[effect.showEffect](effect.showSpeed); } // Attach all JavaScript behaviors to the new content, if it was // successfully added to the page, this if statement allows // `#ajax['wrapper']` to be optional. if ($new_content.parents('html').length > 0) { // Apply any settings from the returned JSON if available. settings = response.settings || ajax.settings || drupalSettings; Drupal.attachBehaviors($new_content.get(0), settings); } }, /** * Command to remove a chunk from the page. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {object} [response.settings] * An optional array of settings that will be used. * @param {number} [status] * The XMLHttpRequest status. */ remove: function (ajax, response, status) { var settings = response.settings || ajax.settings || drupalSettings; $(response.selector).each(function () { Drupal.detachBehaviors(this, settings); }) .remove(); }, /** * Command to mark a chunk changed. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The JSON response object from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {bool} [response.asterisk] * An optional CSS selector. If specified, an asterisk will be * appended to the HTML inside the provided selector. * @param {number} [status] * The request status. */ changed: function (ajax, response, status) { var $element = $(response.selector); if (!$element.hasClass('ajax-changed')) { $element.addClass('ajax-changed'); if (response.asterisk) { $element.find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> '); } } }, /** * Command to provide an alert. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The JSON response from the Ajax request. * @param {string} response.text * The text that will be displayed in an alert dialog. * @param {number} [status] * The XMLHttpRequest status. */ alert: function (ajax, response, status) { window.alert(response.text, response.title); }, /** * Command to set the window.location, redirecting the browser. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.url * The URL to redirect to. * @param {number} [status] * The XMLHttpRequest status. */ redirect: function (ajax, response, status) { window.location = response.url; }, /** * Command to provide the jQuery css() function. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {object} response.argument * An array of key/value pairs to set in the CSS for the selector. * @param {number} [status] * The XMLHttpRequest status. */ css: function (ajax, response, status) { $(response.selector).css(response.argument); }, /** * Command to set the settings used for other commands in this response. * * This method will also remove expired `drupalSettings.ajax` settings. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {bool} response.merge * Determines whether the additional settings should be merged to the * global settings. * @param {object} response.settings * Contains additional settings to add to the global settings. * @param {number} [status] * The XMLHttpRequest status. */ settings: function (ajax, response, status) { var ajaxSettings = drupalSettings.ajax; // Clean up drupalSettings.ajax. Drupal.ajax.expired().forEach(function (instance) { // If the Ajax object has been created through drupalSettings.ajax // it will have a selector. When there is no selector the object // has been initialized with a special class name picked up by the // Ajax behavior. if (instance.selector) { var selector = instance.selector.replace('#', ''); if (ajaxSettings && selector in ajaxSettings) { delete ajaxSettings[selector]; } } }); if (response.merge) { $.extend(true, drupalSettings, response.settings); } else { ajax.settings = response.settings; } }, /** * Command to attach data using jQuery's data API. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.name * The name or key (in the key value pair) of the data attached to this * selector. * @param {string} response.selector * A jQuery selector string. * @param {string|object} response.value * The value of to be attached. * @param {number} [status] * The XMLHttpRequest status. */ data: function (ajax, response, status) { $(response.selector).data(response.name, response.value); }, /** * Command to apply a jQuery method. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {Array} response.args * An array of arguments to the jQuery method, if any. * @param {string} response.method * The jQuery method to invoke. * @param {string} response.selector * A jQuery selector string. * @param {number} [status] * The XMLHttpRequest status. */ invoke: function (ajax, response, status) { var $element = $(response.selector); $element[response.method].apply($element, response.args); }, /** * Command to restripe a table. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {number} [status] * The XMLHttpRequest status. */ restripe: function (ajax, response, status) { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $(response.selector).find('> tbody > tr:visible, > tr:visible') .removeClass('odd even') .filter(':even').addClass('odd').end() .filter(':odd').addClass('even'); }, /** * Command to update a form's build ID. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.old * The old form build ID. * @param {string} response.new * The new form build ID. * @param {number} [status] * The XMLHttpRequest status. */ update_build_id: function (ajax, response, status) { $('input[name="form_build_id"][value="' + response.old + '"]').val(response.new); }, /** * Command to add css. * * Uses the proprietary addImport method if available as browsers which * support that method ignore @import statements in dynamically added * stylesheets. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.data * A string that contains the styles to be added. * @param {number} [status] * The XMLHttpRequest status. */ add_css: function (ajax, response, status) { // Add the styles in the normal way. $('head').prepend(response.data); // Add imports in the styles using the addImport method if available. var match; var importMatch = /^@import url\("(.*)"\);$/igm; if (document.styleSheets[0].addImport && importMatch.test(response.data)) { importMatch.lastIndex = 0; do { match = importMatch.exec(response.data); document.styleSheets[0].addImport(match[1]); } while (match); } } }; })(jQuery, window, Drupal, drupalSettings); ; window.matchMedia||(window.matchMedia=function(){"use strict";var e=window.styleMedia||window.media;if(!e){var t=document.createElement("style"),i=document.getElementsByTagName("script")[0],n=null;t.type="text/css";t.id="matchmediajs-test";i.parentNode.insertBefore(t,i);n="getComputedStyle"in window&&window.getComputedStyle(t,null)||t.currentStyle;e={matchMedium:function(e){var i="@media "+e+"{ #matchmediajs-test { width: 1px; } }";if(t.styleSheet){t.styleSheet.cssText=i}else{t.textContent=i}return n.width==="1px"}}}return function(t){return{matches:e.matchMedium(t||"all"),media:t||"all"}}}()); ; /** * @file * Responsive navigation tabs. * * This also supports collapsible navigable is the 'is-collapsible' class is * added to the main element, and a target element is included. */ (function ($, Drupal) { 'use strict'; function init(i, tab) { var $tab = $(tab); var $target = $tab.find('[data-drupal-nav-tabs-target]'); var isCollapsible = $tab.hasClass('is-collapsible'); function openMenu(e) { $target.toggleClass('is-open'); } function handleResize(e) { $tab.addClass('is-horizontal'); var $tabs = $tab.find('.tabs'); var isHorizontal = $tabs.outerHeight() <= $tabs.find('.tabs__tab').outerHeight(); $tab.toggleClass('is-horizontal', isHorizontal); if (isCollapsible) { $tab.toggleClass('is-collapse-enabled', !isHorizontal); } if (isHorizontal) { $target.removeClass('is-open'); } } $tab.addClass('position-container is-horizontal-enabled'); $tab.on('click.tabs', '[data-drupal-nav-tabs-trigger]', openMenu); $(window).on('resize.tabs', Drupal.debounce(handleResize, 150)).trigger('resize.tabs'); } /** * Initialise the tabs JS. */ Drupal.behaviors.navTabs = { attach: function (context, settings) { var $tabs = $(context).find('[data-drupal-nav-tabs]'); if ($tabs.length) { var notSmartPhone = window.matchMedia('(min-width: 300px)'); if (notSmartPhone.matches) { $tabs.once('nav-tabs').each(init); } } } }; })(jQuery, Drupal); ; /** * @file * Adds an HTML element and method to trigger audio UAs to read system messages. * * Use {@link Drupal.announce} to indicate to screen reader users that an * element on the page has changed state. For instance, if clicking a link * loads 10 more items into a list, one might announce the change like this. * * @example * $('#search-list') * .on('itemInsert', function (event, data) { * // Insert the new items. * $(data.container.el).append(data.items.el); * // Announce the change to the page contents. * Drupal.announce(Drupal.t('@count items added to @container', * {'@count': data.items.length, '@container': data.container.title} * )); * }); */ (function (Drupal, debounce) { 'use strict'; var liveElement; var announcements = []; /** * Builds a div element with the aria-live attribute and add it to the DOM. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the behavior for drupalAnnouce. */ Drupal.behaviors.drupalAnnounce = { attach: function (context) { // Create only one aria-live element. if (!liveElement) { liveElement = document.createElement('div'); liveElement.id = 'drupal-live-announce'; liveElement.className = 'visually-hidden'; liveElement.setAttribute('aria-live', 'polite'); liveElement.setAttribute('aria-busy', 'false'); document.body.appendChild(liveElement); } } }; /** * Concatenates announcements to a single string; appends to the live region. */ function announce() { var text = []; var priority = 'polite'; var announcement; // Create an array of announcement strings to be joined and appended to the // aria live region. var il = announcements.length; for (var i = 0; i < il; i++) { announcement = announcements.pop(); text.unshift(announcement.text); // If any of the announcements has a priority of assertive then the group // of joined announcements will have this priority. if (announcement.priority === 'assertive') { priority = 'assertive'; } } if (text.length) { // Clear the liveElement so that repeated strings will be read. liveElement.innerHTML = ''; // Set the busy state to true until the node changes are complete. liveElement.setAttribute('aria-busy', 'true'); // Set the priority to assertive, or default to polite. liveElement.setAttribute('aria-live', priority); // Print the text to the live region. Text should be run through // Drupal.t() before being passed to Drupal.announce(). liveElement.innerHTML = text.join('\n'); // The live text area is updated. Allow the AT to announce the text. liveElement.setAttribute('aria-busy', 'false'); } } /** * Triggers audio UAs to read the supplied text. * * The aria-live region will only read the text that currently populates its * text node. Replacing text quickly in rapid calls to announce results in * only the text from the most recent call to {@link Drupal.announce} being * read. By wrapping the call to announce in a debounce function, we allow for * time for multiple calls to {@link Drupal.announce} to queue up their * messages. These messages are then joined and append to the aria-live region * as one text node. * * @param {string} text * A string to be read by the UA. * @param {string} [priority='polite'] * A string to indicate the priority of the message. Can be either * 'polite' or 'assertive'. * * @return {function} * The return of the call to debounce. * * @see http://www.w3.org/WAI/PF/aria-practices/#liveprops */ Drupal.announce = function (text, priority) { // Save the text and priority into a closure variable. Multiple simultaneous // announcements will be concatenated and read in sequence. announcements.push({ text: text, priority: priority }); // Immediately invoke the function that debounce returns. 200 ms is right at // the cusp where humans notice a pause, so we will wait // at most this much time before the set of queued announcements is read. return (debounce(announce, 200)()); }; }(Drupal, Drupal.debounce)); ; (function(){if(window.matchMedia&&window.matchMedia("all").addListener){return false}var e=window.matchMedia,i=e("only all").matches,n=false,t=0,a=[],r=function(i){clearTimeout(t);t=setTimeout(function(){for(var i=0,n=a.length;i<n;i++){var t=a[i].mql,r=a[i].listeners||[],o=e(t.media).matches;if(o!==t.matches){t.matches=o;for(var s=0,l=r.length;s<l;s++){r[s].call(window,t)}}}},30)};window.matchMedia=function(t){var o=e(t),s=[],l=0;o.addListener=function(e){if(!i){return}if(!n){n=true;window.addEventListener("resize",r,true)}if(l===0){l=a.push({mql:o,listeners:s})}s.push(e)};o.removeListener=function(e){for(var i=0,n=s.length;i<n;i++){if(s[i]===e){s.splice(i,1)}}};return o}})(); ; /** * @file * Manages elements that can offset the size of the viewport. * * Measures and reports viewport offset dimensions from elements like the * toolbar that can potentially displace the positioning of other elements. */ /** * @typedef {object} Drupal~displaceOffset * * @prop {number} top * @prop {number} left * @prop {number} right * @prop {number} bottom */ /** * Triggers when layout of the page changes. * * This is used to position fixed element on the page during page resize and * Toolbar toggling. * * @event drupalViewportOffsetChange */ (function ($, Drupal, debounce) { 'use strict'; /** * @name Drupal.displace.offsets * * @type {Drupal~displaceOffset} */ var offsets = { top: 0, right: 0, bottom: 0, left: 0 }; /** * Registers a resize handler on the window. * * @type {Drupal~behavior} */ Drupal.behaviors.drupalDisplace = { attach: function () { // Mark this behavior as processed on the first pass. if (this.displaceProcessed) { return; } this.displaceProcessed = true; $(window).on('resize.drupalDisplace', debounce(displace, 200)); } }; /** * Informs listeners of the current offset dimensions. * * @function Drupal.displace * * @prop {Drupal~displaceOffset} offsets * * @param {bool} [broadcast] * When true or undefined, causes the recalculated offsets values to be * broadcast to listeners. * * @return {Drupal~displaceOffset} * An object whose keys are the for sides an element -- top, right, bottom * and left. The value of each key is the viewport displacement distance for * that edge. * * @fires event:drupalViewportOffsetChange */ function displace(broadcast) { offsets = Drupal.displace.offsets = calculateOffsets(); if (typeof broadcast === 'undefined' || broadcast) { $(document).trigger('drupalViewportOffsetChange', offsets); } return offsets; } /** * Determines the viewport offsets. * * @return {Drupal~displaceOffset} * An object whose keys are the for sides an element -- top, right, bottom * and left. The value of each key is the viewport displacement distance for * that edge. */ function calculateOffsets() { return { top: calculateOffset('top'), right: calculateOffset('right'), bottom: calculateOffset('bottom'), left: calculateOffset('left') }; } /** * Gets a specific edge's offset. * * Any element with the attribute data-offset-{edge} e.g. data-offset-top will * be considered in the viewport offset calculations. If the attribute has a * numeric value, that value will be used. If no value is provided, one will * be calculated using the element's dimensions and placement. * * @function Drupal.displace.calculateOffset * * @param {string} edge * The name of the edge to calculate. Can be 'top', 'right', * 'bottom' or 'left'. * * @return {number} * The viewport displacement distance for the requested edge. */ function calculateOffset(edge) { var edgeOffset = 0; var displacingElements = document.querySelectorAll('[data-offset-' + edge + ']'); var n = displacingElements.length; for (var i = 0; i < n; i++) { var el = displacingElements[i]; // If the element is not visible, do consider its dimensions. if (el.style.display === 'none') { continue; } // If the offset data attribute contains a displacing value, use it. var displacement = parseInt(el.getAttribute('data-offset-' + edge), 10); // If the element's offset data attribute exits // but is not a valid number then get the displacement // dimensions directly from the element. if (isNaN(displacement)) { displacement = getRawOffset(el, edge); } // If the displacement value is larger than the current value for this // edge, use the displacement value. edgeOffset = Math.max(edgeOffset, displacement); } return edgeOffset; } /** * Calculates displacement for element based on its dimensions and placement. * * @param {HTMLElement} el * The jQuery element whose dimensions and placement will be measured. * * @param {string} edge * The name of the edge of the viewport that the element is associated * with. * * @return {number} * The viewport displacement distance for the requested edge. */ function getRawOffset(el, edge) { var $el = $(el); var documentElement = document.documentElement; var displacement = 0; var horizontal = (edge === 'left' || edge === 'right'); // Get the offset of the element itself. var placement = $el.offset()[horizontal ? 'left' : 'top']; // Subtract scroll distance from placement to get the distance // to the edge of the viewport. placement -= window['scroll' + (horizontal ? 'X' : 'Y')] || document.documentElement['scroll' + (horizontal) ? 'Left' : 'Top'] || 0; // Find the displacement value according to the edge. switch (edge) { // Left and top elements displace as a sum of their own offset value // plus their size. case 'top': // Total displacement is the sum of the elements placement and size. displacement = placement + $el.outerHeight(); break; case 'left': // Total displacement is the sum of the elements placement and size. displacement = placement + $el.outerWidth(); break; // Right and bottom elements displace according to their left and // top offset. Their size isn't important. case 'bottom': displacement = documentElement.clientHeight - placement; break; case 'right': displacement = documentElement.clientWidth - placement; break; default: displacement = 0; } return displacement; } /** * Assign the displace function to a property of the Drupal global object. * * @ignore */ Drupal.displace = displace; $.extend(Drupal.displace, { /** * Expose offsets to other scripts to avoid having to recalculate offsets. * * @ignore */ offsets: offsets, /** * Expose method to compute a single edge offsets. * * @ignore */ calculateOffset: calculateOffset }); })(jQuery, Drupal, Drupal.debounce); ; /** * @file * Builds a nested accordion widget. * * Invoke on an HTML list element with the jQuery plugin pattern. * * @example * $('.toolbar-menu').drupalToolbarMenu(); */ (function ($, Drupal, drupalSettings) { 'use strict'; /** * Store the open menu tray. */ var activeItem = Drupal.url(drupalSettings.path.currentPath); $.fn.drupalToolbarMenu = function () { var ui = { handleOpen: Drupal.t('Extend'), handleClose: Drupal.t('Collapse') }; /** * Handle clicks from the disclosure button on an item with sub-items. * * @param {Object} event * A jQuery Event object. */ function toggleClickHandler(event) { var $toggle = $(event.target); var $item = $toggle.closest('li'); // Toggle the list item. toggleList($item); // Close open sibling menus. var $openItems = $item.siblings().filter('.open'); toggleList($openItems, false); } /** * Handle clicks from a menu item link. * * @param {Object} event * A jQuery Event object. */ function linkClickHandler(event) { // If the toolbar is positioned fixed (and therefore hiding content // underneath), then users expect clicks in the administration menu tray // to take them to that destination but for the menu tray to be closed // after clicking: otherwise the toolbar itself is obstructing the view // of the destination they chose. if (!Drupal.toolbar.models.toolbarModel.get('isFixed')) { Drupal.toolbar.models.toolbarModel.set('activeTab', null); } // Stopping propagation to make sure that once a toolbar-box is clicked // (the whitespace part), the page is not redirected anymore. event.stopPropagation(); } /** * Toggle the open/close state of a list is a menu. * * @param {jQuery} $item * The li item to be toggled. * * @param {Boolean} switcher * A flag that forces toggleClass to add or a remove a class, rather than * simply toggling its presence. */ function toggleList($item, switcher) { var $toggle = $item.children('.toolbar-box').children('.toolbar-handle'); switcher = (typeof switcher !== 'undefined') ? switcher : !$item.hasClass('open'); // Toggle the item open state. $item.toggleClass('open', switcher); // Twist the toggle. $toggle.toggleClass('open', switcher); // Adjust the toggle text. $toggle .find('.action') // Expand Structure, Collapse Structure. .text((switcher) ? ui.handleClose : ui.handleOpen); } /** * Add markup to the menu elements. * * Items with sub-elements have a list toggle attached to them. Menu item * links and the corresponding list toggle are wrapped with in a div * classed with .toolbar-box. The .toolbar-box div provides a positioning * context for the item list toggle. * * @param {jQuery} $menu * The root of the menu to be initialized. */ function initItems($menu) { var options = { class: 'toolbar-icon toolbar-handle', action: ui.handleOpen, text: '' }; // Initialize items and their links. $menu.find('li > a').wrap('<div class="toolbar-box">'); // Add a handle to each list item if it has a menu. $menu.find('li').each(function (index, element) { var $item = $(element); if ($item.children('ul.toolbar-menu').length) { var $box = $item.children('.toolbar-box'); options.text = Drupal.t('@label', {'@label': $box.find('a').text()}); $item.children('.toolbar-box') .append(Drupal.theme('toolbarMenuItemToggle', options)); } }); } /** * Adds a level class to each list based on its depth in the menu. * * This function is called recursively on each sub level of lists elements * until the depth of the menu is exhausted. * * @param {jQuery} $lists * A jQuery object of ul elements. * * @param {number} level * The current level number to be assigned to the list elements. */ function markListLevels($lists, level) { level = (!level) ? 1 : level; var $lis = $lists.children('li').addClass('level-' + level); $lists = $lis.children('ul'); if ($lists.length) { markListLevels($lists, level + 1); } } /** * On page load, open the active menu item. * * Marks the trail of the active link in the menu back to the root of the * menu with .menu-item--active-trail. * * @param {jQuery} $menu * The root of the menu. */ function openActiveItem($menu) { var pathItem = $menu.find('a[href="' + location.pathname + '"]'); if (pathItem.length && !activeItem) { activeItem = location.pathname; } if (activeItem) { var $activeItem = $menu.find('a[href="' + activeItem + '"]').addClass('menu-item--active'); var $activeTrail = $activeItem.parentsUntil('.root', 'li').addClass('menu-item--active-trail'); toggleList($activeTrail, true); } } // Return the jQuery object. return this.each(function (selector) { var $menu = $(this).once('toolbar-menu'); if ($menu.length) { // Bind event handlers. $menu .on('click.toolbar', '.toolbar-box', toggleClickHandler) .on('click.toolbar', '.toolbar-box a', linkClickHandler); $menu.addClass('root'); initItems($menu); markListLevels($menu); // Restore previous and active states. openActiveItem($menu); } }); }; /** * A toggle is an interactive element often bound to a click handler. * * @param {object} options * Options for the button. * @param {string} options.class * Class to set on the button. * @param {string} options.action * Action for the button. * @param {string} options.text * Used as label for the button. * * @return {string} * A string representing a DOM fragment. */ Drupal.theme.toolbarMenuItemToggle = function (options) { return '<button class="' + options['class'] + '"><span class="action">' + options.action + '</span><span class="label">' + options.text + '</span></button>'; }; }(jQuery, Drupal, drupalSettings)); ; /** * @file * Defines the behavior of the Drupal administration toolbar. */ (function ($, Drupal, drupalSettings) { 'use strict'; // Merge run-time settings with the defaults. var options = $.extend( { breakpoints: { 'toolbar.narrow': '', 'toolbar.standard': '', 'toolbar.wide': '' } }, drupalSettings.toolbar, // Merge strings on top of drupalSettings so that they are not mutable. { strings: { horizontal: Drupal.t('Horizontal orientation'), vertical: Drupal.t('Vertical orientation') } } ); /** * Registers tabs with the toolbar. * * The Drupal toolbar allows modules to register top-level tabs. These may * point directly to a resource or toggle the visibility of a tray. * * Modules register tabs with hook_toolbar(). * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the toolbar rendering functionality to the toolbar element. */ Drupal.behaviors.toolbar = { attach: function (context) { // Verify that the user agent understands media queries. Complex admin // toolbar layouts require media query support. if (!window.matchMedia('only screen').matches) { return; } // Process the administrative toolbar. $(context).find('#toolbar-administration').once('toolbar').each(function () { // Establish the toolbar models and views. var model = Drupal.toolbar.models.toolbarModel = new Drupal.toolbar.ToolbarModel({ locked: JSON.parse(localStorage.getItem('Drupal.toolbar.trayVerticalLocked')) || false, activeTab: document.getElementById(JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID'))) }); Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView({ el: this, model: model, strings: options.strings }); Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView({ el: this, model: model, strings: options.strings }); Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView({ el: this, model: model }); // Render collapsible menus. var menuModel = Drupal.toolbar.models.menuModel = new Drupal.toolbar.MenuModel(); Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView({ el: $(this).find('.toolbar-menu-administration').get(0), model: menuModel, strings: options.strings }); // Handle the resolution of Drupal.toolbar.setSubtrees. // This is handled with a deferred so that the function may be invoked // asynchronously. Drupal.toolbar.setSubtrees.done(function (subtrees) { menuModel.set('subtrees', subtrees); var theme = drupalSettings.ajaxPageState.theme; localStorage.setItem('Drupal.toolbar.subtrees.' + theme, JSON.stringify(subtrees)); // Indicate on the toolbarModel that subtrees are now loaded. model.set('areSubtreesLoaded', true); }); // Attach a listener to the configured media query breakpoints. for (var label in options.breakpoints) { if (options.breakpoints.hasOwnProperty(label)) { var mq = options.breakpoints[label]; var mql = Drupal.toolbar.mql[label] = window.matchMedia(mq); // Curry the model and the label of the media query breakpoint to // the mediaQueryChangeHandler function. mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label)); // Fire the mediaQueryChangeHandler for each configured breakpoint // so that they process once. Drupal.toolbar.mediaQueryChangeHandler.call(null, model, label, mql); } } // Trigger an initial attempt to load menu subitems. This first attempt // is made after the media query handlers have had an opportunity to // process. The toolbar starts in the vertical orientation by default, // unless the viewport is wide enough to accommodate a horizontal // orientation. Thus we give the Toolbar a chance to determine if it // should be set to horizontal orientation before attempting to load // menu subtrees. Drupal.toolbar.views.toolbarVisualView.loadSubtrees(); $(document) // Update the model when the viewport offset changes. .on('drupalViewportOffsetChange.toolbar', function (event, offsets) { model.set('offsets', offsets); }); // Broadcast model changes to other modules. model .on('change:orientation', function (model, orientation) { $(document).trigger('drupalToolbarOrientationChange', orientation); }) .on('change:activeTab', function (model, tab) { $(document).trigger('drupalToolbarTabChange', tab); }) .on('change:activeTray', function (model, tray) { $(document).trigger('drupalToolbarTrayChange', tray); }); // If the toolbar's orientation is horizontal and no active tab is // defined then show the tray of the first toolbar tab by default (but // not the first 'Home' toolbar tab). if (Drupal.toolbar.models.toolbarModel.get('orientation') === 'horizontal' && Drupal.toolbar.models.toolbarModel.get('activeTab') === null) { Drupal.toolbar.models.toolbarModel.set({ activeTab: $('.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a').get(0) }); } }); } }; /** * Toolbar methods of Backbone objects. * * @namespace */ Drupal.toolbar = { /** * A hash of View instances. * * @type {object.<string, Backbone.View>} */ views: {}, /** * A hash of Model instances. * * @type {object.<string, Backbone.Model>} */ models: {}, /** * A hash of MediaQueryList objects tracked by the toolbar. * * @type {object.<string, object>} */ mql: {}, /** * Accepts a list of subtree menu elements. * * A deferred object that is resolved by an inlined JavaScript callback. * * @type {jQuery.Deferred} * * @see toolbar_subtrees_jsonp(). */ setSubtrees: new $.Deferred(), /** * Respond to configured narrow media query changes. * * @param {Drupal.toolbar.ToolbarModel} model * A toolbar model * @param {string} label * Media query label. * @param {object} mql * A MediaQueryList object. */ mediaQueryChangeHandler: function (model, label, mql) { switch (label) { case 'toolbar.narrow': model.set({ isOriented: mql.matches, isTrayToggleVisible: false }); // If the toolbar doesn't have an explicit orientation yet, or if the // narrow media query doesn't match then set the orientation to // vertical. if (!mql.matches || !model.get('orientation')) { model.set({orientation: 'vertical'}, {validate: true}); } break; case 'toolbar.standard': model.set({ isFixed: mql.matches }); break; case 'toolbar.wide': model.set({ orientation: ((mql.matches) ? 'horizontal' : 'vertical') }, {validate: true}); // The tray orientation toggle visibility does not need to be // validated. model.set({ isTrayToggleVisible: mql.matches }); break; default: break; } } }; /** * A toggle is an interactive element often bound to a click handler. * * @return {string} * A string representing a DOM fragment. */ Drupal.theme.toolbarOrientationToggle = function () { return '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' + '<button class="toolbar-icon" type="button"></button>' + '</div></div>'; }; /** * Ajax command to set the toolbar subtrees. * * @param {Drupal.Ajax} ajax * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * JSON response from the Ajax request. * @param {number} [status] * XMLHttpRequest status. */ Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (ajax, response, status) { Drupal.toolbar.setSubtrees.resolve(response.subtrees); }; }(jQuery, Drupal, drupalSettings)); ; /** * @file * A Backbone Model for collapsible menus. */ (function (Backbone, Drupal) { 'use strict'; /** * Backbone Model for collapsible menus. * * @constructor * * @augments Backbone.Model */ Drupal.toolbar.MenuModel = Backbone.Model.extend(/** @lends Drupal.toolbar.MenuModel# */{ /** * @type {object} * * @prop {object} subtrees */ defaults: /** @lends Drupal.toolbar.MenuModel# */{ /** * @type {object} */ subtrees: {} } }); }(Backbone, Drupal)); ; /** * @file * A Backbone Model for the toolbar. */ (function (Backbone, Drupal) { 'use strict'; /** * Backbone model for the toolbar. * * @constructor * * @augments Backbone.Model */ Drupal.toolbar.ToolbarModel = Backbone.Model.extend(/** @lends Drupal.toolbar.ToolbarModel# */{ /** * @type {object} * * @prop activeTab * @prop activeTray * @prop isOriented * @prop isFixed * @prop areSubtreesLoaded * @prop isViewportOverflowConstrained * @prop orientation * @prop locked * @prop isTrayToggleVisible * @prop height * @prop offsets */ defaults: /** @lends Drupal.toolbar.ToolbarModel# */{ /** * The active toolbar tab. All other tabs should be inactive under * normal circumstances. It will remain active across page loads. The * active item is stored as an ID selector e.g. '#toolbar-item--1'. * * @type {string} */ activeTab: null, /** * Represents whether a tray is open or not. Stored as an ID selector e.g. * '#toolbar-item--1-tray'. * * @type {string} */ activeTray: null, /** * Indicates whether the toolbar is displayed in an oriented fashion, * either horizontal or vertical. * * @type {bool} */ isOriented: false, /** * Indicates whether the toolbar is positioned absolute (false) or fixed * (true). * * @type {bool} */ isFixed: false, /** * Menu subtrees are loaded through an AJAX request only when the Toolbar * is set to a vertical orientation. * * @type {bool} */ areSubtreesLoaded: false, /** * If the viewport overflow becomes constrained, isFixed must be true so * that elements in the trays aren't lost off-screen and impossible to * get to. * * @type {bool} */ isViewportOverflowConstrained: false, /** * The orientation of the active tray. * * @type {string} */ orientation: 'vertical', /** * A tray is locked if a user toggled it to vertical. Otherwise a tray * will switch between vertical and horizontal orientation based on the * configured breakpoints. The locked state will be maintained across page * loads. * * @type {bool} */ locked: false, /** * Indicates whether the tray orientation toggle is visible. * * @type {bool} */ isTrayToggleVisible: false, /** * The height of the toolbar. * * @type {number} */ height: null, /** * The current viewport offsets determined by {@link Drupal.displace}. The * offsets suggest how a module might position is components relative to * the viewport. * * @type {object} * * @prop {number} top * @prop {number} right * @prop {number} bottom * @prop {number} left */ offsets: { top: 0, right: 0, bottom: 0, left: 0 } }, /** * @inheritdoc * * @param {object} attributes * Attributes for the toolbar. * @param {object} options * Options for the toolbar. * * @return {string|undefined} * Returns an error message if validation failed. */ validate: function (attributes, options) { // Prevent the orientation being set to horizontal if it is locked, unless // override has not been passed as an option. if (attributes.orientation === 'horizontal' && this.get('locked') && !options.override) { return Drupal.t('The toolbar cannot be set to a horizontal orientation when it is locked.'); } } }); }(Backbone, Drupal)); ; /** * @file * A Backbone view for the body element. */ (function ($, Drupal, Backbone) { 'use strict'; Drupal.toolbar.BodyVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.BodyVisualView# */{ /** * Adjusts the body element with the toolbar position and dimension changes. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change:orientation change:offsets change:activeTray change:isOriented change:isFixed change:isViewportOverflowConstrained', this.render); }, /** * @inheritdoc */ render: function () { var $body = $('body'); var orientation = this.model.get('orientation'); var isOriented = this.model.get('isOriented'); var isViewportOverflowConstrained = this.model.get('isViewportOverflowConstrained'); $body // We are using JavaScript to control media-query handling for two // reasons: (1) Using JavaScript let's us leverage the breakpoint // configurations and (2) the CSS is really complex if we try to hide // some styling from browsers that don't understand CSS media queries. // If we drive the CSS from classes added through JavaScript, // then the CSS becomes simpler and more robust. .toggleClass('toolbar-vertical', (orientation === 'vertical')) .toggleClass('toolbar-horizontal', (isOriented && orientation === 'horizontal')) // When the toolbar is fixed, it will not scroll with page scrolling. .toggleClass('toolbar-fixed', (isViewportOverflowConstrained || this.model.get('isFixed'))) // Toggle the toolbar-tray-open class on the body element. The class is // applied when a toolbar tray is active. Padding might be applied to // the body element to prevent the tray from overlapping content. .toggleClass('toolbar-tray-open', !!this.model.get('activeTray')) // Apply padding to the top of the body to offset the placement of the // toolbar bar element. .css('padding-top', this.model.get('offsets').top); } }); }(jQuery, Drupal, Backbone)); ; /** * @file * A Backbone view for the collapsible menus. */ (function ($, Backbone, Drupal) { 'use strict'; Drupal.toolbar.MenuVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.MenuVisualView# */{ /** * Backbone View for collapsible menus. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change:subtrees', this.render); }, /** * @inheritdoc */ render: function () { var subtrees = this.model.get('subtrees'); // Add subtrees. for (var id in subtrees) { if (subtrees.hasOwnProperty(id)) { this.$el .find('#toolbar-link-' + id) .once('toolbar-subtrees') .after(subtrees[id]); } } // Render the main menu as a nested, collapsible accordion. if ('drupalToolbarMenu' in $.fn) { this.$el .children('.toolbar-menu') .drupalToolbarMenu(); } } }); }(jQuery, Backbone, Drupal)); ; /** * @file * A Backbone view for the aural feedback of the toolbar. */ (function (Backbone, Drupal) { 'use strict'; Drupal.toolbar.ToolbarAuralView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarAuralView# */{ /** * Backbone view for the aural feedback of the toolbar. * * @constructs * * @augments Backbone.View * * @param {object} options * Options for the view. * @param {object} options.strings * Various strings to use in the view. */ initialize: function (options) { this.strings = options.strings; this.listenTo(this.model, 'change:orientation', this.onOrientationChange); this.listenTo(this.model, 'change:activeTray', this.onActiveTrayChange); }, /** * Announces an orientation change. * * @param {Drupal.toolbar.ToolbarModel} model * The toolbar model in question. * @param {string} orientation * The new value of the orientation attribute in the model. */ onOrientationChange: function (model, orientation) { Drupal.announce(Drupal.t('Tray orientation changed to @orientation.', { '@orientation': orientation })); }, /** * Announces a changed active tray. * * @param {Drupal.toolbar.ToolbarModel} model * The toolbar model in question. * @param {HTMLElement} tray * The new value of the tray attribute in the model. */ onActiveTrayChange: function (model, tray) { var relevantTray = (tray === null) ? model.previous('activeTray') : tray; var action = (tray === null) ? Drupal.t('closed') : Drupal.t('opened'); var trayNameElement = relevantTray.querySelector('.toolbar-tray-name'); var text; if (trayNameElement !== null) { text = Drupal.t('Tray "@tray" @action.', { '@tray': trayNameElement.textContent, '@action': action }); } else { text = Drupal.t('Tray @action.', {'@action': action}); } Drupal.announce(text); } }); }(Backbone, Drupal)); ; /** * @file * A Backbone view for the toolbar element. Listens to mouse & touch. */ (function ($, Drupal, drupalSettings, Backbone) { 'use strict'; Drupal.toolbar.ToolbarVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarVisualView# */{ /** * Event map for the `ToolbarVisualView`. * * @return {object} * A map of events. */ events: function () { // Prevents delay and simulated mouse events. var touchEndToClick = function (event) { event.preventDefault(); event.target.click(); }; return { 'click .toolbar-bar .toolbar-tab': 'onTabClick', 'click .toolbar-toggle-orientation button': 'onOrientationToggleClick', 'touchend .toolbar-bar .toolbar-tab': touchEndToClick, 'touchend .toolbar-toggle-orientation button': touchEndToClick }; }, /** * Backbone view for the toolbar element. Listens to mouse & touch. * * @constructs * * @augments Backbone.View * * @param {object} options * Options for the view object. * @param {object} options.strings * Various strings to use in the view. */ initialize: function (options) { this.strings = options.strings; this.listenTo(this.model, 'change:activeTab change:orientation change:isOriented change:isTrayToggleVisible', this.render); this.listenTo(this.model, 'change:mqMatches', this.onMediaQueryChange); this.listenTo(this.model, 'change:offsets', this.adjustPlacement); // Add the tray orientation toggles. this.$el .find('.toolbar-tray .toolbar-lining') .append(Drupal.theme('toolbarOrientationToggle')); // Trigger an activeTab change so that listening scripts can respond on // page load. This will call render. this.model.trigger('change:activeTab'); }, /** * @inheritdoc * * @return {Drupal.toolbar.ToolbarVisualView} * The `ToolbarVisualView` instance. */ render: function () { this.updateTabs(); this.updateTrayOrientation(); this.updateBarAttributes(); // Load the subtrees if the orientation of the toolbar is changed to // vertical. This condition responds to the case that the toolbar switches // from horizontal to vertical orientation. The toolbar starts in a // vertical orientation by default and then switches to horizontal during // initialization if the media query conditions are met. Simply checking // that the orientation is vertical here would result in the subtrees // always being loaded, even when the toolbar initialization ultimately // results in a horizontal orientation. // // @see Drupal.behaviors.toolbar.attach() where admin menu subtrees // loading is invoked during initialization after media query conditions // have been processed. if (this.model.changed.orientation === 'vertical' || this.model.changed.activeTab) { this.loadSubtrees(); } // Trigger a recalculation of viewport displacing elements. Use setTimeout // to ensure this recalculation happens after changes to visual elements // have processed. window.setTimeout(function () { Drupal.displace(true); }, 0); return this; }, /** * Responds to a toolbar tab click. * * @param {jQuery.Event} event * The event triggered. */ onTabClick: function (event) { // If this tab has a tray associated with it, it is considered an // activatable tab. if (event.target.hasAttribute('data-toolbar-tray')) { var activeTab = this.model.get('activeTab'); var clickedTab = event.target; // Set the event target as the active item if it is not already. this.model.set('activeTab', (!activeTab || clickedTab !== activeTab) ? clickedTab : null); event.preventDefault(); event.stopPropagation(); } }, /** * Toggles the orientation of a toolbar tray. * * @param {jQuery.Event} event * The event triggered. */ onOrientationToggleClick: function (event) { var orientation = this.model.get('orientation'); // Determine the toggle-to orientation. var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical'; var locked = antiOrientation === 'vertical'; // Remember the locked state. if (locked) { localStorage.setItem('Drupal.toolbar.trayVerticalLocked', 'true'); } else { localStorage.removeItem('Drupal.toolbar.trayVerticalLocked'); } // Update the model. this.model.set({ locked: locked, orientation: antiOrientation }, { validate: true, override: true }); event.preventDefault(); event.stopPropagation(); }, /** * Updates the display of the tabs: toggles a tab and the associated tray. */ updateTabs: function () { var $tab = $(this.model.get('activeTab')); // Deactivate the previous tab. $(this.model.previous('activeTab')) .removeClass('is-active') .prop('aria-pressed', false); // Deactivate the previous tray. $(this.model.previous('activeTray')) .removeClass('is-active'); // Activate the selected tab. if ($tab.length > 0) { $tab .addClass('is-active') // Mark the tab as pressed. .prop('aria-pressed', true); var name = $tab.attr('data-toolbar-tray'); // Store the active tab name or remove the setting. var id = $tab.get(0).id; if (id) { localStorage.setItem('Drupal.toolbar.activeTabID', JSON.stringify(id)); } // Activate the associated tray. var $tray = this.$el.find('[data-toolbar-tray="' + name + '"].toolbar-tray'); if ($tray.length) { $tray.addClass('is-active'); this.model.set('activeTray', $tray.get(0)); } else { // There is no active tray. this.model.set('activeTray', null); } } else { // There is no active tray. this.model.set('activeTray', null); localStorage.removeItem('Drupal.toolbar.activeTabID'); } }, /** * Update the attributes of the toolbar bar element. */ updateBarAttributes: function () { var isOriented = this.model.get('isOriented'); if (isOriented) { this.$el.find('.toolbar-bar').attr('data-offset-top', ''); } else { this.$el.find('.toolbar-bar').removeAttr('data-offset-top'); } // Toggle between a basic vertical view and a more sophisticated // horizontal and vertical display of the toolbar bar and trays. this.$el.toggleClass('toolbar-oriented', isOriented); }, /** * Updates the orientation of the active tray if necessary. */ updateTrayOrientation: function () { var orientation = this.model.get('orientation'); // The antiOrientation is used to render the view of action buttons like // the tray orientation toggle. var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical'; // Update the orientation of the trays. var $trays = this.$el.find('.toolbar-tray') .removeClass('toolbar-tray-horizontal toolbar-tray-vertical') .addClass('toolbar-tray-' + orientation); // Update the tray orientation toggle button. var iconClass = 'toolbar-icon-toggle-' + orientation; var iconAntiClass = 'toolbar-icon-toggle-' + antiOrientation; var $orientationToggle = this.$el.find('.toolbar-toggle-orientation') .toggle(this.model.get('isTrayToggleVisible')); $orientationToggle.find('button') .val(antiOrientation) .attr('title', this.strings[antiOrientation]) .text(this.strings[antiOrientation]) .removeClass(iconClass) .addClass(iconAntiClass); // Update data offset attributes for the trays. var dir = document.documentElement.dir; var edge = (dir === 'rtl') ? 'right' : 'left'; // Remove data-offset attributes from the trays so they can be refreshed. $trays.removeAttr('data-offset-left data-offset-right data-offset-top'); // If an active vertical tray exists, mark it as an offset element. $trays.filter('.toolbar-tray-vertical.is-active').attr('data-offset-' + edge, ''); // If an active horizontal tray exists, mark it as an offset element. $trays.filter('.toolbar-tray-horizontal.is-active').attr('data-offset-top', ''); }, /** * Sets the tops of the trays so that they align with the bottom of the bar. */ adjustPlacement: function () { var $trays = this.$el.find('.toolbar-tray'); if (!this.model.get('isOriented')) { $trays.css('margin-top', 0); $trays.removeClass('toolbar-tray-horizontal').addClass('toolbar-tray-vertical'); } else { // The toolbar container is invisible. Its placement is used to // determine the container for the trays. $trays.css('margin-top', this.$el.find('.toolbar-bar').outerHeight()); } }, /** * Calls the endpoint URI that builds an AJAX command with the rendered * subtrees. * * The rendered admin menu subtrees HTML is cached on the client in * localStorage until the cache of the admin menu subtrees on the server- * side is invalidated. The subtreesHash is stored in localStorage as well * and compared to the subtreesHash in drupalSettings to determine when the * admin menu subtrees cache has been invalidated. */ loadSubtrees: function () { var $activeTab = $(this.model.get('activeTab')); var orientation = this.model.get('orientation'); // Only load and render the admin menu subtrees if: // (1) They have not been loaded yet. // (2) The active tab is the administration menu tab, indicated by the // presence of the data-drupal-subtrees attribute. // (3) The orientation of the tray is vertical. if (!this.model.get('areSubtreesLoaded') && typeof $activeTab.data('drupal-subtrees') !== 'undefined' && orientation === 'vertical') { var subtreesHash = drupalSettings.toolbar.subtreesHash; var theme = drupalSettings.ajaxPageState.theme; var endpoint = Drupal.url('toolbar/subtrees/' + subtreesHash); var cachedSubtreesHash = localStorage.getItem('Drupal.toolbar.subtreesHash.' + theme); var cachedSubtrees = JSON.parse(localStorage.getItem('Drupal.toolbar.subtrees.' + theme)); var isVertical = this.model.get('orientation') === 'vertical'; // If we have the subtrees in localStorage and the subtree hash has not // changed, then use the cached data. if (isVertical && subtreesHash === cachedSubtreesHash && cachedSubtrees) { Drupal.toolbar.setSubtrees.resolve(cachedSubtrees); } // Only make the call to get the subtrees if the orientation of the // toolbar is vertical. else if (isVertical) { // Remove the cached menu information. localStorage.removeItem('Drupal.toolbar.subtreesHash.' + theme); localStorage.removeItem('Drupal.toolbar.subtrees.' + theme); // The AJAX response's command will trigger the resolve method of the // Drupal.toolbar.setSubtrees Promise. Drupal.ajax({url: endpoint}).execute(); // Cache the hash for the subtrees locally. localStorage.setItem('Drupal.toolbar.subtreesHash.' + theme, subtreesHash); } } } }); }(jQuery, Drupal, drupalSettings, Backbone)); ; /* jQuery Foundation Joyride Plugin 2.1 | Copyright 2012, ZURB | www.opensource.org/licenses/mit-license.php */ (function(e,t,n){"use strict";var r={version:"2.0.3",tipLocation:"bottom",nubPosition:"auto",scroll:!0,scrollSpeed:300,timer:0,autoStart:!1,startTimerOnClick:!0,startOffset:0,nextButton:!0,tipAnimation:"fade",pauseAfter:[],tipAnimationFadeSpeed:300,cookieMonster:!1,cookieName:"joyride",cookieDomain:!1,cookiePath:!1,localStorage:!1,localStorageKey:"joyride",tipContainer:"body",modal:!1,expose:!1,postExposeCallback:e.noop,preRideCallback:e.noop,postRideCallback:e.noop,preStepCallback:e.noop,postStepCallback:e.noop,template:{link:'<a href="#close" class="joyride-close-tip">X</a>',timer:'<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>',tip:'<div class="joyride-tip-guide"><span class="joyride-nub"></span></div>',wrapper:'<div class="joyride-content-wrapper" role="dialog"></div>',button:'<a href="#" class="joyride-next-tip"></a>',modal:'<div class="joyride-modal-bg"></div>',expose:'<div class="joyride-expose-wrapper"></div>',exposeCover:'<div class="joyride-expose-cover"></div>'}},i=i||!1,s={},o={init:function(n){return this.each(function(){e.isEmptyObject(s)?(s=e.extend(!0,r,n),s.document=t.document,s.$document=e(s.document),s.$window=e(t),s.$content_el=e(this),s.$body=e(s.tipContainer),s.body_offset=e(s.tipContainer).position(),s.$tip_content=e("> li",s.$content_el),s.paused=!1,s.attempts=0,s.tipLocationPatterns={top:["bottom"],bottom:[],left:["right","top","bottom"],right:["left","top","bottom"]},o.jquery_check(),e.isFunction(e.cookie)||(s.cookieMonster=!1),(!s.cookieMonster||!e.cookie(s.cookieName))&&(!s.localStorage||!o.support_localstorage()||!localStorage.getItem(s.localStorageKey))&&(s.$tip_content.each(function(t){o.create({$li:e(this),index:t})}),s.autoStart&&(!s.startTimerOnClick&&s.timer>0?(o.show("init"),o.startTimer()):o.show("init"))),s.$document.on("click.joyride",".joyride-next-tip, .joyride-modal-bg",function(e){e.preventDefault(),s.$li.next().length<1?o.end():s.timer>0?(clearTimeout(s.automate),o.hide(),o.show(),o.startTimer()):(o.hide(),o.show())}),s.$document.on("click.joyride",".joyride-close-tip",function(e){e.preventDefault(),o.end()}),s.$window.bind("resize.joyride",function(t){if(s.$li){if(s.exposed&&s.exposed.length>0){var n=e(s.exposed);n.each(function(){var t=e(this);o.un_expose(t),o.expose(t)})}o.is_phone()?o.pos_phone():o.pos_default()}})):o.restart()})},resume:function(){o.set_li(),o.show()},nextTip:function(){s.$li.next().length<1?o.end():s.timer>0?(clearTimeout(s.automate),o.hide(),o.show(),o.startTimer()):(o.hide(),o.show())},tip_template:function(t){var n,r,i;return t.tip_class=t.tip_class||"",n=e(s.template.tip).addClass(t.tip_class),r=e.trim(e(t.li).html())+o.button_text(t.button_text)+s.template.link+o.timer_instance(t.index),i=e(s.template.wrapper),t.li.attr("data-aria-labelledby")&&i.attr("aria-labelledby",t.li.attr("data-aria-labelledby")),t.li.attr("data-aria-describedby")&&i.attr("aria-describedby",t.li.attr("data-aria-describedby")),n.append(i),n.first().attr("data-index",t.index),e(".joyride-content-wrapper",n).append(r),n[0]},timer_instance:function(t){var n;return t===0&&s.startTimerOnClick&&s.timer>0||s.timer===0?n="":n=o.outerHTML(e(s.template.timer)[0]),n},button_text:function(t){return s.nextButton?(t=e.trim(t)||"Next",t=o.outerHTML(e(s.template.button).append(t)[0])):t="",t},create:function(t){var n=t.$li.attr("data-button")||t.$li.attr("data-text"),r=t.$li.attr("class"),i=e(o.tip_template({tip_class:r,index:t.index,button_text:n,li:t.$li}));e(s.tipContainer).append(i)},show:function(t){var r={},i,u=[],a=0,f,l=null;if(s.$li===n||e.inArray(s.$li.index(),s.pauseAfter)===-1){s.paused?s.paused=!1:o.set_li(t),s.attempts=0;if(s.$li.length&&s.$target.length>0){t&&(s.preRideCallback(s.$li.index(),s.$next_tip),s.modal&&o.show_modal()),s.preStepCallback(s.$li.index(),s.$next_tip),u=(s.$li.data("options")||":").split(";"),a=u.length;for(i=a-1;i>=0;i--)f=u[i].split(":"),f.length===2&&(r[e.trim(f[0])]=e.trim(f[1]));s.tipSettings=e.extend({},s,r),s.tipSettings.tipLocationPattern=s.tipLocationPatterns[s.tipSettings.tipLocation],s.modal&&s.expose&&o.expose(),!/body/i.test(s.$target.selector)&&s.scroll&&o.scroll_to(),o.is_phone()?o.pos_phone(!0):o.pos_default(!0),l=e(".joyride-timer-indicator",s.$next_tip),/pop/i.test(s.tipAnimation)?(l.outerWidth(0),s.timer>0?(s.$next_tip.show(),l.animate({width:e(".joyride-timer-indicator-wrap",s.$next_tip).outerWidth()},s.timer)):s.$next_tip.show()):/fade/i.test(s.tipAnimation)&&(l.outerWidth(0),s.timer>0?(s.$next_tip.fadeIn(s.tipAnimationFadeSpeed),s.$next_tip.show(),l.animate({width:e(".joyride-timer-indicator-wrap",s.$next_tip).outerWidth()},s.timer)):s.$next_tip.fadeIn(s.tipAnimationFadeSpeed)),s.$current_tip=s.$next_tip,e(".joyride-next-tip",s.$current_tip).focus(),o.tabbable(s.$current_tip)}else s.$li&&s.$target.length<1?o.show():o.end()}else s.paused=!0},is_phone:function(){return i?i.mq("only screen and (max-width: 767px)"):s.$window.width()<767?!0:!1},support_localstorage:function(){return i?i.localstorage:!!t.localStorage},hide:function(){s.modal&&s.expose&&o.un_expose(),s.modal||e(".joyride-modal-bg").hide(),s.$current_tip.hide(),s.postStepCallback(s.$li.index(),s.$current_tip)},set_li:function(e){e?(s.$li=s.$tip_content.eq(s.startOffset),o.set_next_tip(),s.$current_tip=s.$next_tip):(s.$li=s.$li.next(),o.set_next_tip()),o.set_target()},set_next_tip:function(){s.$next_tip=e(".joyride-tip-guide[data-index="+s.$li.index()+"]")},set_target:function(){var t=s.$li.attr("data-class"),n=s.$li.attr("data-id"),r=function(){return n?e(s.document.getElementById(n)):t?e("."+t).filter(":visible").first():e("body")};s.$target=r()},scroll_to:function(){var t,n;t=s.$window.height()/2,n=Math.ceil(s.$target.offset().top-t+s.$next_tip.outerHeight()),e("html, body").stop().animate({scrollTop:n},s.scrollSpeed)},paused:function(){return e.inArray(s.$li.index()+1,s.pauseAfter)===-1?!0:!1},destroy:function(){e.isEmptyObject(s)||s.$document.off(".joyride"),e(t).off(".joyride"),e(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off(".joyride"),e(".joyride-tip-guide, .joyride-modal-bg").remove(),clearTimeout(s.automate),s={}},restart:function(){s.autoStart?(o.hide(),s.$li=n,o.show("init")):(!s.startTimerOnClick&&s.timer>0?(o.show("init"),o.startTimer()):o.show("init"),s.autoStart=!0)},pos_default:function(t){var n=Math.ceil(s.$window.height()/2),r=s.$next_tip.offset(),i=e(".joyride-nub",s.$next_tip),u=Math.ceil(i.outerWidth()/2),a=Math.ceil(i.outerHeight()/2),f=t||!1;f&&(s.$next_tip.css("visibility","hidden"),s.$next_tip.show());if(!/body/i.test(s.$target.selector)){var l=s.tipSettings.tipAdjustmentY?parseInt(s.tipSettings.tipAdjustmentY):0,c=s.tipSettings.tipAdjustmentX?parseInt(s.tipSettings.tipAdjustmentX):0;o.bottom()?(s.$next_tip.css({top:s.$target.offset().top+a+s.$target.outerHeight()+l,left:s.$target.offset().left+c}),/right/i.test(s.tipSettings.nubPosition)&&s.$next_tip.css("left",s.$target.offset().left-s.$next_tip.outerWidth()+s.$target.outerWidth()),o.nub_position(i,s.tipSettings.nubPosition,"top")):o.top()?(s.$next_tip.css({top:s.$target.offset().top-s.$next_tip.outerHeight()-a+l,left:s.$target.offset().left+c}),o.nub_position(i,s.tipSettings.nubPosition,"bottom")):o.right()?(s.$next_tip.css({top:s.$target.offset().top+l,left:s.$target.outerWidth()+s.$target.offset().left+u+c}),o.nub_position(i,s.tipSettings.nubPosition,"left")):o.left()&&(s.$next_tip.css({top:s.$target.offset().top+l,left:s.$target.offset().left-s.$next_tip.outerWidth()-u+c}),o.nub_position(i,s.tipSettings.nubPosition,"right")),!o.visible(o.corners(s.$next_tip))&&s.attempts<s.tipSettings.tipLocationPattern.length&&(i.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),s.tipSettings.tipLocation=s.tipSettings.tipLocationPattern[s.attempts],s.attempts++,o.pos_default(!0))}else s.$li.length&&o.pos_modal(i);f&&(s.$next_tip.hide(),s.$next_tip.css("visibility","visible"))},pos_phone:function(t){var n=s.$next_tip.outerHeight(),r=s.$next_tip.offset(),i=s.$target.outerHeight(),u=e(".joyride-nub",s.$next_tip),a=Math.ceil(u.outerHeight()/2),f=t||!1;u.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),f&&(s.$next_tip.css("visibility","hidden"),s.$next_tip.show()),/body/i.test(s.$target.selector)?s.$li.length&&o.pos_modal(u):o.top()?(s.$next_tip.offset({top:s.$target.offset().top-n-a}),u.addClass("bottom")):(s.$next_tip.offset({top:s.$target.offset().top+i+a}),u.addClass("top")),f&&(s.$next_tip.hide(),s.$next_tip.css("visibility","visible"))},pos_modal:function(e){o.center(),e.hide(),o.show_modal()},show_modal:function(){e(".joyride-modal-bg").length<1&&e("body").append(s.template.modal).show(),/pop/i.test(s.tipAnimation)?e(".joyride-modal-bg").show():e(".joyride-modal-bg").fadeIn(s.tipAnimationFadeSpeed)},expose:function(){var n,r,i,u,a="expose-"+Math.floor(Math.random()*1e4);if(arguments.length>0&&arguments[0]instanceof e)i=arguments[0];else{if(!s.$target||!!/body/i.test(s.$target.selector))return!1;i=s.$target}if(i.length<1)return t.console&&console.error("element not valid",i),!1;n=e(s.template.expose),s.$body.append(n),n.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),r=e(s.template.exposeCover),u={zIndex:i.css("z-index"),position:i.css("position")},i.css("z-index",n.css("z-index")*1+1),u.position=="static"&&i.css("position","relative"),i.data("expose-css",u),r.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),s.$body.append(r),n.addClass(a),r.addClass(a),s.tipSettings.exposeClass&&(n.addClass(s.tipSettings.exposeClass),r.addClass(s.tipSettings.exposeClass)),i.data("expose",a),s.postExposeCallback(s.$li.index(),s.$next_tip,i),o.add_exposed(i)},un_expose:function(){var n,r,i,u,a=!1;if(arguments.length>0&&arguments[0]instanceof e)r=arguments[0];else{if(!s.$target||!!/body/i.test(s.$target.selector))return!1;r=s.$target}if(r.length<1)return t.console&&console.error("element not valid",r),!1;n=r.data("expose"),i=e("."+n),arguments.length>1&&(a=arguments[1]),a===!0?e(".joyride-expose-wrapper,.joyride-expose-cover").remove():i.remove(),u=r.data("expose-css"),u.zIndex=="auto"?r.css("z-index",""):r.css("z-index",u.zIndex),u.position!=r.css("position")&&(u.position=="static"?r.css("position",""):r.css("position",u.position)),r.removeData("expose"),r.removeData("expose-z-index"),o.remove_exposed(r)},add_exposed:function(t){s.exposed=s.exposed||[],t instanceof e?s.exposed.push(t[0]):typeof t=="string"&&s.exposed.push(t)},remove_exposed:function(t){var n;t instanceof e?n=t[0]:typeof t=="string"&&(n=t),s.exposed=s.exposed||[];for(var r=0;r<s.exposed.length;r++)if(s.exposed[r]==n){s.exposed.splice(r,1);return}},center:function(){var e=s.$window;return s.$next_tip.css({top:(e.height()-s.$next_tip.outerHeight())/2+e.scrollTop(),left:(e.width()-s.$next_tip.outerWidth())/2+e.scrollLeft()}),!0},bottom:function(){return/bottom/i.test(s.tipSettings.tipLocation)},top:function(){return/top/i.test(s.tipSettings.tipLocation)},right:function(){return/right/i.test(s.tipSettings.tipLocation)},left:function(){return/left/i.test(s.tipSettings.tipLocation)},corners:function(e){var t=s.$window,n=t.height()/2,r=Math.ceil(s.$target.offset().top-n+s.$next_tip.outerHeight()),i=t.width()+t.scrollLeft(),o=t.height()+r,u=t.height()+t.scrollTop(),a=t.scrollTop();return r<a&&(r<0?a=0:a=r),o>u&&(u=o),[e.offset().top<a,i<e.offset().left+e.outerWidth(),u<e.offset().top+e.outerHeight(),t.scrollLeft()>e.offset().left]},visible:function(e){var t=e.length;while(t--)if(e[t])return!1;return!0},nub_position:function(e,t,n){t==="auto"?e.addClass(n):e.addClass(t)},startTimer:function(){s.$li.length?s.automate=setTimeout(function(){o.hide(),o.show(),o.startTimer()},s.timer):clearTimeout(s.automate)},end:function(){s.cookieMonster&&e.cookie(s.cookieName,"ridden",{expires:365,domain:s.cookieDomain,path:s.cookiePath}),s.localStorage&&localStorage.setItem(s.localStorageKey,!0),s.timer>0&&clearTimeout(s.automate),s.modal&&s.expose&&o.un_expose(),s.$current_tip&&s.$current_tip.hide(),s.$li&&(s.postStepCallback(s.$li.index(),s.$current_tip),s.postRideCallback(s.$li.index(),s.$current_tip)),e(".joyride-modal-bg").hide()},jquery_check:function(){return e.isFunction(e.fn.on)?!0:(e.fn.on=function(e,t,n){return this.delegate(t,e,n)},e.fn.off=function(e,t,n){return this.undelegate(t,e,n)},!1)},outerHTML:function(e){return e.outerHTML||(new XMLSerializer).serializeToString(e)},version:function(){return s.version},tabbable:function(t){e(t).on("keydown",function(n){if(!n.isDefaultPrevented()&&n.keyCode&&n.keyCode===27){n.preventDefault(),o.end();return}if(n.keyCode!==9)return;var r=e(t).find(":tabbable"),i=r.filter(":first"),s=r.filter(":last");n.target===s[0]&&!n.shiftKey?(i.focus(1),n.preventDefault()):n.target===i[0]&&n.shiftKey&&(s.focus(1),n.preventDefault())})}};e.fn.joyride=function(t){if(o[t])return o[t].apply(this,Array.prototype.slice.call(arguments,1));if(typeof t=="object"||!t)return o.init.apply(this,arguments);e.error("Method "+t+" does not exist on jQuery.joyride")}})(jQuery,this); ; /** * @file * Attaches behaviors for the Tour module's toolbar tab. */ (function ($, Backbone, Drupal, document) { 'use strict'; var queryString = decodeURI(window.location.search); /** * Attaches the tour's toolbar tab behavior. * * It uses the query string for: * - tour: When ?tour=1 is present, the tour will start automatically after * the page has loaded. * - tips: Pass ?tips=class in the url to filter the available tips to the * subset which match the given class. * * @example * http://example.com/foo?tour=1&tips=bar * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attach tour functionality on `tour` events. */ Drupal.behaviors.tour = { attach: function (context) { $('body').once('tour').each(function () { var model = new Drupal.tour.models.StateModel(); new Drupal.tour.views.ToggleTourView({ el: $(context).find('#toolbar-tab-tour'), model: model }); model // Allow other scripts to respond to tour events. .on('change:isActive', function (model, isActive) { $(document).trigger((isActive) ? 'drupalTourStarted' : 'drupalTourStopped'); }) // Initialization: check whether a tour is available on the current // page. .set('tour', $(context).find('ol#tour')); // Start the tour immediately if toggled via query string. if (/tour=?/i.test(queryString)) { model.set('isActive', true); } }); } }; /** * @namespace */ Drupal.tour = Drupal.tour || { /** * @namespace Drupal.tour.models */ models: {}, /** * @namespace Drupal.tour.views */ views: {} }; /** * Backbone Model for tours. * * @constructor * * @augments Backbone.Model */ Drupal.tour.models.StateModel = Backbone.Model.extend(/** @lends Drupal.tour.models.StateModel# */{ /** * @type {object} */ defaults: /** @lends Drupal.tour.models.StateModel# */{ /** * Indicates whether the Drupal root window has a tour. * * @type {Array} */ tour: [], /** * Indicates whether the tour is currently running. * * @type {bool} */ isActive: false, /** * Indicates which tour is the active one (necessary to cleanly stop). * * @type {Array} */ activeTour: [] } }); Drupal.tour.views.ToggleTourView = Backbone.View.extend(/** @lends Drupal.tour.views.ToggleTourView# */{ /** * @type {object} */ events: {click: 'onClick'}, /** * Handles edit mode toggle interactions. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change:tour change:isActive', this.render); this.listenTo(this.model, 'change:isActive', this.toggleTour); }, /** * @inheritdoc * * @return {Drupal.tour.views.ToggleTourView} * The `ToggleTourView` view. */ render: function () { // Render the visibility. this.$el.toggleClass('hidden', this._getTour().length === 0); // Render the state. var isActive = this.model.get('isActive'); this.$el.find('button') .toggleClass('is-active', isActive) .prop('aria-pressed', isActive); return this; }, /** * Model change handler; starts or stops the tour. */ toggleTour: function () { if (this.model.get('isActive')) { var $tour = this._getTour(); this._removeIrrelevantTourItems($tour, this._getDocument()); var that = this; if ($tour.find('li').length) { $tour.joyride({ autoStart: true, postRideCallback: function () { that.model.set('isActive', false); }, // HTML segments for tip layout. template: { link: '<a href=\"#close\" class=\"joyride-close-tip\">&times;</a>', button: '<a href=\"#\" class=\"button button--primary joyride-next-tip\"></a>' } }); this.model.set({isActive: true, activeTour: $tour}); } } else { this.model.get('activeTour').joyride('destroy'); this.model.set({isActive: false, activeTour: []}); } }, /** * Toolbar tab click event handler; toggles isActive. * * @param {jQuery.Event} event * The click event. */ onClick: function (event) { this.model.set('isActive', !this.model.get('isActive')); event.preventDefault(); event.stopPropagation(); }, /** * Gets the tour. * * @return {jQuery} * A jQuery element pointing to a `<ol>` containing tour items. */ _getTour: function () { return this.model.get('tour'); }, /** * Gets the relevant document as a jQuery element. * * @return {jQuery} * A jQuery element pointing to the document within which a tour would be * started given the current state. */ _getDocument: function () { return $(document); }, /** * Removes tour items for elements that don't have matching page elements. * * Or that are explicitly filtered out via the 'tips' query string. * * @example * <caption>This will filter out tips that do not have a matching * page element or don't have the "bar" class.</caption> * http://example.com/foo?tips=bar * * @param {jQuery} $tour * A jQuery element pointing to a `<ol>` containing tour items. * @param {jQuery} $document * A jQuery element pointing to the document within which the elements * should be sought. * * @see Drupal.tour.views.ToggleTourView#_getDocument */ _removeIrrelevantTourItems: function ($tour, $document) { var removals = false; var tips = /tips=([^&]+)/.exec(queryString); $tour .find('li') .each(function () { var $this = $(this); var itemId = $this.attr('data-id'); var itemClass = $this.attr('data-class'); // If the query parameter 'tips' is set, remove all tips that don't // have the matching class. if (tips && !$(this).hasClass(tips[1])) { removals = true; $this.remove(); return; } // Remove tip from the DOM if there is no corresponding page element. if ((!itemId && !itemClass) || (itemId && $document.find('#' + itemId).length) || (itemClass && $document.find('.' + itemClass).length)) { return; } removals = true; $this.remove(); }); // If there were removals, we'll have to do some clean-up. if (removals) { var total = $tour.find('li').length; if (!total) { this.model.set({tour: []}); } $tour .find('li') // Rebuild the progress data. .each(function (index) { var progress = Drupal.t('!tour_item of !total', {'!tour_item': index + 1, '!total': total}); $(this).find('.tour-progress').text(progress); }) // Update the last item to have "End tour" as the button. .eq(-1) .attr('data-text', Drupal.t('End tour')); } } }); })(jQuery, Backbone, Drupal, document); ; /** * @file * Manages page tabbing modifications made by modules. */ /** * Allow modules to respond to the constrain event. * * @event drupalTabbingConstrained */ /** * Allow modules to respond to the tabbingContext release event. * * @event drupalTabbingContextReleased */ /** * Allow modules to respond to the constrain event. * * @event drupalTabbingContextActivated */ /** * Allow modules to respond to the constrain event. * * @event drupalTabbingContextDeactivated */ (function ($, Drupal) { 'use strict'; /** * Provides an API for managing page tabbing order modifications. * * @constructor Drupal~TabbingManager */ function TabbingManager() { /** * Tabbing sets are stored as a stack. The active set is at the top of the * stack. We use a JavaScript array as if it were a stack; we consider the * first element to be the bottom and the last element to be the top. This * allows us to use JavaScript's built-in Array.push() and Array.pop() * methods. * * @type {Array.<Drupal~TabbingContext>} */ this.stack = []; } /** * Add public methods to the TabbingManager class. */ $.extend(TabbingManager.prototype, /** @lends Drupal~TabbingManager# */{ /** * Constrain tabbing to the specified set of elements only. * * Makes elements outside of the specified set of elements unreachable via * the tab key. * * @param {jQuery} elements * The set of elements to which tabbing should be constrained. Can also * be a jQuery-compatible selector string. * * @return {Drupal~TabbingContext} * The TabbingContext instance. * * @fires event:drupalTabbingConstrained */ constrain: function (elements) { // Deactivate all tabbingContexts to prepare for the new constraint. A // tabbingContext instance will only be reactivated if the stack is // unwound to it in the _unwindStack() method. var il = this.stack.length; for (var i = 0; i < il; i++) { this.stack[i].deactivate(); } // The "active tabbing set" are the elements tabbing should be constrained // to. var $elements = $(elements).find(':tabbable').addBack(':tabbable'); var tabbingContext = new TabbingContext({ // The level is the current height of the stack before this new // tabbingContext is pushed on top of the stack. level: this.stack.length, $tabbableElements: $elements }); this.stack.push(tabbingContext); // Activates the tabbingContext; this will manipulate the DOM to constrain // tabbing. tabbingContext.activate(); // Allow modules to respond to the constrain event. $(document).trigger('drupalTabbingConstrained', tabbingContext); return tabbingContext; }, /** * Restores a former tabbingContext when an active one is released. * * The TabbingManager stack of tabbingContext instances will be unwound * from the top-most released tabbingContext down to the first non-released * tabbingContext instance. This non-released instance is then activated. */ release: function () { // Unwind as far as possible: find the topmost non-released // tabbingContext. var toActivate = this.stack.length - 1; while (toActivate >= 0 && this.stack[toActivate].released) { toActivate--; } // Delete all tabbingContexts after the to be activated one. They have // already been deactivated, so their effect on the DOM has been reversed. this.stack.splice(toActivate + 1); // Get topmost tabbingContext, if one exists, and activate it. if (toActivate >= 0) { this.stack[toActivate].activate(); } }, /** * Makes all elements outside of the tabbingContext's set untabbable. * * Elements made untabbable have their original tabindex and autofocus * values stored so that they might be restored later when this * tabbingContext is deactivated. * * @param {Drupal~TabbingContext} tabbingContext * The TabbingContext instance that has been activated. */ activate: function (tabbingContext) { var $set = tabbingContext.$tabbableElements; var level = tabbingContext.level; // Determine which elements are reachable via tabbing by default. var $disabledSet = $(':tabbable') // Exclude elements of the active tabbing set. .not($set); // Set the disabled set on the tabbingContext. tabbingContext.$disabledElements = $disabledSet; // Record the tabindex for each element, so we can restore it later. var il = $disabledSet.length; for (var i = 0; i < il; i++) { this.recordTabindex($disabledSet.eq(i), level); } // Make all tabbable elements outside of the active tabbing set // unreachable. $disabledSet .prop('tabindex', -1) .prop('autofocus', false); // Set focus on an element in the tabbingContext's set of tabbable // elements. First, check if there is an element with an autofocus // attribute. Select the last one from the DOM order. var $hasFocus = $set.filter('[autofocus]').eq(-1); // If no element in the tabbable set has an autofocus attribute, select // the first element in the set. if ($hasFocus.length === 0) { $hasFocus = $set.eq(0); } $hasFocus.trigger('focus'); }, /** * Restores that tabbable state of a tabbingContext's disabled elements. * * Elements that were made untabbable have their original tabindex and * autofocus values restored. * * @param {Drupal~TabbingContext} tabbingContext * The TabbingContext instance that has been deactivated. */ deactivate: function (tabbingContext) { var $set = tabbingContext.$disabledElements; var level = tabbingContext.level; var il = $set.length; for (var i = 0; i < il; i++) { this.restoreTabindex($set.eq(i), level); } }, /** * Records the tabindex and autofocus values of an untabbable element. * * @param {jQuery} $el * The set of elements that have been disabled. * @param {number} level * The stack level for which the tabindex attribute should be recorded. */ recordTabindex: function ($el, level) { var tabInfo = $el.data('drupalOriginalTabIndices') || {}; tabInfo[level] = { tabindex: $el[0].getAttribute('tabindex'), autofocus: $el[0].hasAttribute('autofocus') }; $el.data('drupalOriginalTabIndices', tabInfo); }, /** * Restores the tabindex and autofocus values of a reactivated element. * * @param {jQuery} $el * The element that is being reactivated. * @param {number} level * The stack level for which the tabindex attribute should be restored. */ restoreTabindex: function ($el, level) { var tabInfo = $el.data('drupalOriginalTabIndices'); if (tabInfo && tabInfo[level]) { var data = tabInfo[level]; if (data.tabindex) { $el[0].setAttribute('tabindex', data.tabindex); } // If the element did not have a tabindex at this stack level then // remove it. else { $el[0].removeAttribute('tabindex'); } if (data.autofocus) { $el[0].setAttribute('autofocus', 'autofocus'); } // Clean up $.data. if (level === 0) { // Remove all data. $el.removeData('drupalOriginalTabIndices'); } else { // Remove the data for this stack level and higher. var levelToDelete = level; while (tabInfo.hasOwnProperty(levelToDelete)) { delete tabInfo[levelToDelete]; levelToDelete++; } $el.data('drupalOriginalTabIndices', tabInfo); } } } }); /** * Stores a set of tabbable elements. * * This constraint can be removed with the release() method. * * @constructor Drupal~TabbingContext * * @param {object} options * A set of initiating values * @param {number} options.level * The level in the TabbingManager's stack of this tabbingContext. * @param {jQuery} options.$tabbableElements * The DOM elements that should be reachable via the tab key when this * tabbingContext is active. * @param {jQuery} options.$disabledElements * The DOM elements that should not be reachable via the tab key when this * tabbingContext is active. * @param {bool} options.released * A released tabbingContext can never be activated again. It will be * cleaned up when the TabbingManager unwinds its stack. * @param {bool} options.active * When true, the tabbable elements of this tabbingContext will be reachable * via the tab key and the disabled elements will not. Only one * tabbingContext can be active at a time. */ function TabbingContext(options) { $.extend(this, /** @lends Drupal~TabbingContext# */{ /** * @type {?number} */ level: null, /** * @type {jQuery} */ $tabbableElements: $(), /** * @type {jQuery} */ $disabledElements: $(), /** * @type {bool} */ released: false, /** * @type {bool} */ active: false }, options); } /** * Add public methods to the TabbingContext class. */ $.extend(TabbingContext.prototype, /** @lends Drupal~TabbingContext# */{ /** * Releases this TabbingContext. * * Once a TabbingContext object is released, it can never be activated * again. * * @fires event:drupalTabbingContextReleased */ release: function () { if (!this.released) { this.deactivate(); this.released = true; Drupal.tabbingManager.release(this); // Allow modules to respond to the tabbingContext release event. $(document).trigger('drupalTabbingContextReleased', this); } }, /** * Activates this TabbingContext. * * @fires event:drupalTabbingContextActivated */ activate: function () { // A released TabbingContext object can never be activated again. if (!this.active && !this.released) { this.active = true; Drupal.tabbingManager.activate(this); // Allow modules to respond to the constrain event. $(document).trigger('drupalTabbingContextActivated', this); } }, /** * Deactivates this TabbingContext. * * @fires event:drupalTabbingContextDeactivated */ deactivate: function () { if (this.active) { this.active = false; Drupal.tabbingManager.deactivate(this); // Allow modules to respond to the constrain event. $(document).trigger('drupalTabbingContextDeactivated', this); } } }); // Mark this behavior as processed on the first pass and return if it is // already processed. if (Drupal.tabbingManager) { return; } /** * @type {Drupal~TabbingManager} */ Drupal.tabbingManager = new TabbingManager(); }(jQuery, Drupal)); ; /** * @file * Attaches behaviors for the Contextual module's edit toolbar tab. */ (function ($, Drupal, Backbone) { 'use strict'; var strings = { tabbingReleased: Drupal.t('Tabbing is no longer constrained by the Contextual module.'), tabbingConstrained: Drupal.t('Tabbing is constrained to a set of @contextualsCount and the edit mode toggle.'), pressEsc: Drupal.t('Press the esc key to exit.') }; /** * Initializes a contextual link: updates its DOM, sets up model and views. * * @param {HTMLElement} context * A contextual links DOM element as rendered by the server. */ function initContextualToolbar(context) { if (!Drupal.contextual || !Drupal.contextual.collection) { return; } var contextualToolbar = Drupal.contextualToolbar; var model = contextualToolbar.model = new contextualToolbar.StateModel({ // Checks whether localStorage indicates we should start in edit mode // rather than view mode. // @see Drupal.contextualToolbar.VisualView.persist isViewing: localStorage.getItem('Drupal.contextualToolbar.isViewing') !== 'false' }, { contextualCollection: Drupal.contextual.collection }); var viewOptions = { el: $('.toolbar .toolbar-bar .contextual-toolbar-tab'), model: model, strings: strings }; new contextualToolbar.VisualView(viewOptions); new contextualToolbar.AuralView(viewOptions); } /** * Attaches contextual's edit toolbar tab behavior. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches contextual toolbar behavior on a contextualToolbar-init event. */ Drupal.behaviors.contextualToolbar = { attach: function (context) { if ($('body').once('contextualToolbar-init').length) { initContextualToolbar(context); } } }; /** * Namespace for the contextual toolbar. * * @namespace */ Drupal.contextualToolbar = { /** * The {@link Drupal.contextualToolbar.StateModel} instance. * * @type {?Drupal.contextualToolbar.StateModel} */ model: null }; })(jQuery, Drupal, Backbone); ; /** * @file * A Backbone Model for the state of Contextual module's edit toolbar tab. */ (function (Drupal, Backbone) { 'use strict'; Drupal.contextualToolbar.StateModel = Backbone.Model.extend(/** @lends Drupal.contextualToolbar.StateModel# */{ /** * @type {object} * * @prop {bool} isViewing * @prop {bool} isVisible * @prop {number} contextualCount * @prop {Drupal~TabbingContext} tabbingContext */ defaults: /** @lends Drupal.contextualToolbar.StateModel# */{ /** * Indicates whether the toggle is currently in "view" or "edit" mode. * * @type {bool} */ isViewing: true, /** * Indicates whether the toggle should be visible or hidden. Automatically * calculated, depends on contextualCount. * * @type {bool} */ isVisible: false, /** * Tracks how many contextual links exist on the page. * * @type {number} */ contextualCount: 0, /** * A TabbingContext object as returned by {@link Drupal~TabbingManager}: * the set of tabbable elements when edit mode is enabled. * * @type {?Drupal~TabbingContext} */ tabbingContext: null }, /** * Models the state of the edit mode toggle. * * @constructs * * @augments Backbone.Model * * @param {object} attrs * Attributes for the backbone model. * @param {object} options * An object with the following option: * @param {Backbone.collection} options.contextualCollection * The collection of {@link Drupal.contextual.StateModel} models that * represent the contextual links on the page. */ initialize: function (attrs, options) { // Respond to new/removed contextual links. this.listenTo(options.contextualCollection, 'reset remove add', this.countContextualLinks); this.listenTo(options.contextualCollection, 'add', this.lockNewContextualLinks); // Automatically determine visibility. this.listenTo(this, 'change:contextualCount', this.updateVisibility); // Whenever edit mode is toggled, lock all contextual links. this.listenTo(this, 'change:isViewing', function (model, isViewing) { options.contextualCollection.each(function (contextualModel) { contextualModel.set('isLocked', !isViewing); }); }); }, /** * Tracks the number of contextual link models in the collection. * * @param {Drupal.contextual.StateModel} contextualModel * The contextual links model that was added or removed. * @param {Backbone.Collection} contextualCollection * The collection of contextual link models. */ countContextualLinks: function (contextualModel, contextualCollection) { this.set('contextualCount', contextualCollection.length); }, /** * Lock newly added contextual links if edit mode is enabled. * * @param {Drupal.contextual.StateModel} contextualModel * The contextual links model that was added. * @param {Backbone.Collection} [contextualCollection] * The collection of contextual link models. */ lockNewContextualLinks: function (contextualModel, contextualCollection) { if (!this.get('isViewing')) { contextualModel.set('isLocked', true); } }, /** * Automatically updates visibility of the view/edit mode toggle. */ updateVisibility: function () { this.set('isVisible', this.get('contextualCount') > 0); } }); })(Drupal, Backbone); ; /** * @file * A Backbone View that provides the aural view of the edit mode toggle. */ (function ($, Drupal, Backbone, _) { 'use strict'; Drupal.contextualToolbar.AuralView = Backbone.View.extend(/** @lends Drupal.contextualToolbar.AuralView# */{ /** * Tracks whether the tabbing constraint announcement has been read once. * * @type {bool} */ announcedOnce: false, /** * Renders the aural view of the edit mode toggle (screen reader support). * * @constructs * * @augments Backbone.View * * @param {object} options * Options for the view. */ initialize: function (options) { this.options = options; this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'change:isViewing', this.manageTabbing); $(document).on('keyup', _.bind(this.onKeypress, this)); }, /** * @inheritdoc * * @return {Drupal.contextualToolbar.AuralView} * The current contextual toolbar aural view. */ render: function () { // Render the state. this.$el.find('button').attr('aria-pressed', !this.model.get('isViewing')); return this; }, /** * Limits tabbing to the contextual links and edit mode toolbar tab. */ manageTabbing: function () { var tabbingContext = this.model.get('tabbingContext'); // Always release an existing tabbing context. if (tabbingContext) { tabbingContext.release(); Drupal.announce(this.options.strings.tabbingReleased); } // Create a new tabbing context when edit mode is enabled. if (!this.model.get('isViewing')) { tabbingContext = Drupal.tabbingManager.constrain($('.contextual-toolbar-tab, .contextual')); this.model.set('tabbingContext', tabbingContext); this.announceTabbingConstraint(); this.announcedOnce = true; } }, /** * Announces the current tabbing constraint. */ announceTabbingConstraint: function () { var strings = this.options.strings; Drupal.announce(Drupal.formatString(strings.tabbingConstrained, { '@contextualsCount': Drupal.formatPlural(Drupal.contextual.collection.length, '@count contextual link', '@count contextual links') })); Drupal.announce(strings.pressEsc); }, /** * Responds to esc and tab key press events. * * @param {jQuery.Event} event * The keypress event. */ onKeypress: function (event) { // The first tab key press is tracked so that an annoucement about tabbing // constraints can be raised if edit mode is enabled when the page is // loaded. if (!this.announcedOnce && event.keyCode === 9 && !this.model.get('isViewing')) { this.announceTabbingConstraint(); // Set announce to true so that this conditional block won't run again. this.announcedOnce = true; } // Respond to the ESC key. Exit out of edit mode. if (event.keyCode === 27) { this.model.set('isViewing', true); } } }); })(jQuery, Drupal, Backbone, _); ; /** * @file * A Backbone View that provides the visual view of the edit mode toggle. */ (function (Drupal, Backbone) { 'use strict'; Drupal.contextualToolbar.VisualView = Backbone.View.extend(/** @lends Drupal.contextualToolbar.VisualView# */{ /** * Events for the Backbone view. * * @return {object} * A mapping of events to be used in the view. */ events: function () { // Prevents delay and simulated mouse events. var touchEndToClick = function (event) { event.preventDefault(); event.target.click(); }; return { click: function () { this.model.set('isViewing', !this.model.get('isViewing')); }, touchend: touchEndToClick }; }, /** * Renders the visual view of the edit mode toggle. * * Listens to mouse & touch and handles edit mode toggle interactions. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'change:isViewing', this.persist); }, /** * @inheritdoc * * @return {Drupal.contextualToolbar.VisualView} * The current contextual toolbar visual view. */ render: function () { // Render the visibility. this.$el.toggleClass('hidden', !this.model.get('isVisible')); // Render the state. this.$el.find('button').toggleClass('is-active', !this.model.get('isViewing')); return this; }, /** * Model change handler; persists the isViewing value to localStorage. * * `isViewing === true` is the default, so only stores in localStorage when * it's not the default value (i.e. false). * * @param {Drupal.contextualToolbar.StateModel} model * A {@link Drupal.contextualToolbar.StateModel} model. * @param {bool} isViewing * The value of the isViewing attribute in the model. */ persist: function (model, isViewing) { if (!isViewing) { localStorage.setItem('Drupal.contextualToolbar.isViewing', 'false'); } else { localStorage.removeItem('Drupal.contextualToolbar.isViewing'); } } }); })(Drupal, Backbone); ; /** * @file * Replaces the home link in toolbar with a back to site link. */ (function ($, Drupal, drupalSettings) { 'use strict'; var pathInfo = drupalSettings.path; var escapeAdminPath = sessionStorage.getItem('escapeAdminPath'); var windowLocation = window.location; // Saves the last non-administrative page in the browser to be able to link // back to it when browsing administrative pages. If there is a destination // parameter there is not need to save the current path because the page is // loaded within an existing "workflow". if (!pathInfo.currentPathIsAdmin && !/destination=/.test(windowLocation.search)) { sessionStorage.setItem('escapeAdminPath', windowLocation); } /** * Replaces the "Home" link with "Back to site" link. * * Back to site link points to the last non-administrative page the user * visited within the same browser tab. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the replacement functionality to the toolbar-escape-admin element. */ Drupal.behaviors.escapeAdmin = { attach: function () { var $toolbarEscape = $('[data-toolbar-escape-admin]').once('escapeAdmin'); if ($toolbarEscape.length && pathInfo.currentPathIsAdmin) { if (escapeAdminPath !== null) { $toolbarEscape.attr('href', escapeAdminPath); } else { $toolbarEscape.text(Drupal.t('Home')); } $toolbarEscape.closest('.toolbar-tab').removeClass('hidden'); } } }; })(jQuery, Drupal, drupalSettings); ;
/*! ReactInstantSearch 4.0.0-beta.5 | © Algolia, inc. | https://community.algolia.com/react-instantsearch/ */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["Core"] = factory(require("react")); else root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Core"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__) { 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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 433); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (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; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, 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. */ if (false) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(208)(); } /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEqual2 = __webpack_require__(104); var _isEqual3 = _interopRequireDefault(_isEqual2); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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 _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; }; }(); exports.default = createConnector; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); 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; } /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = (0, _has3.default)(connectorDesc, 'refine'); var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters'); var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata'); var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState'); var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { _inherits(Connector, _Component); function Connector(props, context) { _classCallCheck(this, Connector); var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais; var store = _context$ais.store; var widgetsManager = _context$ais.widgetsManager; var multiIndexContext = context.multiIndexContext; _this.state = { props: _this.getProvidedProps(props) }; _this.unsubscribe = store.subscribe(function () { _this.setState({ props: _this.getProvidedProps(_this.props) }); }); var getSearchParameters = hasSearchParameters ? function (searchParameters) { return connectorDesc.getSearchParameters.call(_this, searchParameters, _this.props, store.getState().widgets); } : null; var getMetadata = hasMetadata ? function (nextWidgetsState) { return connectorDesc.getMetadata.call(_this, _this.props, nextWidgetsState); } : null; var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) { return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState); } : null; if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget({ getSearchParameters: getSearchParameters, getMetadata: getMetadata, transitionState: transitionState, multiIndexContext: multiIndexContext }); } return _this; } _createClass(Connector, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!(0, _isEqual3.default)(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); //will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange((0, _utils.removeEmptyKey)(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props); } }, { key: 'render', value: function render() { var _this2 = this; if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues, searchForFacetValues: function searchForFacetValues(facetName, query) { if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.'); } _this2.searchForFacetValues(facetName, query); } } : {}; return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: _propTypes2.default.object.isRequired, multiIndexContext: _propTypes2.default.object }, _initialiseProps = function _initialiseProps() { var _this3 = this; this.getProvidedProps = function (props) { var store = _this3.context.ais.store; var _store$getState = store.getState(); var results = _store$getState.results; var searching = _store$getState.searching; var error = _store$getState.error; var widgets = _store$getState.widgets; var metadata = _store$getState.metadata; var resultsFacetValues = _store$getState.resultsFacetValues; var searchState = { results: results, searching: searching, error: error }; return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args)); }; }, _temp; }; } /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(78); /** 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) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }), /* 5 */, /* 6 */ /***/ (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; /***/ }), /* 7 */ /***/ (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; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), getRawTag = __webpack_require__(157), objectToString = __webpack_require__(184); /** `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; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(88), baseKeys = __webpack_require__(76), isArrayLike = __webpack_require__(11); /** * 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; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(136), getValue = __webpack_require__(159); /** * 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; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isLength = __webpack_require__(47); /** * 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; /***/ }), /* 12 */ /***/ (function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }), /* 13 */, /* 14 */, /* 15 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { var baseKeys = __webpack_require__(76), getTag = __webpack_require__(56), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isArrayLike = __webpack_require__(11), isBuffer = __webpack_require__(26), isPrototype = __webpack_require__(37), isTypedArray = __webpack_require__(36); /** `Object#toString` result references. */ var mapTag = '[object Map]', setTag = '[object Set]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } module.exports = isEmpty; /***/ }), /* 17 */, /* 18 */ /***/ (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; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObject = __webpack_require__(6); /** `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; /***/ }), /* 20 */, /* 21 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isKey = __webpack_require__(72), stringToPath = __webpack_require__(196), toString = __webpack_require__(75); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }), /* 22 */, /* 23 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }), /* 24 */, /* 25 */ /***/ (function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(134), isObjectLike = __webpack_require__(7); /** 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; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3), stubFalse = __webpack_require__(206); /** 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__(55)(module))) /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(169), listCacheDelete = __webpack_require__(170), listCacheGet = __webpack_require__(171), listCacheHas = __webpack_require__(172), listCacheSet = __webpack_require__(173); /** * 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; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18); /** * 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; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(166); /** * 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; /***/ }), /* 31 */ /***/ (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; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }), /* 33 */, /* 34 */, /* 35 */, /* 36 */ /***/ (function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(137), baseUnary = __webpack_require__(44), nodeUtil = __webpack_require__(183); /* 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; /***/ }), /* 37 */ /***/ (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; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(174), mapCacheDelete = __webpack_require__(175), mapCacheGet = __webpack_require__(176), mapCacheHas = __webpack_require__(177), mapCacheSet = __webpack_require__(178); /** * 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; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), stackClear = __webpack_require__(191), stackDelete = __webpack_require__(192), stackGet = __webpack_require__(193), stackHas = __webpack_require__(194), stackSet = __webpack_require__(195); /** * 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; /***/ }), /* 41 */, /* 42 */, /* 43 */, /* 44 */ /***/ (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; /***/ }), /* 45 */, /* 46 */, /* 47 */ /***/ (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; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), getPrototype = __webpack_require__(70), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** 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 infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }), /* 49 */, /* 50 */, /* 51 */, /* 52 */, /* 53 */, /* 54 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 55 */ /***/ (function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if(!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { var DataView = __webpack_require__(122), Map = __webpack_require__(38), Promise = __webpack_require__(125), Set = __webpack_require__(126), WeakMap = __webpack_require__(84), baseGetTag = __webpack_require__(8), toSource = __webpack_require__(80); /** `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; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(133), hasPath = __webpack_require__(97); /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } module.exports = has; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defer = undefined; var _isPlainObject2 = __webpack_require__(48); var _isPlainObject3 = _interopRequireDefault(_isPlainObject2); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); exports.shallowEqual = shallowEqual; exports.isSpecialClick = isSpecialClick; exports.capitalize = capitalize; exports.assertFacetDefined = assertFacetDefined; exports.getDisplayName = getDisplayName; exports.removeEmptyKey = removeEmptyKey; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } 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 hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); } function capitalize(key) { return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1); } function assertFacetDefined(searchParameters, searchResults, facet) { var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet); var wasReceived = Boolean(searchResults.getFacetByName(facet)); if (searchResults.nbHits > 0 && wasRequested && !wasReceived) { // eslint-disable-next-line no-console console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.'); } } function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; } var resolved = Promise.resolve(); var defer = exports.defer = function defer(f) { resolved.then(f); }; function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if ((0, _isEmpty3.default)(value) && (0, _isPlainObject3.default)(value)) { delete obj[key]; } else if ((0, _isPlainObject3.default)(value)) { removeEmptyKey(value); } }); return obj; } /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(39), setCacheAdd = __webpack_require__(186), setCacheHas = __webpack_require__(187); /** * * 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; /***/ }), /* 60 */, /* 61 */ /***/ (function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }), /* 62 */, /* 63 */, /* 64 */, /* 65 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(135), isObjectLike = __webpack_require__(7); /** * 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 {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), arrayMap = __webpack_require__(12), isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }), /* 67 */ /***/ (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; /***/ }), /* 68 */, /* 69 */, /* 70 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(86), stubArray = __webpack_require__(107); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }), /* 73 */, /* 74 */, /* 75 */ /***/ (function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(66); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(37), nativeKeys = __webpack_require__(182); /** 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; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arraySome = __webpack_require__(128), cacheHas = __webpack_require__(67); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_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 & COMPARE_UNORDERED_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, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 79 */ /***/ (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; /***/ }), /* 80 */ /***/ (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; /***/ }), /* 81 */, /* 82 */, /* 83 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }), /* 85 */, /* 86 */ /***/ (function(module, exports) { /** * A specialized version of `_.filter` 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 {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }), /* 87 */, /* 88 */ /***/ (function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(142), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isIndex = __webpack_require__(31), isTypedArray = __webpack_require__(36); /** 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; /***/ }), /* 89 */, /* 90 */, /* 91 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), isArray = __webpack_require__(0); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }), /* 92 */, /* 93 */, /* 94 */, /* 95 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(91), getSymbols = __webpack_require__(71), keys = __webpack_require__(9); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }), /* 96 */, /* 97 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isIndex = __webpack_require__(31), isLength = __webpack_require__(47), toKey = __webpack_require__(23); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; /***/ }), /* 98 */ /***/ (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; /***/ }), /* 99 */ /***/ (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; /***/ }), /* 100 */, /* 101 */, /* 102 */, /* 103 */, /* 104 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(65); /** * 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 compared by strict equality, i.e. `===`. * * @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; /***/ }), /* 105 */, /* 106 */, /* 107 */ /***/ (function(module, exports) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }), /* 108 */, /* 109 */, /* 110 */, /* 111 */, /* 112 */, /* 113 */, /* 114 */, /* 115 */, /* 116 */, /* 117 */, /* 118 */, /* 119 */, /* 120 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, 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. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, 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. * */ /** * 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. */ var validateFormat = function validateFormat(format) {}; if (false) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); 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; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(160), hashDelete = __webpack_require__(161), hashGet = __webpack_require__(162), hashHas = __webpack_require__(163), hashSet = __webpack_require__(164); /** * 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; /***/ }), /* 124 */, /* 125 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }), /* 127 */, /* 128 */ /***/ (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; /***/ }), /* 129 */, /* 130 */, /* 131 */, /* 132 */, /* 133 */ /***/ (function(module, exports) { /** 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 `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } module.exports = baseHas; /***/ }), /* 134 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `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; /***/ }), /* 135 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(40), equalArrays = __webpack_require__(77), equalByTag = __webpack_require__(153), equalObjects = __webpack_require__(154), getTag = __webpack_require__(56), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isTypedArray = __webpack_require__(36); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; 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, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_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, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isMasked = __webpack_require__(167), isObject = __webpack_require__(6), toSource = __webpack_require__(80); /** * 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; /***/ }), /* 137 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isLength = __webpack_require__(47), isObjectLike = __webpack_require__(7); /** `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; /***/ }), /* 138 */, /* 139 */, /* 140 */, /* 141 */, /* 142 */ /***/ (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; /***/ }), /* 143 */, /* 144 */, /* 145 */, /* 146 */, /* 147 */, /* 148 */ /***/ (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; /***/ }), /* 149 */, /* 150 */, /* 151 */, /* 152 */, /* 153 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), Uint8Array = __webpack_require__(83), eq = __webpack_require__(18), equalArrays = __webpack_require__(77), mapToArray = __webpack_require__(98), setToArray = __webpack_require__(99); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @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, bitmask, customizer, equalFunc, 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 & COMPARE_PARTIAL_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 |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(95); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(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, bitmask, customizer, 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; /***/ }), /* 155 */, /* 156 */, /* 157 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** 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; /***/ }), /* 158 */, /* 159 */ /***/ (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; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** * 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; /***/ }), /* 161 */ /***/ (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; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 165 */, /* 166 */ /***/ (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; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(148); /** 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; /***/ }), /* 168 */, /* 169 */ /***/ (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; /***/ }), /* 170 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** 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; /***/ }), /* 171 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * 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; /***/ }), /* 172 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * 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; /***/ }), /* 173 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * 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; /***/ }), /* 174 */ /***/ (function(module, exports, __webpack_require__) { var Hash = __webpack_require__(123), ListCache = __webpack_require__(28), Map = __webpack_require__(38); /** * 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; /***/ }), /* 175 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 179 */, /* 180 */ /***/ (function(module, exports, __webpack_require__) { var memoize = __webpack_require__(205); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }), /* 181 */, /* 182 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(78); /** 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 && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }), /* 184 */ /***/ (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; /***/ }), /* 185 */, /* 186 */ /***/ (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; /***/ }), /* 187 */ /***/ (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; /***/ }), /* 188 */, /* 189 */, /* 190 */, /* 191 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28); /** * 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; /***/ }), /* 192 */ /***/ (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; /***/ }), /* 193 */ /***/ (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; /***/ }), /* 194 */ /***/ (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; /***/ }), /* 195 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), Map = __webpack_require__(38), MapCache = __webpack_require__(39); /** 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; /***/ }), /* 196 */ /***/ (function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(180); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }), /* 197 */, /* 198 */, /* 199 */, /* 200 */, /* 201 */, /* 202 */, /* 203 */, /* 204 */, /* 205 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(39); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }), /* 206 */ /***/ (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; /***/ }), /* 207 */, /* 208 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2013-present, 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. */ var emptyFunction = __webpack_require__(120); var invariant = __webpack_require__(121); module.exports = function() { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); }; shim.isRequired = shim; function getShim() { return shim; }; var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 209 */, /* 210 */, /* 211 */, /* 212 */, /* 213 */, /* 214 */, /* 215 */, /* 216 */, /* 217 */, /* 218 */, /* 219 */, /* 220 */, /* 221 */, /* 222 */, /* 223 */, /* 224 */, /* 225 */, /* 226 */, /* 227 */, /* 228 */, /* 229 */, /* 230 */, /* 231 */, /* 232 */, /* 233 */, /* 234 */, /* 235 */, /* 236 */, /* 237 */, /* 238 */, /* 239 */, /* 240 */, /* 241 */, /* 242 */, /* 243 */, /* 244 */, /* 245 */, /* 246 */, /* 247 */, /* 248 */, /* 249 */, /* 250 */, /* 251 */, /* 252 */, /* 253 */, /* 254 */, /* 255 */, /* 256 */, /* 257 */, /* 258 */, /* 259 */, /* 260 */, /* 261 */, /* 262 */, /* 263 */, /* 264 */, /* 265 */, /* 266 */, /* 267 */, /* 268 */, /* 269 */, /* 270 */, /* 271 */, /* 272 */, /* 273 */, /* 274 */, /* 275 */, /* 276 */, /* 277 */, /* 278 */, /* 279 */, /* 280 */, /* 281 */, /* 282 */, /* 283 */, /* 284 */, /* 285 */, /* 286 */, /* 287 */, /* 288 */, /* 289 */, /* 290 */, /* 291 */, /* 292 */, /* 293 */, /* 294 */, /* 295 */, /* 296 */, /* 297 */, /* 298 */, /* 299 */, /* 300 */, /* 301 */, /* 302 */, /* 303 */, /* 304 */, /* 305 */, /* 306 */, /* 307 */, /* 308 */, /* 309 */, /* 310 */, /* 311 */, /* 312 */, /* 313 */, /* 314 */, /* 315 */, /* 316 */, /* 317 */, /* 318 */, /* 319 */, /* 320 */, /* 321 */, /* 322 */, /* 323 */, /* 324 */, /* 325 */, /* 326 */, /* 327 */, /* 328 */, /* 329 */, /* 330 */, /* 331 */, /* 332 */, /* 333 */, /* 334 */, /* 335 */, /* 336 */, /* 337 */, /* 338 */, /* 339 */, /* 340 */, /* 341 */, /* 342 */, /* 343 */, /* 344 */, /* 345 */, /* 346 */, /* 347 */, /* 348 */, /* 349 */, /* 350 */, /* 351 */, /* 352 */, /* 353 */, /* 354 */, /* 355 */, /* 356 */, /* 357 */, /* 358 */, /* 359 */, /* 360 */, /* 361 */, /* 362 */, /* 363 */, /* 364 */, /* 365 */, /* 366 */, /* 367 */, /* 368 */, /* 369 */, /* 370 */, /* 371 */, /* 372 */, /* 373 */, /* 374 */, /* 375 */, /* 376 */, /* 377 */, /* 378 */, /* 379 */, /* 380 */, /* 381 */, /* 382 */, /* 383 */, /* 384 */, /* 385 */, /* 386 */, /* 387 */, /* 388 */, /* 389 */, /* 390 */, /* 391 */, /* 392 */, /* 393 */, /* 394 */, /* 395 */, /* 396 */, /* 397 */, /* 398 */, /* 399 */, /* 400 */, /* 401 */, /* 402 */, /* 403 */, /* 404 */, /* 405 */, /* 406 */, /* 407 */, /* 408 */, /* 409 */, /* 410 */, /* 411 */, /* 412 */, /* 413 */, /* 414 */, /* 415 */, /* 416 */, /* 417 */, /* 418 */, /* 419 */, /* 420 */, /* 421 */, /* 422 */, /* 423 */, /* 424 */, /* 425 */, /* 426 */, /* 427 */, /* 428 */, /* 429 */, /* 430 */, /* 431 */, /* 432 */, /* 433 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); Object.defineProperty(exports, 'createConnector', { enumerable: true, get: function get() { return _interopRequireDefault(_createConnector).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }) /******/ ]); }); //# sourceMappingURL=Core.js.map
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; import { connect } from 'react-redux'; import { increase, decrease, reset } from './actions'; class Home extends Component { _onPressReset() { this.props.dispatch(reset()); } _onPressInc() { this.props.dispatch(increase()); } _onPressDec() { this.props.dispatch(decrease()); } render() { return ( <View style={styles.container}> <Text style={styles.counter}>{this.props.counter.count}</Text> <TouchableOpacity style={styles.reset} onPress={()=>this._onPressReset()}> <Text>归零</Text> </TouchableOpacity> <TouchableOpacity style={styles.start} onPress={()=>this._onPressInc()}> <Text>加1</Text> </TouchableOpacity> <TouchableOpacity style={styles.stop} onPress={()=>this._onPressDec()}> <Text>减1</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }, counter: { fontSize: 50, marginBottom: 70 }, reset: { margin: 10, backgroundColor: 'yellow' }, start: { margin: 10, backgroundColor: 'yellow' }, stop: { margin: 10, backgroundColor: 'yellow' } }) const mapStateToProps = state => ({ counter: state.counter }) export default connect(mapStateToProps)(Home);
/*! * @overview Ember Data * @copyright Copyright 2011-2014 Tilde Inc. and contributors. * Portions Copyright 2011 LivingSocial Inc. * @license Licensed under MIT license (see license.js) * @version 1.0.0-beta.5 */ (function() { var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; var mod, deps, callback, reified , exports; mod = registry[name]; if (!mod) { throw new Error("Module '" + name + "' not found."); } deps = mod.deps; callback = mod.callback; reified = []; exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(deps[i])); } } var value = callback.apply(this, reified); return seen[name] = exports || value; }; })(); (function() { /** @module ember-data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ var DS; if ('undefined' === typeof DS) { /** @property VERSION @type String @default '1.0.0-beta.5' @static */ DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.5' }); if ('undefined' !== typeof window) { window.DS = DS; } if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } } })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; // Simple dispatcher to support overriding the aliased // method in subclasses. function aliasMethod(methodName) { return function() { return this[methodName].apply(this, arguments); }; } /** In Ember Data a Serializer is used to serialize and deserialize records when they are transfered in and out of an external source. This process involves normalizing property names, transforming attribute values and serializeing relationships. For maximum performance Ember Data recomends you use the [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. @class JSONSerializer @namespace DS */ DS.JSONSerializer = Ember.Object.extend({ /** The primaryKey is used when serializing and deserializing data. Ember Data always uses the `id` propery to store the id of the record. The external source may not always follow this convention. In these cases it is usesful to override the primaryKey property to match the primaryKey of your external store. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {subclass of DS.Model} type @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(type, data) { type.eachTransformedAttribute(function(key, type) { var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ normalize: function(type, hash) { var fields = Ember.get(type, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { if (!hash) { return hash; } this.applyTransforms(type, hash); return hash; }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```javascript App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {subclass of DS.Model} record @param {Object} options @return {Object} json */ serialize: function(record, options) { var json = {}; if (options && options.includeId) { var id = get(record, 'id'); if (id) { json[get(this, 'primaryKey')] = id; } } record.eachAttribute(function(key, attribute) { this.serializeAttribute(record, json, key, attribute); }, this); record.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(record, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(record, json, relationship); } }, this); return json; }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all you attributes were always serialized as properties on an `attributes` object you could write: ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serializeAttribute: function(record, json, key, attributes) { json.attributes = json.attributes || {}; this._super(record, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Model} record @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function(record, json, key, attribute) { var attrs = get(this, 'attrs'); var value = get(record, key), type = attribute.type; if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key); json[key] = value; }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; if (isNone(belongsTo)) { json[key] = belongsTo; } else { json[key] = get(belongsTo, 'id'); } if (relationship.options.polymorphic) { this.serializePolymorphicType(record, json, relationship); } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var key = relationship.key; var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[key] = get(record, key).mapBy('id'); // TODO support for polymorphic manyToNone and manyToMany relationships } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{polymorphic: true}` is pass as the second argument to the `DS.belongsTo` function. Example ```javascript App.CommentSerializer = DS.JSONSerializer.extend({ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "_type"] = belongsTo.constructor.typeKey; } }); ``` @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method deletegates to a more specific extract method based on the `requestType`. Example ```javascript var get = Ember.get; socket.on('message', function(message) { var modelName = message.model; var data = message.data; var type = store.modelFor(modelName); var serializer = store.serializerFor(type.typeKey); var record = serializer.extract(store, type, data, get(data, 'id'), 'single'); store.push(modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindAll: aliasMethod('extractArray'), /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindQuery: aliasMethod('extractArray'), /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindMany: aliasMethod('extractArray'), /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindHasMany: aliasMethod('extractArray'), /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Store#createRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractCreateRecord: aliasMethod('extractSave'), /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Store#update`. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractUpdateRecord: aliasMethod('extractSave'), /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Store#deleteRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractDeleteRecord: aliasMethod('extractSave'), /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFind: aliasMethod('extractSingle'), /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFindBelongsTo: aliasMethod('extractSingle'), /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSave: aliasMethod('extractSingle'), /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractSingle: function(store, type, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, type, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSingle: function(store, type, payload) { return this.normalize(type, payload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, type, payload) { return payload.map(function(json) { return this.extractSingle(json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractArray: function(store, type, payload) { return this.normalize(type, payload); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractMeta: function(store, type, payload) { if (payload && payload._pagination) { store.metaForType(type, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload */ extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.metaForType(type, payload.meta); delete payload.meta; } }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```javascript App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @return {String} normalized key */ /** `keyForRelationship` can be used to define a custom key when serializeing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship type @return {String} normalized key */ // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function(attributeType, skipAssertion) { var transform = this.container.lookup('transform:' + attributeType); return transform; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore, DS = window.DS ; /** Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ DS.DebugAdapter = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== DS.Model && DS.Model.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this; get(type, 'attributes').forEach(function(name, meta) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this, count = 0, columnValues = { id: get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = [], keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(), self = this, keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); })(); (function() { /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```javascript App.RawTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); ``` Usage ```javascript var attr = DS.attr; App.Requirement = DS.Model.extend({ name: attr('string'), optionsArray: attr('raw') }); ``` @class Transform @namespace DS */ DS.Transform = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @return The serialized value */ serialize: Ember.required(), /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @return The deserialized value */ deserialize: Ember.required() }); })(); (function() { /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ DS.BooleanTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); })(); (function() { /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ DS.DateTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var pad = function(num) { return num < 10 ? "0"+num : ""+num; }; var utcYear = date.getUTCFullYear(), utcMonth = date.getUTCMonth(), utcDayOfMonth = date.getUTCDate(), utcDay = date.getUTCDay(), utcHours = date.getUTCHours(), utcMinutes = date.getUTCMinutes(), utcSeconds = date.getUTCSeconds(); var dayOfWeek = days[utcDay]; var dayOfMonth = pad(utcDayOfMonth); var month = months[utcMonth]; return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " + pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT"; } else { return null; } } }); })(); (function() { var empty = Ember.isEmpty; /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ DS.NumberTransform = DS.Transform.extend({ deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }); })(); (function() { var none = Ember.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ DS.StringTransform = DS.Transform.extend({ deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }); })(); (function() { })(); (function() { /** @module ember-data */ var set = Ember.set; /* This code registers an injection for Ember.Application. If an Ember.js developer defines a subclass of DS.Store on their application, this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.Store = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.Store` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "store", initialize: function(container, application) { application.register('store:main', application.Store || DS.Store); application.register('serializer:_default', DS.JSONSerializer); application.register('serializer:_rest', DS.RESTSerializer); application.register('adapter:_rest', DS.RESTAdapter); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); } }); Application.initializer({ name: "transforms", before: "store", initialize: function(container, application) { application.register('transform:boolean', DS.BooleanTransform); application.register('transform:date', DS.DateTransform); application.register('transform:number', DS.NumberTransform); application.register('transform:string', DS.StringTransform); } }); Application.initializer({ name: "dataAdapter", before: "store", initialize: function(container, application) { application.register('dataAdapter:main', DS.DebugAdapter); } }); Application.initializer({ name: "injectStore", before: "store", initialize: function(container, application) { application.inject('controller', 'store', 'store:main'); application.inject('route', 'store', 'store:main'); application.inject('serializer', 'store', 'store:main'); application.inject('dataAdapter', 'store', 'store:main'); } }); }); })(); (function() { /** @module ember-data */ /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; /** @method parse @param date */ Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all(App.Person); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all(App.Person); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function(index) { var content = get(this, 'content'); return content.objectAt(index); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.all(App.Person); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @method update */ update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'), type = get(this, 'type'); store.fetchAll(type, this); }, /** Adds a record to the `RecordArray`. @method addRecord @private @param {DS.Model} record */ addRecord: function(record) { get(this, 'content').addObject(record); }, /** Removes a record to the `RecordArray`. @method removeRecord @private @param {DS.Model} record */ removeRecord: function(record) { get(this, 'content').removeObject(record); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.all(App.Message); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return Ember.A(array); }, null, "DS: RecordArray#save apply Ember.NativeArray"); return DS.PromiseArray.create({ promise: promise }); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ DS.FilteredRecordArray = DS.RecordArray.extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.all('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ updateFilter: Ember.observer(function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, 'filterFunction') }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function(data) { var store = get(this, 'store'), type = get(this, 'type'), records = store.pushMany(type, data), meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: meta }); // TODO: does triggering didLoad event should be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.EnumerableUtils.map; /** A `ManyArray` is a `RecordArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray */ DS.ManyArray = DS.RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** The property name of the relationship @property {String} name @private */ name: null, /** The record to which this relationship belongs. @property {DS.Model} owner @private */ owner: null, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, // LOADING STATE isLoaded: false, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method fetch @private */ fetch: function() { var records = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'), resolver = Ember.RSVP.defer("DS: ManyArray#fetch " + get(this, 'type')); var unloadedRecords = records.filterProperty('isEmpty', true); store.fetchMany(unloadedRecords, owner, resolver); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = map(added, function(record) { return record; }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { Ember.run.once(this, 'fetch'); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(function(change) { change.sync(); }); this._changesToSync.clear(); } }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function(hash) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; record = store.createRecord.call(store, type, hash); this.pushObject(record); return record; } }); })(); (function() { /** @module ember-data */ })(); (function() { /*globals Ember*/ /*jshint eqnull:true*/ /** @module ember-data */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var indexOf = Ember.EnumerableUtils.indexOf; var map = Ember.EnumerableUtils.map; var resolve = Ember.RSVP.resolve; var copy = Ember.copy; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. var coerceId = function(id) { return id == null ? null : id+''; }; /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```javascript MyApp.Store = DS.Store.extend(); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `find()` method: ```javascript var person = store.find('person', 123); ``` If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: ```javascript var person = store.find(App.Person, 123); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```javascript MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. @class Store @namespace DS @extends Ember.Object */ DS.Store = Ember.Object.extend({ /** @method init @private */ init: function() { // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = DS.RecordArrayManager.create({ store: this }); this._relationshipChanges = {}; this._pendingSave = []; }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '_rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.serializerFor(record.constructor.typeKey).serialize(record, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @returns DS.Adapter */ defaultAdapter: Ember.computed('adapter', function() { var adapter = get(this, 'adapter'); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:_rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container }); } return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @returns {DS.Model} record */ createRecord: function(type, properties) { type = this.modelFor(type); properties = copy(properties) || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(type); } // Coerce ID to a string properties.id = coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} type @returns {String} if the adapter can generate one, an ID */ _generateId: function(type) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deletedRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- To find all records for a type, call `find` with no additional parameters: ```javascript store.find('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. --- To find a record by a query, call `find` with a hash as the second parameter: ```javascript store.find(App.Person, { page: 1 }); ``` This will ask the adapter's `findQuery` method to find the records for the query, and return a promise that will be resolved once the server responds. @method find @param {String or subclass of DS.Model} type @param {Object|String|Integer|null} id @return {Promise} promise */ find: function(type, id) { if (id === undefined) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id)); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Promise} promise */ findById: function(type, id) { type = this.modelFor(type); var record = this.recordForId(type, id); var promise = this.fetchRecord(record) || resolve(record, "DS: Store#findById " + type + " with id: " + id); return promiseObject(promise); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} type @param {Array} ids @returns {Promise} promise */ findByIds: function(type, ids) { var store = this; var promiseLabel = "DS: Store#findByIds " + type; return promiseArray(Ember.RSVP.all(map(ids, function(id) { return store.findById(type, id); })).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete")); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @returns {Promise} promise */ fetchRecord: function(record) { if (isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } if (!get(record, 'isEmpty')) { return null; } var type = record.constructor, id = get(record, 'id'); var adapter = this.adapterFor(type); var promise = _find(adapter, this, type, id); record.loadingData(promise); return promise; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it's available. Otherwise, it will return null. ```js var post = store.getById('post', 1); ``` @method getById @param {String or subclass of DS.Model} type @param {String|Integer} id @param {DS.Model} record */ getById: function(type, id) { if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @return {Promise} promise */ reloadRecord: function(record) { var type = record.constructor, adapter = this.adapterFor(type), id = get(record, 'id'); return _find(adapter, this, type, id); }, /** This method takes a list of records, groups the records by type, converts the records into IDs, and then invokes the adapter's `findMany` method. The records are grouped by type to invoke `findMany` on adapters for each unique type in records. It is used both by a brand new relationship (via the `findMany` method) or when the data underlying an existing relationship changes. @method fetchMany @private @param {Array} records @param {DS.Model} owner @param {Resolver} resolver */ fetchMany: function(records, owner, resolver) { if (!records.length) { return; } // Group By Type var recordsByTypeMap = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); forEach(records, function(record) { recordsByTypeMap.get(record.constructor).push(record); }); forEach(recordsByTypeMap, function(type, records) { var ids = records.mapProperty('id'), adapter = this.adapterFor(type); resolver.resolve(_findMany(adapter, this, type, ids, owner)); }, this); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String or subclass of DS.Model} type @param {String|Integer} id @returns {Boolean} */ hasRecordForId: function(type, id) { id = coerceId(id); type = this.modelFor(type); return !!this.typeMapFor(type).idToRecord[id]; }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String or subclass of DS.Model} type @param {String|Integer} id @returns {DS.Model} record */ recordForId: function(type, id) { type = this.modelFor(type); id = coerceId(id); var record = this.typeMapFor(type).idToRecord[id]; if (!record) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array} records @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} records */ findMany: function(owner, records, type, resolver) { type = this.modelFor(type); records = Ember.A(records); var unloadedRecords = records.filterProperty('isEmpty', true), manyArray = this.recordArrayManager.createManyArray(type, records); forEach(unloadedRecords, function(record) { record.loadingData(); }); manyArray.loadingRecordsCount = unloadedRecords.length; if (unloadedRecords.length) { forEach(unloadedRecords, function(record) { this.recordArrayManager.registerWaitingRecordArray(record, manyArray); }, this); this.fetchMany(unloadedRecords, owner, resolver); } else { if (resolver) { resolver.resolve(); } manyArray.set('isLoaded', true); Ember.run.once(manyArray, 'trigger', 'didLoad'); } return manyArray; }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} */ findHasMany: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([])); resolver.resolve(_findHasMany(adapter, this, owner, link, relationship)); return records; }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @param {Resolver} resolver */ findBelongsTo: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); resolver.resolve(_findBelongsTo(adapter, this, owner, link, relationship)); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ findQuery: function(type, query) { type = this.modelFor(type); var array = this.recordArrayManager .createAdapterPopulatedRecordArray(type, query); var adapter = this.adapterFor(type), promiseLabel = "DS: Store#findQuery " + type, resolver = Ember.RSVP.defer(promiseLabel); resolver.resolve(_findQuery(adapter, this, type, query, array)); return promiseArray(resolver.promise); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {String or subclass of DS.Model} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(type) { type = this.modelFor(type); return this.fetchAll(type, this.all(type)); }, /** @method fetchAll @private @param {DS.Model} type @param {DS.RecordArray} array @returns {Promise} promise */ fetchAll: function(type, array) { var adapter = this.adapterFor(type), sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); return promiseArray(_findAll(adapter, this, type, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. Example ```javascript var local_posts = store.all(App.Post); ``` @method all @param {String or subclass of DS.Model} type @return {DS.RecordArray} */ all: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = this.recordArrayManager.createRecordArray(type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. ```javascript store.unloadAll(App.Post); ``` @method unloadAll @param {String or subclass of DS.Model} type */ unloadAll: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), records = typeMap.records, record; while(record = records.pop()) { record.unloadRecord(); } typeMap.findAllCache = null; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function. Example ```javascript store.filter(App.Post, {unread: true}, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPosts.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String or subclass of DS.Model} type @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function(type, query, filter) { var promise; // allow an optional server query if (arguments.length === 3) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); var array = this.recordArrayManager .createFilteredRecordArray(type, filter); promise = promise || resolve(array); return promiseArray(promise.then(function() { return array; }, null, "DS: Store#filter of " + type)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded(App.Post, 1); // false store.find(App.Post, 1).then(function() { store.recordIsLoaded(App.Post, 1); // true }); ``` @method recordIsLoaded @param {String or subclass of DS.Model} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String or subclass of DS.Model} type @return {object} */ metadataFor: function(type) { type = this.modelFor(type); return this.typeMapFor(type).metadata; }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {DS.Model} record */ dataWasUpdated: function(type, record) { this.recordArrayManager.recordDidChange(record); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; forEach(pending, function(tuple) { var record = tuple[0], resolver = tuple[1], adapter = this.adapterFor(record.constructor), operation; if (get(record, 'isNew')) { operation = 'createRecord'; } else if (get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, this, operation, record)); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records data = normalizeRelationships(this, record.constructor, data, record); this.updateId(record, data); } record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = get(record, 'id'), id = coerceId(data.id); this.typeMapFor(record.constructor).idToRecord[id] = record; set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param type @return {Object} typeMap */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'), guid = Ember.guidFor(type), typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: {}, records: [], metadata: {} }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {String or subclass of DS.Model} type @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ _load: function(type, data, partial) { var id = coerceId(data.id), record = this.recordForId(type, id); record.setupData(data, partial); this.recordArrayManager.recordDidChange(record); return record; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String or subclass of DS.Model} key @returns {subclass of DS.Model} */ modelFor: function(key) { var factory; if (typeof key === 'string') { var normalizedKey = this.container.normalize('model:' + key); factory = this.container.lookupFactory(normalizedKey); if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); } factory.typeKey = normalizedKey.split(':', 2)[1]; } else { // A factory already supplied. factory = key; } factory.store = this; return factory; }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String or subclass of DS.Model} type @param {Object} data @returns {DS.Model} the record that was created or updated. */ push: function(type, data, _partial) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. type = this.modelFor(type); // normalize relationship IDs into records data = normalizeRelationships(this, type, data); this._load(type, data, _partial); return this.recordForId(type, data.id); }, /** Push some raw data into the store. The data will be automatically deserialized using the serializer for the `type` param. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload('post', pushData); ``` @method pushPayload @param {String} type @param {Object} payload @return {DS.Model} the record that was created or updated. */ pushPayload: function (type, payload) { var serializer; if (!payload) { payload = type; serializer = defaultSerializer(this.container); } else { serializer = this.serializerFor(type); } serializer.pushPayload(this, payload); }, update: function(type, data) { return this.push(type, data, true); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String or subclass of DS.Model} type @param {Array} datas @return {Array} */ pushMany: function(type, datas) { return map(datas, function(data) { return this.push(type, data); }, this); }, /** If you have some metadata to set for a type you can call `metaForType`. @method metaForType @param {String or subclass of DS.Model} type @param {Object} metadata */ metaForType: function(type, metadata) { type = this.modelFor(type); Ember.merge(this.typeMapFor(type).metadata, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @returns {DS.Model} record */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type), idToRecord = typeMap.idToRecord; // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method dematerializeRecord @private @param {DS.Model} record */ dematerializeRecord: function(record) { var type = record.constructor, typeMap = this.typeMapFor(type), id = get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) { var clientId = childRecord.clientId, parentClientId = parentRecord ? parentRecord : parentRecord; var key = childKey + parentKey; var changes = this._relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) { var clientId = clientRecord.clientId, parentClientId = parentRecord ? parentRecord.clientId : parentRecord; var changes = this._relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangePairsFor: function(record){ var toReturn = []; if( !record ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this._relationshipChanges[record.clientId]; for (var objKey in changesObject){ if(changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if(changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns the adapter for a given type. @method adapterFor @private @param {subclass of DS.Model} type @returns DS.Adapter */ adapterFor: function(type) { var container = this.container, adapter; if (container) { adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application'); } return adapter || get(this, 'defaultAdapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). If no `App.ApplicationSerializer` is found, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String} type the record to serialize @return {DS.Serializer} */ serializerFor: function(type) { type = this.modelFor(type); var adapter = this.adapterFor(type); return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer); } }); function normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { // A link (usually a URL) was already provided in // normalized form if (data.links && data.links[key]) { if (record && relationship.options.async) { record._relationships[key] = null; } return; } var kind = relationship.kind, value = data[key]; if (value == null) { return; } if (kind === 'belongsTo') { deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { deserializeRecordIds(store, data, key, relationship, value); addUnsavedRecords(record, key, value); } }); return data; } function deserializeRecordId(store, data, key, relationship, id) { if (isNone(id) || id instanceof DS.Model) { return; } var type; if (typeof id === 'number' || typeof id === 'string') { type = typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // polymorphic data[key] = store.recordForId(id.type, id.id); } } function typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function deserializeRecordIds(store, data, key, relationship, ids) { for (var i=0, l=ids.length; i<l; i++) { deserializeRecordId(store, ids, i, relationship, ids[i]); } } // If there are any unsaved records that are in a hasMany they won't be // in the payload, so add them back in manually. function addUnsavedRecords(record, key, data) { if(record) { data.pushObjects(record.get(key).filterBy('isNew')); } } // Delegation to the adapter and promise management /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ DS.PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved the the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ DS.PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); function promiseObject(promise) { return DS.PromiseObject.create({ promise: promise }); } function promiseArray(promise) { return DS.PromiseArray.create({ promise: promise }); } function isThenable(object) { return object && typeof object.then === 'function'; } function serializerFor(container, type, defaultSerializer) { return container.lookup('serializer:'+type) || container.lookup('serializer:application') || container.lookup('serializer:' + defaultSerializer) || container.lookup('serializer:_default'); } function defaultSerializer(container) { return container.lookup('serializer:application') || container.lookup('serializer:_default'); } function serializerForAdapter(adapter, type) { var serializer = adapter.serializer, defaultSerializer = adapter.defaultSerializer, container = adapter.container; if (container && serializer === undefined) { serializer = serializerFor(container, type.typeKey, defaultSerializer); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } function _find(adapter, store, type, id) { var promise = adapter.find(store, type, id), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#find of " + type + " with id: " + id).then(function(payload) { payload = serializer.extract(store, type, payload, id, 'find'); return store.push(type, payload); }, function(error) { var record = store.getById(type, id); record.notFound(); throw error; }, "DS: Extract payload of '" + type + "'"); } function _findMany(adapter, store, type, ids, owner) { var promise = adapter.findMany(store, type, ids, owner), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findMany of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findMany'); store.pushMany(type, payload); }, null, "DS: Extract payload of " + type); } function _findHasMany(adapter, store, record, link, relationship) { var promise = adapter.findHasMany(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise, "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findHasMany'); var records = store.pushMany(relationship.type, payload); record.updateHasMany(relationship.key, records); }, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, record, link, relationship) { var promise = adapter.findBelongsTo(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise, "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findBelongsTo'); var record = store.push(relationship.type, payload); record.updateBelongsTo(relationship.key, record); return record; }, null, "DS: Extract payload of " + record + " : " + relationship.type); } function _findAll(adapter, store, type, sinceToken) { var promise = adapter.findAll(store, type, sinceToken), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findAll of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findAll'); store.pushMany(type, payload); store.didUpdateAll(type); return store.all(type); }, null, "DS: Extract payload of findAll " + type); } function _findQuery(adapter, store, type, query, recordArray) { var promise = adapter.findQuery(store, type, query, recordArray), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findQuery of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findQuery'); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + type); } function _commit(adapter, store, operation, record) { var type = record.constructor, promise = adapter[operation](store, type, record), serializer = serializerForAdapter(adapter, type); return promise.then(function(payload) { if (payload) { payload = serializer.extract(store, type, payload, get(record, 'id'), operation); } store.didSaveRecord(record, payload); return record; }, function(reason) { if (reason instanceof DS.InvalidError) { store.recordWasInvalid(record, reason.errors); } else { store.recordWasError(record, reason); } throw reason; }, "DS: Extract and notify about " + operation + " completion of " + record); } })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (These state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What we mean is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ var hasDefinedProperties = function(object) { // Ignore internal property defined by simulated `Ember.create`. var names = Ember.keys(object); var i, l, name; for (i = 0, l = names.length; i < l; i++ ) { name = names[i]; if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; }; var didSetProperty = function(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); }; // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: No client-side validations have failed and the // adapter did not report any server-side validation failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, propertyWasReset: function(record, name) { var stillDirty = false; for (var prop in record._attributes) { stillDirty = true; break; } if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` state when its client-side // invalidations have failed, or if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, didSetProperty: function(record, context) { get(record, 'errors').remove(context.name); didSetProperty(record, context); }, becomeDirty: Ember.K, rolledBack: function(record) { get(record, 'errors').clear(); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}, value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); createdState.uncommitted.deleteRecord = function(record) { record.clearRelationships(); record.transitionTo('deleted.saved'); }; createdState.uncommitted.rollback = function(record) { DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.suspendRelationshipObservers(function() { record.notifyPropertyChange('data'); }); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); } }, // A record enters this state when the store askes // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes, isDirty = false; for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { isDirty = true; break; } } if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { record.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); } } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); DS.RootState = RootState; })(); (function() { var get = Ember.get, isEmpty = Ember.isEmpty; /** @module ember-data */ /** Holds validation errors for a given record organized by attribute names. @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ DS.Errors = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.reduceComputed("content", { initialValue: function() { return Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); }, addedItem: function(errors, error) { errors.get(error.attribute).pushObject(error); return errors; }, removedItem: function(errors, error) { errors.get(error.attribute).removeObject(error); return errors; } }), /** Returns errors for a given attribute @method errorsFor @param {String} attribute @returns {Array} */ errorsFor: function(attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** */ messages: Ember.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function() { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function(attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** @method nextObject @private */ nextObject: function(index, previousObject, context) { return get(this, 'content').objectAt(index); }, /** Total number of errors. @property length @type {Number} @readOnly */ length: Ember.computed.oneWay('content.length').readOnly(), /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. @method add @param {String} attribute @param {Array|String} messages */ add: function(attribute, messages) { var wasEmpty = get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); get(this, 'content').addObjects(messages); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function(attribute, messages) { var errors = this.errorsFor(attribute); return Ember.makeArray(messages).map(function(message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. @method remove @param {String} attribute */ remove: function(attribute) { if (get(this, 'isEmpty')) { return; } var content = get(this, 'content').rejectBy('attribute', attribute); get(this, 'content').setObjects(content); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages and sends `becameValid` event to the record. @method clear */ clear: function() { if (get(this, 'isEmpty')) { return; } get(this, 'content').clear(); this.enumerableContentDidChange(); this.trigger('becameValid'); }, /** Checks if there is error messages for the given attribute. @method has @param {String} attribute @returns {Boolean} true if there some errors on given attribute */ has: function(attribute) { return !isEmpty(this.errorsFor(attribute)); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, merge = Ember.merge, once = Ember.run.once; var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { return get(get(this, 'currentState'), key); }).readOnly(); /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ DS.Model = Ember.Object.extend(Ember.Evented, { /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store askes the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord(App.Model); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord(App.Model); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.set('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly */ isDirty: retrieveFromCurrentState, /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord(App.Model); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord(App.Model); record.get('isDeleted'); // false record.deleteRecord(); record.get('isDeleted'); // true ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord(App.Model); record.get('isNew'); // true store.find('model', 1).then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when no client-side validations have failed and the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord(App.Model); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend. This may also result in the record having its `isValid` property become false if the adapter reported that server-side validations failed. Example ```javascript record.get('isError'); // false record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** The `clientId` property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id. @property clientId @private @type {Number|String} */ clientId: null, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord(App.Model); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, transaction: null, /** @property currentState @private @type {Object} */ currentState: null, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash typically contains keys coresponding to the invalid property names and values which are an array of error messages. ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('errors').get('foo'); // ['foo should be a number.'] }); ``` @property errors @type {Object} */ errors: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @returns {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @returns {Object} A JSON representation of the object. */ toJSON: function(options) { // container is for lazy transform lookups var serializer = DS.JSONSerializer.create({ container: this.container }); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).property(), _data: null, init: function() { set(this, 'currentState', DS.RootState.empty); var errors = DS.Errors.create(); errors.registerHandlers(this, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); set(this, 'errors', errors); this._super(); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = {}; this._inFlightAttributes = {}; this._relationships = {}; }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = name.split(".", 1), currentState = get(this, 'currentState'), state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = name.split("."); var setups = [], enters = [], i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollback()` a delete after it was made. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { softDelete: function() { this.get('model').deleteRecord(); }, confirm: function() { this.get('model').save(); }, undo: function() { this.get('model').rollback(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this.send('deleteRecord'); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; this.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function() { this.deleteRecord(); return this.save(); }, /** @method unloadRecord @private */ unloadRecord: function() { this.send('unloadRecord'); }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { var hasMany = this._relationships[relationship.name]; if (hasMany) { hasMany.clear(); } } }, this); }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { get(this, 'store').dataWasUpdated(this.constructor, this); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```javascript App.Mascot = DS.Model.extend({ name: attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.set('name', 'Tomster'); person.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this, '_data'), newData = get(this, '_attributes'), diffData = {}, prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { set(this, 'isError', false); if (data) { this._data = data; } else { Ember.mixin(this._data, this._inFlightAttributes); } this._inFlightAttributes = {}; this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { this.reloadHasManys(); }, 'data'), reloadHasManys: function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (this._data.links && this._data.links[name]) { return; } if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); }, hasManyDidChange: function(key) { var hasMany = this._relationships[key]; if (hasMany) { var records = this._data[key] || []; set(hasMany, 'content', Ember.A(records)); set(hasMany, 'isLoaded', true); hasMany.trigger('didLoad'); } }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { Ember.run.once(this, this.updateRecordArrays); }, /** @method setupData @private @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ setupData: function(data, partial) { if (partial) { Ember.merge(this._data, data); } else { this._data = data; } var relationships = this._relationships; this.eachRelationship(function(name, rel) { if (data.links && data.links[name]) { return; } if (rel.options.async) { relationships[name] = null; } }); if (data) { this.pushedData(); } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { merge(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, /** @method updateHasMany @private @param {String} name @param {Array} records */ updateHasMany: function(name, records) { this._data[name] = records; this.hasManyDidChange(name); }, /** @method updateBelongsTo @private @param {String} name @param {DS.Model} record */ updateBelongsTo: function(name, record) { this._data[name] = record; }, /** If the model `isDirty` this function will which discard any unsaved changes Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback */ rollback: function() { this._attributes = {}; if (get(this, 'isError')) { this._inFlightAttributes = {}; set(this, 'isError', false); } if (!get(this, 'isValid')) { this._inFlightAttributes = {}; } this.send('rolledBack'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. @method suspendRelationshipObservers @private @param callback @param binding */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, /** Save the record and persist any changes to the record to an extenal source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function(){ // Success callback }, function() { // Error callback }); ``` @method save @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function() { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.get('store').scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = {}; return DS.PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```javascript App.ModelViewRoute = Ember.Route.extend({ actions: { reload: function() { this.get('model').reload(); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { set(this, 'isReloading', true); var record = this; var promiseLabel = "DS: Model#reload of " + this; var promise = new Ember.RSVP.Promise(function(resolve){ record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags"); return DS.PromiseObject.create({ promise: promise }); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { this._data[attributeName] = value; this.notifyPropertyChange(attributeName); } else { this._data[attributeName] = this._inFlightAttributes[attributeName]; } this.updateRecordArraysLater(); }, /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var recordErrors = get(this, 'errors'); function addError(name) { if (errors[name]) { recordErrors.add(name, errors[name]); } } this.eachAttribute(addError); this.eachRelationship(addError); }, /** @method adapterDidError @private */ adapterDidError: function() { this.send('becameError'); set(this, 'isError', true); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param name */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); }, triggerLater: function() { this._deferredTriggers.push(arguments); once(this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l=this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers = []; } }); DS.Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: DS.Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** @class Model @namespace DS */ DS.Model.reopenClass({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); var attributes = Ember.get(App.Person, 'attributes') attributes.forEach(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { meta.name = name; map.set(name, meta); } }); return map; }), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); App.Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachAttribute: function(callback, binding) { get(this, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a tring contrining the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); App.Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachTransformedAttribute: function(callback, binding) { get(this, 'transformedAttributes').forEach(function(name, type) { callback.call(binding, name, type); }); } }); DS.Model.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue(); } else { return options.defaultValue; } } function hasValue(record, key) { return record._attributes.hasOwnProperty(key) || record._inFlightAttributes.hasOwnProperty(key) || record._data.hasOwnProperty(key); } function getValue(record, key) { if (record._attributes.hasOwnProperty(key)) { return record._attributes[key]; } else if (record._inFlightAttributes.hasOwnProperty(key)) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](DS.Transform.html). `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```javascript var attr = DS.attr; App.User = DS.Model.extend({ username: attr('string'), email: attr('string'), verified: attr('boolean', {defaultValue: false}) }); ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ DS.attr = function(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed(function(key, value) { if (arguments.length > 1) { var oldValue = this._attributes[key] || this._inFlightAttributes[key] || this._data[key]; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); this._attributes[key] = value; return value; } else if (hasValue(this, key)) { return getValue(this, key); } else { return getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).property('data').meta(meta); }; })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ /** An AttributeChange object is created whenever a record's attribute changes value. It is used to track changes to a record between transaction commits. @class AttributeChange @namespace DS @private @constructor */ var AttributeChange = DS.AttributeChange = function(options) { this.record = options.record; this.store = options.store; this.name = options.name; this.value = options.value; this.oldValue = options.oldValue; }; AttributeChange.createChange = function(options) { return new AttributeChange(options); }; AttributeChange.prototype = { sync: function() { if (this.value !== this.oldValue) { this.record.send('becomeDirty'); this.record.updateRecordArraysLater(); } // TODO: Use this object in the commit process this.destroy(); }, /** If the AttributeChange is destroyed (either by being rolled back or being committed), remove it from the list of pending changes on the record. @method destroy */ destroy: function() { delete this.record._changesToSync[this.name]; } }; })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RelationshipChange @namespace DS @private @construtor */ DS.RelationshipChange = function(options) { this.parentRecord = options.parentRecord; this.childRecord = options.childRecord; this.firstRecord = options.firstRecord; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecord = options.secondRecord; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.changeType = options.changeType; this.store = options.store; this.committed = {}; }; /** @class RelationshipChangeAdd @namespace DS @private @construtor */ DS.RelationshipChangeAdd = function(options){ DS.RelationshipChange.call(this, options); }; /** @class RelationshipChangeRemove @namespace DS @private @construtor */ DS.RelationshipChangeRemove = function(options){ DS.RelationshipChange.call(this, options); }; DS.RelationshipChange.create = function(options) { return new DS.RelationshipChange(options); }; DS.RelationshipChangeAdd.create = function(options) { return new DS.RelationshipChangeAdd(options); }; DS.RelationshipChangeRemove.create = function(options) { return new DS.RelationshipChangeRemove(options); }; DS.OneToManyChange = {}; DS.OneToNoneChange = {}; DS.ManyToNoneChange = {}; DS.OneToOneChange = {}; DS.ManyToManyChange = {}; DS.RelationshipChange._createChange = function(options){ if(options.changeType === "add"){ return DS.RelationshipChangeAdd.create(options); } if(options.changeType === "remove"){ return DS.RelationshipChangeRemove.create(options); } }; DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse){ key = inverse.name; otherKind = inverse.kind; } if (!inverse){ return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; } else{ if(otherKind === "belongsTo"){ return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; } else{ return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; } } }; DS.RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecord.constructor, changeType; changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === "oneToMany"){ return DS.OneToManyChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToOne"){ return DS.OneToManyChange.createChange(secondRecord, firstRecord, store, options); } else if (changeType === "oneToNone"){ return DS.OneToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToNone"){ return DS.ManyToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "oneToOne"){ return DS.OneToOneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToMany"){ return DS.ManyToManyChange.createChange(firstRecord, secondRecord, store, options); } }; DS.OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: "belongsTo" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: childRecord, childRecord: parentRecord, secondRecord: childRecord, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: "hasMany" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) { // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "hasMany", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "belongsTo", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToOneChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange); correspondingChange.sync(); } } }; DS.OneToManyChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; DS.OneToManyChange.maintainInvariant( options, store, childRecord, key ); } else if (options.key) { key = options.key; } else { } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change); return change; }; DS.OneToManyChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && childRecord) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToManyChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange); correspondingChange.sync(); } } }; /** @class RelationshipChange @namespace DS */ DS.RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, parent; if (!name) { parent = this.secondRecord; if (!parent) { return; } var childType = this.firstRecord.constructor; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @method getFirstRecordName @return {String} */ getFirstRecordName: function() { var name = this.firstRecordName; return name; }, /** @method destroy @private */ destroy: function() { var childRecord = this.childRecord, belongsToName = this.getFirstRecordName(), hasManyName = this.getSecondRecordName(), store = this.store; store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType); }, getSecondRecord: function(){ return this.secondRecord; }, /** @method getFirstRecord @private */ getFirstRecord: function() { return this.firstRecord; }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); // the object is a value, and not a promise function isValue(object) { return typeof object === 'object' && (!object.then || typeof object.then !== 'function'); } DS.RelationshipChangeAdd.prototype.changeType = "add"; DS.RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, firstRecord); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.addObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && secondRecord instanceof DS.Model && get(firstRecord, firstRecordName) !== secondRecord) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, secondRecord); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.addObject(secondRecord); } }); } } this.coalesce(); }; DS.RelationshipChangeRemove.prototype.changeType = "remove"; DS.RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, null); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.removeObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && get(firstRecord, firstRecordName)) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, null); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.removeObject(secondRecord); } }); } } this.coalesce(); }; })(); (function() { /** @module ember-data */ })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; /** @module ember-data */ function asyncBelongsTo(type, options, meta) { return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), promiseLabel = "DS: Async belongsTo " + this + " : " + key; if (arguments.length === 2) { return value === undefined ? null : DS.PromiseObject.create({ promise: Ember.RSVP.resolve(value, promiseLabel) }); } var link = data.links && data.links[key], belongsTo = data[key]; if(!isNone(belongsTo)) { var promise = store.fetchRecord(belongsTo) || Ember.RSVP.resolve(belongsTo, promiseLabel); return DS.PromiseObject.create({ promise: promise}); } else if (link) { var resolver = Ember.RSVP.defer("DS: Async belongsTo (link) " + this + " : " + key); store.findBelongsTo(this, link, meta, resolver); return DS.PromiseObject.create({ promise: resolver.promise }); } else { return null; } }).property('data').meta(meta); } /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```javascript App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` @namespace @method belongsTo @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ DS.belongsTo = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; if (options.async) { return asyncBelongsTo(type, options, meta); } return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), belongsTo, typeClass; if (typeof type === 'string') { typeClass = store.modelFor(type); } else { typeClass = type; } if (arguments.length === 2) { return value === undefined ? null : value; } belongsTo = data[key]; if (isNone(belongsTo)) { return null; } store.fetchRecord(belongsTo); return belongsTo; }).property('data').meta(meta); }; /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. @class Model @namespace DS */ DS.Model.reopen({ /** @method belongsToWillChange @private @static @param record @param key */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded')) { var oldParent = get(record, key); if (oldParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" }); change.sync(); this._changesToSync[key] = change; } } }), /** @method belongsToDidChange @private @static @param record @param key */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if (newParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" }); change.sync(); } } delete this._changesToSync[key]; }) }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties; function asyncHasMany(type, options, meta) { return Ember.computed(function(key, value) { var relationship = this._relationships[key], promiseLabel = "DS: Async hasMany " + this + " : " + key; if (!relationship) { var resolver = Ember.RSVP.defer(promiseLabel); relationship = buildRelationship(this, key, options, function(store, data) { var link = data.links && data.links[key]; var rel; if (link) { rel = store.findHasMany(this, link, meta, resolver); } else { rel = store.findMany(this, data[key], meta.type, resolver); } // cache the promise so we can use it // when we come back and don't need to rebuild // the relationship. set(rel, 'promise', resolver.promise); return rel; }); } var promise = relationship.get('promise').then(function() { return relationship; }, null, "DS: Async hasMany records received"); return DS.PromiseArray.create({ promise: promise }); }).property('data').meta(meta); } function buildRelationship(record, key, options, callback) { var rels = record._relationships; if (rels[key]) { return rels[key]; } var data = get(record, 'data'), store = get(record, 'store'); var relationship = rels[key] = callback.call(record, store, data); return setProperties(relationship, { owner: record, name: key, isPolymorphic: options.polymorphic }); } function hasRelationship(type, options) { options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; if (options.async) { return asyncHasMany(type, options, meta); } return Ember.computed(function(key, value) { return buildRelationship(this, key, options, function(store, data) { var records = data[key]; return store.findMany(this, data[key], meta.type); }); }).property('data').meta(meta); } /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); App.Tag = DS.Model.extend({ posts: DS.hasMany('post') }); ``` #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```javascript var belongsTo = DS.belongsTo, hasMany = DS.hasMany; App.Comment = DS.Model.extend({ onePost: belongsTo('post'), twoPost: belongsTo('post'), redPost: belongsTo('post'), bluePost: belongsTo('post') }); App.Post = DS.Model.extend({ comments: hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ DS.hasMany = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } return hasRelationship(type, options); }; })(); (function() { var get = Ember.get, set = Ember.set; /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ DS.Model.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param proto @param key @param value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.Descriptor) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ DS.Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; if (options.inverse === null) { return null; } var inverseName, inverseKind; if (options.inverse) { inverseName = options.inverse; inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { if (typeof meta.type === 'string') { meta.type = this.store.modelFor(meta.type); } var relationshipsForType = map.get(meta.type); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type, types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || this.store.modelFor(type); } if (!types.contains(type)) { types.push(type); } } }); return types; }), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(), type; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = meta.type; if (!type && meta.kind === 'hasMany') { type = Ember.String.singularize(name); } else if (!type) { type = name; } if (typeof type === 'string') { meta.type = this.store.modelFor(type); } map.set(name, meta); } }); return map; }), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); DS.Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var forEach = Ember.EnumerableUtils.forEach; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ DS.RecordArrayManager = Ember.Object.extend({ init: function() { this.filteredRecordArrays = Ember.MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; }, recordDidChange: function(record) { this.changedRecords.push(record); once(this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || Ember.OrderedSet.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedRecords, function(record) { if (get(record, 'isDeleted')) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords = []; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } forEach(recordArrays, function(array) { array.removeRecord(record); }); }, _recordWasChanged: function (record) { var type = record.constructor, recordArrays = this.filteredRecordArrays.get(type), filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = record._loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } record._loadingRecordArrays = []; } }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { recordArrays.add(array); array.addRecord(record); } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeRecord(record); } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param array @param type @param filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type), records = typeMap.records, record; for (var i=0, l=records.length; i<l; i++) { record = records[i]; if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @method createManyArray @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, records) { var manyArray = DS.ManyArray.create({ type: type, content: records, store: this.store }); forEach(records, function(record) { var arrays = this.recordArraysForRecord(record); arrays.add(manyArray); }, this); return manyArray; }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} type @return {DS.RecordArray} */ createRecordArray: function(type) { var array = DS.RecordArray.create({ type: type, content: Ember.A(), store: this.store, isLoaded: true }); this.registerFilteredRecordArray(array, type); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {Class} type @param {Function} filter @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(type, filter) { var array = DS.FilteredRecordArray.create({ type: type, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, type, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {Class} type @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(type, query) { return DS.AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A(), store: this.store }); }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(record, array) { var loadingRecordArrays = record._loadingRecordArrays || []; loadingRecordArrays.push(array); record._loadingRecordArrays = loadingRecordArrays; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.ArrayPolyfills.map; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` @class InvalidError @namespace DS */ DS.InvalidError = function(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=errorProps.length; i<l; i++) { this[errorProps[i]] = tmp[errorProps[i]]; } }; DS.InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter First, create a new subclass of `DS.Adapter`: ```javascript App.MyAdapter = DS.Adapter.extend({ // ...your code here }); ``` To tell your store which adapter to use, set its `adapter` property: ```javascript App.store = DS.Store.create({ adapter: App.MyAdapter.create() }); ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `findQuery()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ DS.Adapter = Ember.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority then a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```javascript var DjangoAdapter = DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: ```javascript App.ApplicationAdapter = DS.Adapter.extend({ find: function(store, type, id) { var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: Ember.required(Function), /** The `findAll()` method is called when you call `find` on the store without an ID (i.e. `store.find('post')`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: null, /** This method is called when you call `find` on the store with a query object as the second parameter (i.e. `store.find('person', { page: 1 })`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findQuery: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String|Number} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Model} record @param {Object} options @return {Object} serialized record */ serialize: function(record, options) { return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ createRecord: Ember.required(Function), /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ updateRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ updateRecord: Ember.required(Function), /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ deleteRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ deleteRecord: Ember.required(Function), /** Find multiple records at once. By default, it loops over the provided ids and calls `find` on each. May be overwritten to improve performance and reduce the number of server requests. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findMany: function(store, type, ids) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, {ids: ids}).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var promises = map.call(ids, function(id) { return this.find(store, type, id); }, this); return Ember.RSVP.all(promises); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, fmt = Ember.String.fmt, indexOf = Ember.EnumerableUtils.indexOf; var counter = 0; /** `DS.FixtureAdapter` is an adapter that loads records from memory. Its primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but are not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. Its possible to do develop your entire application with `DS.FixtureAdapter`. For information on how to use the `FixtureAdapter` in your application please see the [FixtureAdapter guide](/guides/models/the-fixture-adapter/). @class FixtureAdapter @namespace DS @extends DS.Adapter */ DS.FixtureAdapter = DS.Adapter.extend({ // by default, fixtures are already in normalized form serializer: null, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {Subclass of DS.Model} type @return {Array} */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixture @param {Object} query @param {Subclass of DS.Model} type @return {Promise|Array} */ queryFixtures: function(fixtures, query, type) { }, /** @method updateFixtures @param {Subclass of DS.Model} type @param {Array} fixture */ updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {Subclass of DS.Model} type @param {DS.Model} record */ mockJSON: function(store, type, record) { return store.serializerFor(type).serialize(record, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String} id */ generateIdForRecord: function(store) { return "fixture-" + counter++; }, /** @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: function(store, type, id) { var fixtures = this.fixturesForType(type), fixture; if (fixtures) { fixture = Ember.A(fixtures).findProperty('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); if (fixtures) { fixtures = fixtures.filter(function(item) { return indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.deleteLoadedFixture(type, fixture); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param record */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if(existingFixture) { var index = indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param record */ findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = get(record, 'id'); return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if(''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { if (get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(callback.call(context)); }, get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule('actions', null, function() { resolve(callback.call(context)); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; function coerceId(id) { return id == null ? null : id+''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to defined across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ DS.RESTSerializer = DS.JSONSerializer.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```javascript App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implemention makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @returns {Object} */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } return this._super(type, hash, prop); }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ normalizePayload: function(type, payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {subclass of DS.Model} type @param {Object} hash @returns {Object} the normalized payload */ normalizePayload: function(type, payload) { return payload; }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = get(this, 'attrs'), payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = attrs[key]; if (payloadKey && payloadKey.key) { payloadKey = payloadKey.key; } if (typeof payloadKey === 'string') { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey, key; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, key; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id, requestType) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String} id @param {'find'|'createRecord'|'updateRecord'|'deleteRecord'} requestType @returns {Object} the primary response to the original request */ extractSingle: function(store, primaryType, payload, recordId, requestType) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop), isPrimary = typeName === primaryTypeName; // legacy support for singular resources if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) { primaryRecord = this.normalize(primaryType, payload[prop], prop); continue; } var type = store.modelFor(typeName); /*jshint loopfunc:true*/ forEach.call(payload[prop], function(hash) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord, isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload, id, requestType) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; } payload = { comments: comments, posts: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {'findAll'|'findMany'|'findHasMany'|'findQuery'} requestType @returns {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, payload) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryArray; for (var prop in payload) { var typeKey = prop, forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type), isPrimary = (!forcedSecondary && (typeName === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, payload) { payload = this.normalizePayload(null, payload); for (var prop in payload) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName); /*jshint loopfunc:true*/ var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) { return this.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** You can use this method to normalize the JSON root keys returned into the model type expected by your store. For example, your server may return underscored root keys rather than the expected camelcased versions. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { var camelized = Ember.String.camelize(root); return Ember.String.singularize(camelized); } }); ``` @method typeForRoot @param {String} root @returns {String} the model's typeKey */ typeForRoot: function(root) { return Ember.String.singularize(root); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = this._super(record, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param record @param options */ serialize: function(record, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends camelized root keys. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { hash[type.typeKey] = this.serialize(record, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "Type"] = belongsTo.constructor.typeKey; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```js DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Person` would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```js DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. An array of headers can be added to the adapter which are passed with every request: ```js DS.RESTAdapter.reopen({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ DS.RESTAdapter = DS.Adapter.extend({ defaultSerializer: '_rest', /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```javascript DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```javascript DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. An array of headers can be added to the adapter which are passed with every request: ```javascript DS.RESTAdapter.reopen({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the querystring. @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @returns {Promise} promise */ find: function(store, type, id) { return this.ajax(this.buildURL(type.typeKey, id), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @returns {Promise} promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @returns {Promise} promise */ findQuery: function(store, type, query) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as IDs. For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @returns {Promise} promise */ findMany: function(store, type, ids) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. If the URL is host-relative (starting with a single slash), the request will use the host specified on the adapter (if any). @method findHasMany @param {DS.Store} store @param {DS.Model} record @param {String} url @returns {Promise} promise */ findHasMany: function(store, record, url) { var host = get(this, 'host'), id = get(record, 'id'), type = record.constructor.typeKey; if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') { url = host + url; } return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Model} record @param {String} url @returns {Promise} promise */ findBelongsTo: function(store, record, url) { var id = get(record, 'id'), type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ createRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record, { includeId: true }); return this.ajax(this.buildURL(type.typeKey), "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ updateRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record); var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ deleteRecord: function(store, type, record) { var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "DELETE"); }, /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. @method buildURL @param {String} type @param {String} id @returns {String} url */ buildURL: function(type, id) { var url = [], host = get(this, 'host'), prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } if (id) { url.push(id); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, /** @method urlPrefix @private @param {String} path @param {String} parentUrl @return {String} urlPrefix */ urlPrefix: function(path, parentURL) { var host = get(this, 'host'), namespace = get(this, 'namespace'), url = []; if (path) { // Absolute path if (path.charAt(0) === '/') { if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js DS.RESTAdapter.reopen({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); }; }); ``` @method pathForType @param {String} type @returns {String} path **/ pathForType: function(type) { return Ember.String.pluralize(type); }, /** Takes an ajax response, and returns a relavant error. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` Note: As a correctness optimization, the default implementation of the `ajaxError` method strips out the `then` method from jquery's ajax response (jqXHR). This is important because the jqXHR's `then` method fulfills the promise with itself resulting in a circular "thenable" chain which may cause problems for some promise libraries. @method ajaxError @param {Object} jqXHR @return {Object} jqXHR */ ajaxError: function(jqXHR) { if (jqXHR) { jqXHR.then = null; } return jqXHR; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE ect. @param {Object} hash @return {Promise} promise */ ajax: function(url, type, hash) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { hash = adapter.ajaxOptions(url, type, hash); hash.success = function(json) { Ember.run(null, resolve, json); }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR)); }; Ember.$.ajax(hash); }, "DS: RestAdapter#ajax " + type + " to " + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE ect. @param {Object} hash @return {Object} hash */ ajaxOptions: function(url, type, hash) { hash = hash || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } if (this.headers !== undefined) { var headers = this.headers; hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; } }); })(); (function() { /** @module ember-data */ })(); (function() { DS.Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); })(); (function() { /** @module ember-data */ })(); (function() { /** Ember Data @module ember-data @main ember-data */ })(); (function() { Ember.String.pluralize = function(word) { return Ember.Inflector.inflector.pluralize(word); }; Ember.String.singularize = function(word) { return Ember.Inflector.inflector.singularize(word); }; })(); (function() { var BLANK_REGEX = /^\s*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow') //=> 'kine' inflector.singularize('kine') //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice') // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice') // => 'advice' inflector.pluralize('formula') // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula') // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || {}; ruleSet.irregularPairs = ruleSet.irregularPairs || {}; var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: {}, irregularInverse: {}, uncountable: {} }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); } Inflector.prototype = { /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, isBlank, isUncountable, isIrregular, isIrregularInverse, rule; isBlank = BLANK_REGEX.test(word); if (isBlank) { return word; } lowercase = word.toLowerCase(); isUncountable = this.rules.uncountable[lowercase]; if (isUncountable) { return word; } isIrregular = irregular && irregular[lowercase]; if (isIrregular) { return isIrregular; } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; Ember.Inflector = Inflector; })(); (function() { Ember.Inflector.defaultRules = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; })(); (function() { if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return Ember.String.pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return Ember.String.singularize(this); }; } })(); (function() { Ember.Inflector.inflector = new Ember.Inflector(Ember.Inflector.defaultRules); })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; DS.ActiveModelSerializer = DS.RESTSerializer.extend({ // SERIALIZE /** Converts camelcased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @returns String */ keyForAttribute: function(attr) { return Ember.String.decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @returns String */ keyForRelationship: function(key, kind) { key = Ember.String.decamelize(key); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return Ember.String.singularize(key) + "_ids"; } else { return key; } }, /** Does not serialize hasMany relationships by default. */ serializeHasMany: Ember.K, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute(key); json[key + "_type"] = Ember.String.capitalize(belongsTo.constructor.typeKey); }, // EXTRACT /** Extracts the model typeKey from underscored root objects. @method typeForRoot @param {String} root @returns String the model's typeKey */ typeForRoot: function(root) { var camelized = Ember.String.camelize(root); return Ember.String.singularize(camelized); }, /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @returns Object */ normalize: function(type, hash, prop) { this.normalizeLinks(hash); return this._super(type, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} hash */ normalizeLinks: function(data){ if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = Ember.String.camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, payload; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } else if (payload && relationship.kind === "hasMany") { var self = this; forEach(payload, function(single) { single.type = self.typeForRoot(single.type); }); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } } }); })(); (function() { var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; /** The EmbeddedRecordsMixin allows you to add embedded record support to your serializers. To set up embedded records, you include the mixin into the serializer and then define your embedded relations. ```js App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {embedded: 'always'} } }) ``` Currently only `{embedded: 'always'}` records are supported. @class EmbeddedRecordsMixin @namespace DS */ DS.EmbeddedRecordsMixin = Ember.Mixin.create({ /** Serialize has-may relationship when it is configured as embedded objects. @method serializeHasMany */ serializeHasMany: function(record, json, relationship) { var key = relationship.key, attrs = get(this, 'attrs'), embed = attrs && attrs[key] && attrs[key].embedded === 'always'; if (embed) { json[this.keyForAttribute(key)] = get(record, key).map(function(relation) { var data = relation.serialize(), primaryKey = get(this, 'primaryKey'); data[primaryKey] = get(relation, primaryKey); return data; }, this); } }, /** Extract embedded objects out of the payload for a single object and add them as sideloaded objects instead. @method extractSingle */ extractSingle: function(store, primaryType, payload, recordId, requestType) { var root = this.keyForAttribute(primaryType.typeKey), partial = payload[root]; updatePayloadWithEmbedded(store, this, primaryType, partial, payload); return this._super(store, primaryType, payload, recordId, requestType); }, /** Extract embedded objects out of a standard payload and add them as sideloaded objects instead. @method extractArray */ extractArray: function(store, type, payload) { var root = this.keyForAttribute(type.typeKey), partials = payload[Ember.String.pluralize(root)]; forEach(partials, function(partial) { updatePayloadWithEmbedded(store, this, type, partial, payload); }, this); return this._super(store, type, payload); } }); function updatePayloadWithEmbedded(store, serializer, type, partial, payload) { var attrs = get(serializer, 'attrs'); if (!attrs) { return; } type.eachRelationship(function(key, relationship) { var expandedKey, embeddedTypeKey, attribute, ids, config = attrs[key], serializer = store.serializerFor(relationship.type.typeKey), primaryKey = get(serializer, "primaryKey"); if (relationship.kind !== "hasMany") { return; } if (config && (config.embedded === 'always' || config.embedded === 'load')) { // underscore forces the embedded records to be side loaded. // it is needed when main type === relationship.type embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey); expandedKey = this.keyForRelationship(key, relationship.kind); attribute = this.keyForAttribute(key); ids = []; if (!partial[attribute]) { return; } payload[embeddedTypeKey] = payload[embeddedTypeKey] || []; forEach(partial[attribute], function(data) { var embeddedType = store.modelFor(relationship.type.typeKey); updatePayloadWithEmbedded(store, serializer, embeddedType, data, payload); ids.push(data[primaryKey]); payload[embeddedTypeKey].push(data); }); partial[expandedKey] = ids; delete partial[attribute]; } }, serializer); } })(); (function() { /** @module ember-data */ var forEach = Ember.EnumerableUtils.forEach; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelcasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.Adapter **/ DS.ActiveModelAdapter = DS.RESTAdapter.extend({ defaultSerializer: '_ams', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @returns String */ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param jqXHR @returns error */ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"], errors = {}; forEach(Ember.keys(jsonErrors), function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; }); return new DS.InvalidError(errors); } else { return error; } } }); })(); (function() { })(); (function() { Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "activeModelAdapter", initialize: function(container, application) { application.register('serializer:_ams', DS.ActiveModelSerializer); application.register('adapter:_ams', DS.ActiveModelAdapter); } }); }); })(); (function() { })(); })(); if (typeof location !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) { Ember.Logger.warn("You are running a production build of Ember on localhost and won't receive detailed error messages. "+ "If you want full error messages please use the non-minified build provided on the Ember website."); }
!function(e){function t(r){if(n[r])return n[r].exports;var s=n[r]={i:r,l:!1,exports:{}};return e[r].call(s.exports,s,s.exports,t),s.l=!0,s.exports}var n={};t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var s in e)t.d(r,s,function(t){return e[t]}.bind(null,s));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s="mdyV")}({"/IQw":function(e,t,n){const r=n("ffMB"),{defaults:s}=n("bixo"),{inline:i}=n("Jzis"),{findClosingBracket:o,escape:a}=n("AkNA");e.exports=class e{constructor(e,t){if(this.options=t||s,this.links=e,this.rules=i.normal,this.options.renderer=this.options.renderer||new r,this.renderer=this.options.renderer,this.renderer.options=this.options,!this.links)throw new Error("Tokens array requires a `links` property.");this.options.pedantic?this.rules=i.pedantic:this.options.gfm&&(this.rules=this.options.breaks?i.breaks:i.gfm)}static get rules(){return i}static output(t,n,r){return new e(n,r).output(t)}output(t){let n,r,s,i,l,c,u="";for(;t;)if(l=this.rules.escape.exec(t))t=t.substring(l[0].length),u+=a(l[1]);else if(l=this.rules.tag.exec(t))!this.inLink&&/^<a /i.test(l[0])?this.inLink=!0:this.inLink&&/^<\/a>/i.test(l[0])&&(this.inLink=!1),!this.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(l[0])?this.inRawBlock=!0:this.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(l[0])&&(this.inRawBlock=!1),t=t.substring(l[0].length),u+=this.renderer.html(this.options.sanitize?this.options.sanitizer?this.options.sanitizer(l[0]):a(l[0]):l[0]);else if(l=this.rules.link.exec(t)){const r=o(l[2],"()");if(r>-1){const e=(0===l[0].indexOf("!")?5:4)+l[1].length+r;l[2]=l[2].substring(0,r),l[0]=l[0].substring(0,e).trim(),l[3]=""}t=t.substring(l[0].length),this.inLink=!0,s=l[2],this.options.pedantic?(n=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(s),n?(s=n[1],i=n[3]):i=""):i=l[3]?l[3].slice(1,-1):"",s=s.trim().replace(/^<([\s\S]*)>$/,"$1"),u+=this.outputLink(l,{href:e.escapes(s),title:e.escapes(i)}),this.inLink=!1}else if((l=this.rules.reflink.exec(t))||(l=this.rules.nolink.exec(t))){if(t=t.substring(l[0].length),n=(l[2]||l[1]).replace(/\s+/g," "),n=this.links[n.toLowerCase()],!n||!n.href){u+=l[0].charAt(0),t=l[0].substring(1)+t;continue}this.inLink=!0,u+=this.outputLink(l,n),this.inLink=!1}else if(l=this.rules.strong.exec(t))t=t.substring(l[0].length),u+=this.renderer.strong(this.output(l[4]||l[3]||l[2]||l[1]));else if(l=this.rules.em.exec(t))t=t.substring(l[0].length),u+=this.renderer.em(this.output(l[6]||l[5]||l[4]||l[3]||l[2]||l[1]));else if(l=this.rules.code.exec(t))t=t.substring(l[0].length),u+=this.renderer.codespan(a(l[2].trim(),!0));else if(l=this.rules.br.exec(t))t=t.substring(l[0].length),u+=this.renderer.br();else if(l=this.rules.del.exec(t))t=t.substring(l[0].length),u+=this.renderer.del(this.output(l[1]));else if(l=this.rules.autolink.exec(t))t=t.substring(l[0].length),"@"===l[2]?(r=a(this.mangle(l[1])),s="mailto:"+r):(r=a(l[1]),s=r),u+=this.renderer.link(s,null,r);else if(this.inLink||!(l=this.rules.url.exec(t))){if(l=this.rules.text.exec(t))t=t.substring(l[0].length),u+=this.renderer.text(this.inRawBlock?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(l[0]):a(l[0]):l[0]:a(this.smartypants(l[0])));else if(t)throw new Error("Infinite loop on byte: "+t.charCodeAt(0))}else{if("@"===l[2])r=a(l[0]),s="mailto:"+r;else{do{c=l[0],l[0]=this.rules._backpedal.exec(l[0])[0]}while(c!==l[0]);r=a(l[0]),s="www."===l[1]?"http://"+r:r}t=t.substring(l[0].length),u+=this.renderer.link(s,null,r)}return u}static escapes(t){return t?t.replace(e.rules._escapes,"$1"):t}outputLink(e,t){const n=t.href,r=t.title?a(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,a(e[1]))}smartypants(e){return this.options.smartypants?e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e}mangle(e){if(!this.options.mangle)return e;const t=e.length;let n,r="",s=0;for(;s<t;s++)n=e.charCodeAt(s),Math.random()>.5&&(n="x"+n.toString(16)),r+="&#"+n+";";return r}}},"0G4o":function(e){e.exports=class{constructor(){this.seen={}}slug(e){let t=e.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-");if(this.seen.hasOwnProperty(t)){const e=t;do{this.seen[e]++,t=e+"-"+this.seen[e]}while(this.seen.hasOwnProperty(t))}return this.seen[t]=0,t}}},"5y6D":function(e,t,n){const{defaults:r}=n("bixo"),{block:s}=n("Jzis"),{rtrim:i,splitCells:o,escape:a}=n("AkNA");e.exports=class e{constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||r,this.rules=s.normal,this.options.pedantic?this.rules=s.pedantic:this.options.gfm&&(this.rules=s.gfm)}static get rules(){return s}static lex(t,n){return new e(n).lex(t)}lex(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g," "),this.token(e,!0)}token(e,t){let n,r,l,c,u,p,h,d,f,g,m,_,b,y,v,k;for(e=e.replace(/^ +$/gm,"");e;)if((l=this.rules.newline.exec(e))&&(e=e.substring(l[0].length),l[0].length>1&&this.tokens.push({type:"space"})),l=this.rules.code.exec(e)){const t=this.tokens[this.tokens.length-1];e=e.substring(l[0].length),t&&"paragraph"===t.type?t.text+="\n"+l[0].trimRight():(l=l[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",codeBlockStyle:"indented",text:this.options.pedantic?l:i(l,"\n")}))}else if(l=this.rules.fences.exec(e))e=e.substring(l[0].length),this.tokens.push({type:"code",lang:l[2]?l[2].trim():l[2],text:l[3]||""});else if(l=this.rules.heading.exec(e))e=e.substring(l[0].length),this.tokens.push({type:"heading",depth:l[1].length,text:l[2]});else if((l=this.rules.nptable.exec(e))&&(p={type:"table",header:o(l[1].replace(/^ *| *\| *$/g,"")),align:l[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:l[3]?l[3].replace(/\n$/,"").split("\n"):[]},p.header.length===p.align.length)){for(e=e.substring(l[0].length),m=0;m<p.align.length;m++)p.align[m]=/^ *-+: *$/.test(p.align[m])?"right":/^ *:-+: *$/.test(p.align[m])?"center":/^ *:-+ *$/.test(p.align[m])?"left":null;for(m=0;m<p.cells.length;m++)p.cells[m]=o(p.cells[m],p.header.length);this.tokens.push(p)}else if(l=this.rules.hr.exec(e))e=e.substring(l[0].length),this.tokens.push({type:"hr"});else if(l=this.rules.blockquote.exec(e))e=e.substring(l[0].length),this.tokens.push({type:"blockquote_start"}),l=l[0].replace(/^ *> ?/gm,""),this.token(l,t),this.tokens.push({type:"blockquote_end"});else if(l=this.rules.list.exec(e)){for(e=e.substring(l[0].length),c=l[2],y=c.length>1,h={type:"list_start",ordered:y,start:y?+c:"",loose:!1},this.tokens.push(h),l=l[0].match(this.rules.item),d=[],n=!1,b=l.length,m=0;m<b;m++)p=l[m],g=p.length,p=p.replace(/^ *([*+-]|\d+\.) */,""),~p.indexOf("\n ")&&(g-=p.length,p=p.replace(this.options.pedantic?/^ {1,4}/gm:new RegExp("^ {1,"+g+"}","gm"),"")),m!==b-1&&(u=s.bullet.exec(l[m+1])[0],(c.length>1?1===u.length:u.length>1||this.options.smartLists&&u!==c)&&(e=l.slice(m+1).join("\n")+e,m=b-1)),r=n||/\n\n(?!\s*$)/.test(p),m!==b-1&&(n="\n"===p.charAt(p.length-1),r||(r=n)),r&&(h.loose=!0),v=/^\[[ xX]\] /.test(p),k=void 0,v&&(k=" "!==p[1],p=p.replace(/^\[[ xX]\] +/,"")),f={type:"list_item_start",task:v,checked:k,loose:r},d.push(f),this.tokens.push(f),this.token(p,!1),this.tokens.push({type:"list_item_end"});if(h.loose)for(b=d.length,m=0;m<b;m++)d[m].loose=!0;this.tokens.push({type:"list_end"})}else if(l=this.rules.html.exec(e))e=e.substring(l[0].length),this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&("pre"===l[1]||"script"===l[1]||"style"===l[1]),text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(l[0]):a(l[0]):l[0]});else if(t&&(l=this.rules.def.exec(e)))e=e.substring(l[0].length),l[3]&&(l[3]=l[3].substring(1,l[3].length-1)),_=l[1].toLowerCase().replace(/\s+/g," "),this.tokens.links[_]||(this.tokens.links[_]={href:l[2],title:l[3]});else if((l=this.rules.table.exec(e))&&(p={type:"table",header:o(l[1].replace(/^ *| *\| *$/g,"")),align:l[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:l[3]?l[3].replace(/\n$/,"").split("\n"):[]},p.header.length===p.align.length)){for(e=e.substring(l[0].length),m=0;m<p.align.length;m++)p.align[m]=/^ *-+: *$/.test(p.align[m])?"right":/^ *:-+: *$/.test(p.align[m])?"center":/^ *:-+ *$/.test(p.align[m])?"left":null;for(m=0;m<p.cells.length;m++)p.cells[m]=o(p.cells[m].replace(/^ *\| *| *\| *$/g,""),p.header.length);this.tokens.push(p)}else if(l=this.rules.lheading.exec(e))e=e.substring(l[0].length),this.tokens.push({type:"heading",depth:"="===l[2].charAt(0)?1:2,text:l[1]});else if(t&&(l=this.rules.paragraph.exec(e)))e=e.substring(l[0].length),this.tokens.push({type:"paragraph",text:"\n"===l[1].charAt(l[1].length-1)?l[1].slice(0,-1):l[1]});else if(l=this.rules.text.exec(e))e=e.substring(l[0].length),this.tokens.push({type:"text",text:l[0]});else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0));return this.tokens}}},A61a:function(e,t,n){"use strict";(function(e){function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o({url:e,headers:t={},body:n={},settings:r={}}){const s={credentials:"omit",method:"GET",mode:"cors",cache:"default",headers:{}};r.jwtToken&&(s.headers={Authorization:`Bearer ${r.jwtToken}`});let i="";return"POST"===r.method||"PUT"===r.method||"PATCH"===r.method||"DELETE"===r.method?(s.method=r.method,s.body=JSON.stringify(n),s.headers["Content-Type"]="application/json"):i=p.a.stringify(n),fetch(`${r.apiServer}${e}${i?`?${i}`:""}`,s).then((e=>e)).then((e=>e.json())).catch((e=>{throw e}))}function a(t){const{apiServer:n,articleId:r,sheetId:i,className:a,style:u}=t,[p,d]=Object(c.c)({}),[m,_]=Object(c.c)({}),[b,y]=Object(c.c)({}),[v,k]=Object(c.c)({}),[O,w]=Object(c.c)({}),[x,j]=Object(c.c)(0),[$,S]=Object(c.c)(!1),[D,A]=Object(c.c)({}),[I,P]=Object(c.c)({}),[C,T]=Object(c.c)({}),E=i||p["form-sheetId"],M=`data-${E}`;Object(c.b)((()=>{const e=localStorage.getItem(M);e&&A(JSON.parse(e))}),[E]),Object(c.b)((()=>{r&&(async()=>{const e=await o({url:`/api/article/${r}`,settings:{apiServer:n}});d(e.article),_(e.imageServer),y(e.imagePath)})()}),[r]),Object(c.b)((()=>{E&&(async()=>{const e=await o({url:`/api/forms/${E}`,settings:{apiServer:n}});w(e)})()}),[E]);Object(c.a)((e=>{const{id:t}=e.target.closest("tr").dataset;j(t)}),[x]),Object(c.a)((()=>{j(0),P({})}),[0]);const L=Object(c.a)((e=>{const{name:t,value:n}=e.target,{validation:r,removechars:i,help:o}=e.target.dataset;let a=n;if("email"===t&&(a=n.toLowerCase()),i){const e=new RegExp(`${i}`,"g");a=`${a}`.replace(e,"")}const l=s({},D);if(l[t]=a,A(l),E&&localStorage.setItem(M,JSON.stringify(l)),r){const n=s({},C);if("email"===r)h.a.validateEmail(a)?(e.target.classList.remove("is-invalid"),e.target.classList.add("is-valid"),delete n[t]):(e.target.classList.remove("is-valid"),e.target.classList.add("is-invalid"),n[t]=o);else{new RegExp(`${r}`).test(a)?(e.target.classList.remove("is-invalid"),e.target.classList.add("is-valid"),delete n[t]):(e.target.classList.remove("is-valid"),e.target.classList.add("is-invalid"),n[t]=o)}T(n)}}),[D]),z=Object(c.a)((async()=>{D.email&&h.a.validateEmail(D.email)&&0===Object.keys(C).length&&(S(!0),await(async()=>{const e=await o({url:`/api/forms/${E}`,body:s({},D),settings:{apiServer:n,method:"POST"}});P(e)})(),S(!1))}),[D,x]);return I&&I.status?Object(l.h)(e,null,Object(l.h)("div",{class:`${p["form-class"]} ${a}`,style:`${p["form-style"]} ${u}`},I.status<300?Object(l.h)(e,null,Object(l.h)("div",{class:"alert alert-success",role:"alert"},Object(l.h)("i",{class:"fas fa-check text-success"})," Påmeldingen er mottatt.")):Object(l.h)(e,null,Object(l.h)("div",{class:"alert alert-danger",role:"alert"},Object(l.h)("i",{class:"fas fa-exclamation-triangle text-danger"})," ",I.data)))):Object(l.h)("div",{class:`${p["form-class"]} row ${a}`,style:`${p["form-style"]} ${u}`},O&&O.title?Object(l.h)(e,null,O.rows&&O.rows.map((t=>{if("headerRow"===t.type){const n=t.values.split(","),r=t.titles.split(",");return Object(l.h)(e,null,(t.heading||t.description)&&Object(l.h)("div",{class:"col-12"},t.heading&&Object(l.h)("h5",{class:"mt-5"},t.heading),t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g})),Object(l.h)("div",{class:"col-12"},Object(l.h)("div",{class:"row"},Object(l.h)("div",{class:t.classes||"col-3"},t.title&&Object(l.h)("label",{for:`${t.name}Input`},t.title)),n&&n.map(((e,n)=>Object(l.h)("div",{class:`${t.valueClasses||"col-12"}`},r[n]||e))))))}if("checkboxHorizontal"===t.type){const n=t.values.split(","),r=t.titles.split(",");return Object(l.h)(e,null,(t.heading||t.description)&&Object(l.h)("div",{class:"col-12"},t.heading&&Object(l.h)("h5",{class:"mt-5"},t.heading),t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g})),Object(l.h)("div",{class:"col-12"},Object(l.h)("div",{class:"row"},Object(l.h)("div",{class:t.classes||"col-3"},t.title&&Object(l.h)("label",{for:`${t.name}Input`},t.title)),n&&n.map(((e,n)=>Object(l.h)("div",{class:`${t.valueClasses||"col-12"}`},Object(l.h)("div",{class:t.classes||"col-3"},Object(l.h)("div",{class:"form-check"},Object(l.h)("input",{class:"form-check-input",type:"checkbox",name:`${t.name}-${e}`,checked:"1"===D[`${t.name}-${e}`]&&"checked",id:`${t.name}Input${e}`,value:1,onInput:L}),Object(l.h)("label",{class:"form-check-label",for:`${t.name}Input${e}`},r[n]))))))),t.help&&Object(l.h)("small",{id:`${t.name}Help`,class:"form-text text-muted"},t.help)))}if("radio"===t.type){const n=t.values.split(","),r=t.titles.split(",");return Object(l.h)(e,null,(t.heading||t.description)&&Object(l.h)("div",{class:"col-12"},t.heading&&Object(l.h)("h5",{class:"mt-5"},t.heading),t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g})),Object(l.h)("div",{class:t.classes||"col-12"},t.title&&Object(l.h)("label",{for:`${t.name}Input`},t.title),Object(l.h)("div",{class:"row"},n&&n.map(((e,n)=>Object(l.h)("div",{class:`${t.valueClasses||"col-12"}`},Object(l.h)("div",{class:"form-check"},Object(l.h)("input",{class:"form-check-input",type:"radio",name:`${t.name}-${e}`,checked:"1"===D[`${t.name}-${e}`]&&"checked",id:`${t.name}Input${e}`,value:1,onInput:L}),Object(l.h)("label",{class:"form-check-label",for:`${t.name}Input${e}`},r[n]||e)))))),t.help&&Object(l.h)("small",{id:`${t.name}Help`,class:"form-text text-muted"},t.help)))}if("select"===t.type){const n=t.values.split(","),r=t.titles.split(",");return Object(l.h)(e,null,(t.heading||t.description)&&Object(l.h)("div",{class:"col-12"},t.heading&&Object(l.h)("h5",{class:"mt-5"},t.heading),t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g})),Object(l.h)("div",{class:t.classes||"col-12"},Object(l.h)("div",{class:"form-group"},Object(l.h)("label",{for:`${t.name}Input`},t.title),Object(l.h)("select",{id:`${t.name}Input`,class:"form-control",onInput:L,name:t.name},Object(l.h)("option",{selected:!0},"-- velg --"),n&&n.map(((n,s)=>Object(l.h)(e,null,Object(l.h)("option",{value:n,selected:D[t.name]===n&&"selected"},r[s]||n))))),t.help&&Object(l.h)("small",{id:`${t.name}Help`,class:"form-text text-muted"},t.help))))}if("checkbox"===t.type){const n=t.values.split(","),r=t.titles.split(",");return Object(l.h)(e,null,(t.heading||t.description)&&Object(l.h)("div",{class:"col-12"},t.heading&&Object(l.h)("h5",{class:"mt-5"},t.heading),t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g})),Object(l.h)("div",{class:t.classes||"col-12"},t.title&&Object(l.h)("label",{for:`${t.name}Input`},t.title),Object(l.h)("div",{class:"row"},n&&n.map(((e,n)=>Object(l.h)("div",{class:`${t.valueClasses||"col-12"}`},Object(l.h)("div",{class:"form-check"},Object(l.h)("input",{class:"form-check-input",type:"checkbox",name:`${t.name}-${e}`,checked:"1"===D[`${t.name}-${e}`]&&"checked",id:`${t.name}Input${e}`,value:1,onInput:L}),Object(l.h)("label",{class:"form-check-label",for:`${t.name}Input${e}`},r[n]||e)))))),t.help&&Object(l.h)("small",{id:`${t.name}Help`,class:"form-text text-muted"},t.help)))}return"textarea"===t.type?Object(l.h)(e,null,(t.heading||t.description)&&Object(l.h)("div",{class:"col-12"},t.heading&&Object(l.h)("h5",{class:"mt-5"},t.heading),t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g})),Object(l.h)("div",{class:t.classes||"col-12"},Object(l.h)("div",{class:"form-group"},t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g}),Object(l.h)("label",{for:`${t.name}Input`},t.title),Object(l.h)("textarea",{rows:5,class:"form-control",id:`${t.name}Input`,name:t.name,value:D[t.name],"aria-describedby":`${t.name}Help`,onInput:L,"data-validation":t.validation,"data-removechars":t.removechars,"data-help":t.helpvalidation}),t.help&&Object(l.h)("small",{id:`${t.name}Help`,class:"form-text text-muted"},t.help)))):Object(l.h)(e,null,(t.heading||t.description)&&Object(l.h)("div",{class:"col-12"},t.heading&&Object(l.h)("h5",{class:"mt-5"},t.heading),t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g})),Object(l.h)("div",{class:t.classes||"col-12"},Object(l.h)("div",{class:"form-group"},t.description&&Object(l.h)(f.a,{markdown:`${t.description}`,markdownOpts:g}),Object(l.h)("label",{for:`${t.name}Input`},t.title),Object(l.h)("input",{type:t.type,class:"form-control",id:`${t.name}Input`,name:t.name,value:D[t.name],"aria-describedby":`${t.name}Help`,onInput:L,"data-validation":t.validation,"data-removechars":t.removechars,"data-help":t.helpvalidation,min:t.min,max:t.max}),t.help&&Object(l.h)("small",{id:`${t.name}Help`,class:"form-text text-muted"},t.help),C[t.name]&&Object(l.h)("div",{id:`validationFeedback${t.name}`,class:"invalid-feedback"},C[t.name]))))})),$&&Object(l.h)(e,null,Object(l.h)("div",{class:"d-flex justify-content-center py-3"},Object(l.h)("div",{class:"spinner-border",role:"status"},Object(l.h)("span",{class:"sr-only"},"Sender inn informasjonen...")),Object(l.h)("div",{class:"ml-3"},"Sender inn informasjonen..."))),Object(l.h)("div",{class:"col-12 mt-5"},C&&Object.keys(C).length>0&&Object(l.h)(e,null,Object(l.h)("div",{class:"alert alert-danger",role:"alert"},Object(l.h)("ul",null,Object.keys(C).map((e=>Object(l.h)("li",null,C[e]||e)))))),Object(l.h)("button",{type:"button",class:`btn btn-block btn-${Object.keys(C).length>0||$?"secondary":"primary"} float-right`,onClick:z,disabled:$||Object.keys(C).length>0},0===Object.keys(C).length?Object(l.h)(e,null,"Send inn skjema"):Object(l.h)(e,null,"Fyll inn feltene over...")))):Object(l.h)(e,null,Object(l.h)("div",{class:"d-flex justify-content-center py-3"},Object(l.h)("div",{class:"spinner-border",role:"status"},Object(l.h)("span",{class:"sr-only"},"Loading...")))))}n.d(t,"a",(function(){return a}));var l=n("hosL"),c=n("QRet"),u=n("UKnr"),p=n.n(u),h=n("Utv1"),d=n("fh8t"),f=n.n(d);const g={pedantic:!1,gfm:!0,breaks:!0,sanitize:!1,smartLists:!0,smartypants:!0,xhtml:!0}}).call(this,n("hosL").Fragment)},AkNA:function(e){function t(e){return e.replace(u,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}function n(e,t){f[" "+e]||(f[" "+e]=g.test(e)?e+"/":r(e,"/",!0));const n=-1===(e=f[" "+e]).indexOf(":");return"//"===t.substring(0,2)?n?t:e.replace(m,"$1")+t:"/"===t.charAt(0)?n?t:e.replace(_,"$1")+t:e+t}function r(e,t,n){const r=e.length;if(0===r)return"";let s=0;for(;s<r;){const i=e.charAt(r-s-1);if(i!==t||n){if(i===t||!n)break;s++}else s++}return e.substr(0,r-s)}const s=/[&<>"']/,i=/[&<>"']/g,o=/[<>"']|&(?!#?\w+;)/,a=/[<>"']|&(?!#?\w+;)/g,l={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},c=e=>l[e],u=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,p=/(^|[^\[])\^/g,h=/[^\w:]/g,d=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i,f={},g=/^[^:]+:\/*[^/]*$/,m=/^([^:]+:)[\s\S]*$/,_=/^([^:]+:\/*[^/]*)[\s\S]*$/;e.exports={escape:function(e,t){if(t){if(s.test(e))return e.replace(i,c)}else if(o.test(e))return e.replace(a,c);return e},unescape:t,edit:function(e,t){e=e.source||e,t=t||"";const n={replace:(t,r)=>(r=(r=r.source||r).replace(p,"$1"),e=e.replace(t,r),n),getRegex:()=>new RegExp(e,t)};return n},cleanUrl:function(e,r,s){if(e){let e;try{e=decodeURIComponent(t(s)).replace(h,"").toLowerCase()}catch(e){return null}if(0===e.indexOf("javascript:")||0===e.indexOf("vbscript:")||0===e.indexOf("data:"))return null}r&&!d.test(s)&&(s=n(r,s));try{s=encodeURI(s).replace(/%25/g,"%")}catch(e){return null}return s},resolveUrl:n,noopTest:{exec:function(){}},merge:function(e){let t,n,r=1;for(;r<arguments.length;r++)for(n in t=arguments[r],t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},splitCells:function(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let r=!1,s=t;for(;--s>=0&&"\\"===n[s];)r=!r;return r?"|":" |"})).split(/ \|/);let r=0;if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(/\\\|/g,"|");return n},rtrim:r,findClosingBracket:function(e,t){if(-1===e.indexOf(t[1]))return-1;const n=e.length;let r=0,s=0;for(;s<n;s++)if("\\"===e[s])s++;else if(e[s]===t[0])r++;else if(e[s]===t[1]&&(r--,r<0))return s;return-1},checkSanitizeDeprecation:function(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}}},F2rU:function(e){e.exports=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}}},Jzis:function(e,t,n){const{noopTest:r,edit:s,merge:i}=n("AkNA"),o={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?\\?>\\n*|<![A-Z][\\s\\S]*?>\\n*|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,nptable:r,table:r,lheading:/^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};o.def=s(o.def).replace("label",o._label).replace("title",o._title).getRegex(),o.bullet=/(?:[*+-]|\d{1,9}\.)/,o.item=/^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/,o.item=s(o.item,"gm").replace(/bull/g,o.bullet).getRegex(),o.list=s(o.list).replace(/bull/g,o.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+o.def.source+")").getRegex(),o._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",o._comment=/<!--(?!-?>)[\s\S]*?-->/,o.html=s(o.html,"i").replace("comment",o._comment).replace("tag",o._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),o.paragraph=s(o._paragraph).replace("hr",o.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)").replace("tag",o._tag).getRegex(),o.blockquote=s(o.blockquote).replace("paragraph",o.paragraph).getRegex(),o.normal=i({},o),o.gfm=i({},o.normal,{nptable:"^ *([^|\\n ].*\\|.*)\\n *([-:]+ *\\|[-| :]*)(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)",table:"^ *\\|(.+)\\n *\\|?( *[-:]+[-| :]*)(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"}),o.gfm.nptable=s(o.gfm.nptable).replace("hr",o.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)").replace("tag",o._tag).getRegex(),o.gfm.table=s(o.gfm.table).replace("hr",o.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)").replace("tag",o._tag).getRegex(),o.pedantic=i({},o.normal,{html:s("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",o._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,fences:r,paragraph:s(o.normal._paragraph).replace("hr",o.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",o.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});const a={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:r,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,strong:/^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,em:/^_([^\s_])_(?!_)|^\*([^\s*<\[])\*(?!\*)|^_([^\s<][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_<][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s<"][\s\S]*?[^\s\*])\*(?!\*|[^\spunctuation])|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:r,text:/^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/,_punctuation:"!\"#$%&'()*+,\\-./:;<=>?@\\[^_{|}~"};a.em=s(a.em).replace(/punctuation/g,a._punctuation).getRegex(),a._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,a._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,a._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,a.autolink=s(a.autolink).replace("scheme",a._scheme).replace("email",a._email).getRegex(),a._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,a.tag=s(a.tag).replace("comment",o._comment).replace("attribute",a._attribute).getRegex(),a._label=/(?:\[[^\[\]]*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,a._href=/<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*/,a._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,a.link=s(a.link).replace("label",a._label).replace("href",a._href).replace("title",a._title).getRegex(),a.reflink=s(a.reflink).replace("label",a._label).getRegex(),a.normal=i({},a),a.pedantic=i({},a.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,link:s(/^!?\[(label)\]\((.*?)\)/).replace("label",a._label).getRegex(),reflink:s(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",a._label).getRegex()}),a.gfm=i({},a.normal,{escape:s(a.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^~+(?=\S)([\s\S]*?\S)~+/,text:/^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/}),a.gfm.url=s(a.gfm.url,"i").replace("email",a.gfm._extended_email).getRegex(),a.breaks=i({},a.gfm,{br:s(a.br).replace("{2,}","*").getRegex(),text:s(a.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()}),e.exports={block:o,inline:a}},Kx7A:function(e,t,n){const r=n("ffMB"),s=n("0G4o"),i=n("/IQw"),o=n("F2rU"),{defaults:a}=n("bixo"),{merge:l,unescape:c}=n("AkNA");e.exports=class e{constructor(e){this.tokens=[],this.token=null,this.options=e||a,this.options.renderer=this.options.renderer||new r,this.renderer=this.options.renderer,this.renderer.options=this.options,this.slugger=new s}static parse(t,n){return new e(n).parse(t)}parse(e){this.inline=new i(e.links,this.options),this.inlineText=new i(e.links,l({},this.options,{renderer:new o})),this.tokens=e.reverse();let t="";for(;this.next();)t+=this.tok();return t}next(){return this.token=this.tokens.pop(),this.token}peek(){return this.tokens[this.tokens.length-1]||0}parseText(){let e=this.token.text;for(;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)}tok(){let e="";switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,c(this.inlineText.output(this.token.text)),this.slugger);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":{let t,n,r,s,i="";for(r="",t=0;t<this.token.header.length;t++)r+=this.renderer.tablecell(this.inline.output(this.token.header[t]),{header:!0,align:this.token.align[t]});for(i+=this.renderer.tablerow(r),t=0;t<this.token.cells.length;t++){for(n=this.token.cells[t],r="",s=0;s<n.length;s++)r+=this.renderer.tablecell(this.inline.output(n[s]),{header:!1,align:this.token.align[s]});e+=this.renderer.tablerow(r)}return this.renderer.table(i,e)}case"blockquote_start":for(e="";"blockquote_end"!==this.next().type;)e+=this.tok();return this.renderer.blockquote(e);case"list_start":{e="";const t=this.token.ordered,n=this.token.start;for(;"list_end"!==this.next().type;)e+=this.tok();return this.renderer.list(e,t,n)}case"list_item_start":{e="";const t=this.token.loose,n=this.token.checked,r=this.token.task;if(this.token.task)if(t)if("text"===this.peek().type){const e=this.peek();e.text=this.renderer.checkbox(n)+" "+e.text}else this.tokens.push({type:"text",text:this.renderer.checkbox(n)});else e+=this.renderer.checkbox(n);for(;"list_item_end"!==this.next().type;)e+=t||"text"!==this.token.type?this.tok():this.parseText();return this.renderer.listitem(e,r,n)}case"html":return this.renderer.html(this.token.text);case"paragraph":return this.renderer.paragraph(this.inline.output(this.token.text));case"text":return this.renderer.paragraph(this.parseText());default:{const e='Token with "'+this.token.type+'" type was not found.';if(!this.options.silent)throw new Error(e);console.log(e)}}}}},MNOf:function(e){"use strict";function t(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,r,s,i){s=s||"=";var o={};if("string"!=typeof e||0===e.length)return o;var a=/\+/g;e=e.split(r=r||"&");var l=1e3;i&&"number"==typeof i.maxKeys&&(l=i.maxKeys);var c=e.length;l>0&&c>l&&(c=l);for(var u=0;u<c;++u){var p,h,d,f,g=e[u].replace(a,"%20"),m=g.indexOf(s);m>=0?(p=g.substr(0,m),h=g.substr(m+1)):(p=g,h=""),d=decodeURIComponent(p),f=decodeURIComponent(h),t(o,d)?n(o[d])?o[d].push(f):o[d]=[o[d],f]:o[d]=f}return o};var n=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},QRet:function(e,t,n){"use strict";function r(e,t){m.options.__h&&m.options.__h(f,e,_||t),_=0;var n=f.__H||(f.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function s(e){return _=1,function(e,t,n){var s=r(d++,2);return s.t=e,s.__c||(s.__=[n?n(t):h(void 0,t),function(e){var t=s.t(s.__[0],e);s.__[0]!==t&&(s.__=[t,s.__[1]],s.__c.setState({}))}],s.__c=f),s.__}(h,e)}function i(e,t){var n=r(d++,3);!m.options.__s&&p(n.__H,t)&&(n.__=e,n.__H=t,f.__H.__h.push(n))}function o(e,t){var n=r(d++,7);return p(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function a(e,t){return _=8,o((function(){return e}),t)}function l(){b.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(c),e.__H.__h.forEach(u),e.__H.__h=[]}catch(t){e.__H.__h=[],m.options.__e(t,e.__v)}})),b=[]}function c(e){var t=f;"function"==typeof e.__c&&e.__c(),f=t}function u(e){var t=f;e.__c=e.__(),f=t}function p(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function h(e,t){return"function"==typeof t?t(e):t}n.d(t,"c",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return a}));var d,f,g,m=n("hosL"),_=0,b=[],y=m.options.__b,v=m.options.__r,k=m.options.diffed,O=m.options.__c,w=m.options.unmount;m.options.__b=function(e){f=null,y&&y(e)},m.options.__r=function(e){v&&v(e),d=0;var t=(f=e.__c).__H;t&&(t.__h.forEach(c),t.__h.forEach(u),t.__h=[])},m.options.diffed=function(e){k&&k(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==b.push(t)&&g===m.options.requestAnimationFrame||((g=m.options.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),x&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);x&&(t=requestAnimationFrame(n))})(l)),f=void 0},m.options.__c=function(e,t){t.some((function(e){try{e.__h.forEach(c),e.__h=e.__h.filter((function(e){return!e.__||u(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],m.options.__e(n,e.__v)}})),O&&O(e,t)},m.options.unmount=function(e){w&&w(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(c)}catch(e){m.options.__e(e,t.__v)}};var x="function"==typeof requestAnimationFrame},QfWi:function(e,t,n){"use strict";function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}n.r(t);var s=n("hosL"),i=function(e){var t,n=e.selector,r=e.inline,s=e.clientSpecified,i=[],o=document.currentScript||(t=document.getElementsByTagName("script"))[t.length-1];!0===r&&i.push(o.parentNode);return!0!==s||n||(n=function(e){var t=e.attributes,n=null;return Object.keys(t).forEach((function(e){t.hasOwnProperty(e)&&"data-mount-in"===t[e].name&&(n=t[e].nodeValue)})),n}(o)),n&&[].forEach.call(document.querySelectorAll(n),(function(e){i.push(e)})),i},o=function(e,t,n,i,o){t.forEach((function(t){var a=t;if(!a._habitat){a._habitat=!0;var l=function(e,t){void 0===t&&(t={});var n=e.attributes,s=r({},t);return Object.keys(n).forEach((function(e){if(n.hasOwnProperty(e)){var t=n[e].name;if(!t||"string"!=typeof t)return!1;var r=t.split(/(data-props?-)/).pop()||"";t!==(r=r.replace(/-([a-z])/gi,(function(e,t){return t.toUpperCase()})))&&(s[r]=n[e].nodeValue)}})),[].forEach.call(e.getElementsByTagName("script"),(function(e){var t={};if(e.hasAttribute("type")){if("text/props"!==e.getAttribute("type")&&"application/json"!==e.getAttribute("type"))return;try{t=JSON.parse(e.innerHTML)}catch(e){throw new Error(e)}r(s,t)}})),s}(t,o)||o;return i&&(a.innerHTML=""),Object(s.render)(Object(s.h)(e,l),a,n)}}))};(function(e){var t=e;return{render:function(e){void 0===e&&(e={});var n=e.selector;void 0===n&&(n=null);var r=e.inline;void 0===r&&(r=!1);var s=e.clean;void 0===s&&(s=!1);var a=e.clientSpecified;void 0===a&&(a=!1);var l=e.defaultProps;void 0===l&&(l={});var c=i({selector:n,inline:r,clientSpecified:a}),u=function(){if(c.length>0){var e=i({selector:n,inline:r,clientSpecified:a});return o(t,e,null,s,l)}};u(),document.addEventListener("DOMContentLoaded",u),document.addEventListener("load",u)}}})(n("A61a").a).render({selector:'[data-widget-host="simple-blog-form"]',clean:!0})},RlRQ:function(e,t,n){"use strict";function r(e,t,n){if(3===e.nodeType){var s="textContent"in e?e.textContent:e.nodeValue||"";if(!1!==r.options.trim){var i=0===t||t===n.length-1;if((!(s=s.match(/^[\s\n]+$/g)&&"all"!==r.options.trim?" ":s.replace(/(^[\s\n]+|[\s\n]+$)/g,"all"===r.options.trim||i?"":" "))||" "===s)&&n.length>1&&i)return null}return s}if(1!==e.nodeType)return null;var o=String(e.nodeName).toLowerCase();if("script"===o&&!r.options.allowScripts)return null;var a,l,u=r.h(o,function(e){var t=e&&e.length;if(!t)return null;for(var n={},s=0;s<t;s++){var i=e[s],o=i.name,a=i.value;"on"===o.substring(0,2)&&r.options.allowEvents&&(a=new Function(a)),n[o]=a}return n}(e.attributes),(l=(a=e.childNodes)&&Array.prototype.map.call(a,r).filter(c))&&l.length?l:null);return r.visitor&&r.visitor(u),u}function s(e){var t=(e.type||"").toLowerCase(),n=s.map;n&&n.hasOwnProperty(t)?(e.type=n[t],e.props=Object.keys(e.props||{}).reduce((function(t,n){var r;return t[(r=n,r.replace(/-(.)/g,(function(e,t){return t.toUpperCase()})))]=e.props[n],t}),{})):e.type=t.replace(/[^a-z0-9-]/i,"")}n.r(t);var i,o,a=n("hosL"),l={},c=function(e){return e},u={};t.default=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),(t.prototype=Object.create(e&&e.prototype)).constructor=t,t.setReviver=function(e){o=e},t.prototype.shouldComponentUpdate=function(e){var t=this.props;return e.wrap!==t.wrap||e.type!==t.type||e.markup!==t.markup},t.prototype.setComponents=function(e){if(this.map={},e)for(var t in e)if(e.hasOwnProperty(t)){var n=t.replace(/([A-Z]+)([A-Z][a-z0-9])|([a-z0-9]+)([A-Z])/g,"$1$3-$2$4").toLowerCase();this.map[n]=e[t]}},t.prototype.render=function(e){var t=e.wrap;void 0===t&&(t=!0);var n,c=e.type,p=e.markup,h=e.components,d=e.reviver,f=e.onError,g=e["allow-scripts"],m=e["allow-events"],_=e.trim,b=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&-1===t.indexOf(r)&&(n[r]=e[r]);return n}(e,["wrap","type","markup","components","reviver","onError","allow-scripts","allow-events","trim"]),y=d||this.reviver||this.constructor.prototype.reviver||o||a.h;this.setComponents(h);var v={allowScripts:g,allowEvents:m,trim:_};try{n=function(e,t,n,o,a){var c=function(e,t){var n,r,s,o,a="html"===t?"text/html":"application/xml";"html"===t?(o="body",s="<!DOCTYPE html>\n<html><body>"+e+"</body></html>"):(o="xml",s='<?xml version="1.0" encoding="UTF-8"?>\n<xml>'+e+"</xml>");try{n=(new DOMParser).parseFromString(s,a)}catch(e){r=e}if(n||"html"!==t||((n=i||(i=function(){if(document.implementation&&document.implementation.createHTMLDocument)return document.implementation.createHTMLDocument("");var e=document.createElement("iframe");return e.style.cssText="position:absolute; left:0; top:-999em; width:1px; height:1px; overflow:hidden;",e.setAttribute("sandbox","allow-forms"),document.body.appendChild(e),e.contentWindow.document}())).open(),n.write(s),n.close()),n){var l=n.getElementsByTagName(o)[0],c=l.firstChild;return e&&!c&&(l.error="Document parse failed."),c&&"parsererror"===String(c.nodeName).toLowerCase()&&(c.removeChild(c.firstChild),c.removeChild(c.lastChild),l.error=c.textContent||c.nodeValue||r||"Unknown error",l.removeChild(c)),l}}(e,t);if(c&&c.error)throw new Error(c.error);var p=c&&c.body||c;s.map=o||u;var h=p&&function(e,t,n,s){return r.visitor=t,r.h=n,r.options=s||l,r(e)}(p,s,n,a);return s.map=null,h&&h.props&&h.props.children||null}(p,c,y,this.map,v)}catch(e){f?f({error:e}):"undefined"!=typeof console&&console.error&&console.error("preact-markup: "+e)}if(!1===t)return n||null;var k=b.hasOwnProperty("className")?"className":"class",O=b[k];return O?O.splice?O.splice(0,0,"markup"):"string"==typeof O?b[k]+=" markup":"object"==typeof O&&(O.markup=!0):b[k]="markup",y("div",b,n||null)},t}(a.Component)},RoC8:function(e){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},THQi:function(e){"use strict";function t(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,i,o,a){return i=i||"&",o=o||"=",null===e&&(e=void 0),"object"==typeof e?t(s(e),(function(s){var a=encodeURIComponent(n(s))+o;return r(e[s])?t(e[s],(function(e){return a+encodeURIComponent(n(e))})).join(i):a+encodeURIComponent(n(e[s]))})).join(i):a?encodeURIComponent(n(a))+o+encodeURIComponent(n(e)):""};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},UKnr:function(e,t,n){"use strict";t.decode=t.parse=n("MNOf"),t.encode=t.stringify=n("THQi")},Utv1:function(e,t,n){"use strict";function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(){return(o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var a=n("UKnr"),l=n.n(a),c=n("jpFG"),u=n.n(c);const p="loadingProgress",h="errorMessage";var d={publish:(e,t)=>{u.a.publish(e,t)},subscribe:(e,t)=>{u.a.subscribe(e,((e,n)=>{t(n)}))}};const f="apiServer",g="imageServer",m="jwtToken",_="userEmail",b=/Mac/.test(navigator.platform);class y{static getType(e){return Object.prototype.toString.call(e)}static isError(e){return"[object Error]"===y.getType(e)}static isArray(e){return"[object Array]"===y.getType(e)}static isObject(e){return"[object Object]"===y.getType(e)}static isString(e){return"[object String]"===y.getType(e)}static isDate(e){return"[object Date]"===y.getType(e)}static isNumber(e){return"[object Number]"===y.getType(e)&&!Number.isNaN(e)}static isFunction(e){return"[object Function]"===y.getType(e)}static isRegexp(e){return"[object RegExp]"===y.getType(e)}static isBoolean(e){return"[object Boolean]"===y.getType(e)}static isNull(e){return"[object Null]"===y.getType(e)}static isUndefined(e){return"[object Undefined]"===y.getType(e)}static isDefined(e){return!y.isUndefined(e)}static checkNested(e,...t){let n=e;for(let e=0;e<t.length;e+=1){if(!n||!n.hasOwnProperty(t[e]))return!1;n=n[t[e]]}return!0}static getNestedValue(e,t){let n=e;return t.split(".").forEach((e=>{y.isObject(n)&&void 0!==n[e]||(n=null),n&&(n=n[e])})),n}static setNestedValue(e,t,n){return"string"==typeof t?y.setNestedValue(e,t.split("."),n):1===t.length&&void 0!==n?(y.isObject(e)||(e={}),e[t[0]]=n):0===t.length?e:y.setNestedValue(e[t[0]],t.slice(1),n)}static asNumber(e,...t){let n=t;Array.isArray(n[0])&&(n=n[0]);let r=e;for(let e=0;e<n.length;e+=1){if(!r||!r.hasOwnProperty(n[e]))return 0;r=r[n[e]]}return parseFloat(r)}static asString(e,...t){let n=t;Array.isArray(n[0])&&(n=n[0]);let r=e;for(let e=0;e<n.length;e+=1){if(!r||!r.hasOwnProperty(n[e]))return;r=r[n[e]]}return r}static asObject(e,...t){let n=t;Array.isArray(n[0])&&(n=n[0]);let r=e;for(let e=0;e<n.length;e+=1){if(!r||!r.hasOwnProperty(n[e]))return;r=r[n[e]]}if("object"==typeof r)return r}static asBoolean(e,...t){let n=t;Array.isArray(n[0])&&(n=n[0]);let r=e;for(let e=0;e<n.length;e+=1){if(!r||!r.hasOwnProperty(n[e]))return!1;r=r[n[e]]}return"boolean"==typeof r&&r}static cleanObject(e,t={}){const n=o({},e),r=Object.keys(n);for(let e=0;e<r.length;e+=1){const s=r[e];n.hasOwnProperty(s)&&(void 0!==n[s]&&!1!==n[s]||delete n[s],t.emptyIsUndefined&&""===n[s]&&delete n[s],t.zeroIsUndefined&&0===n[s]&&delete n[s],t.zeroStringIsUndefined&&"0"===n[s]&&delete n[s],t.nullIsUndefined&&null===n[s]&&delete n[s])}return n}static escapeEmail(e){return"string"==typeof e?e.replace(/[^a-z1-9]/g,"_"):e}static padDate(e){let t=String(e);return 1===t.length&&(t=`0${t}`),t}static parseInputDate(e){let t;return y.isDate(e)?e:(y.isString(e)||y.isNumber(e)?e>1e9&&e<9999999999?(t=new Date(0),t.setUTCSeconds(e)):e>1e12&&e<9999999999999?(t=new Date(0),t.setUTCSeconds(parseInt(e/1e3,10))):y.isString(e)&&e.match(/\d{4}-\d{2}-\d{2}/)&&(t=new Date(e)):t=new Date,t)}static isoDate(e,t=!1,n=!1,r=!1){const s=y.parseInputDate(e);if(s){const e=s.getMonth()+1,i=s.getDate(),o=s.getFullYear(),a=s.getHours(),l=s.getMinutes(),c=s.getSeconds(),u=-s.getTimezoneOffset(),p=u>=0?"+":"-";let h=`${y.padDate(o)}-${y.padDate(e)}-${y.padDate(i)}`;return r||(h+=` ${y.padDate(a)}:${y.padDate(l)}`,t&&(h+=`:${y.padDate(c)}`),n&&(h+=`${p}${u}`)),h}return"n/a"}static isoTime(e,t=!1,n=!1){const r=y.parseInputDate(e);if(r){const e=r.getHours(),s=r.getMinutes(),i=r.getSeconds(),o=-r.getTimezoneOffset(),a=o>=0?"+":"-";let l=`${y.padDate(e)}:${y.padDate(s)}`;return t&&(l+=`:${y.padDate(i)}`),n&&(l+=`${a}${o}`),l}return"n/a"}static formatDate(e,t={}){const n=s({},t),r=n.locale||"en-US";delete n.locale;const i=s({year:"numeric",month:"short",day:"numeric"},n);return(y.isDate(e)?e:new Date(e)).toLocaleString(r,i)}static getApiServer(){return localStorage.getItem(f)}static setApiServer(e){return localStorage.setItem(f,e)}static getImageServer(){return localStorage.getItem(g)}static setImageServer(e){return localStorage.setItem(g,e)}static getJwtToken(){return localStorage.getItem(m)}static setJwtToken(e){return localStorage.setItem(m,e)}static removeJwtToken(){return localStorage.removeItem(m)}static setUserEmail(e){return localStorage.setItem(_,e)}static getUserEmail(){return localStorage.getItem(_)}static removeUserEmail(){return localStorage.removeItem(_)}static setObject(e,t,n){const r=localStorage.getItem(e);let i={};if("object"==typeof t)i=s({},t);else if("string"==typeof r)try{i=JSON.parse(r),i[t]=n}catch(e){i=void 0}return localStorage.setItem(e,JSON.stringify(i))}static unsetObj(e,t){return"string"==typeof t?y.setObject(e,t,null):localStorage.setItem(e,null)}static getObject(e){try{let t=JSON.parse(localStorage.getItem(e));return null===t&&(t={}),t}catch(e){return}}static set(e,t){return localStorage.setItem(e,JSON.stringify(t))}static unset(e){return localStorage.setItem(e,null)}static get(e){try{return JSON.parse(localStorage.getItem(e))}catch(e){return}}static async fetchApi(e,t={},n={}){const r=y.getApiServer(),i=!t.hasOwnProperty("publish")||t.publish;i&&d.publish(p,0);const o=y.getJwtToken(),a=s({credentials:"omit",method:"GET",mode:"cors",cache:"default",headers:{},publish:!0},t);o&&(a.headers={Authorization:`Bearer ${o}`});let c="";["POST","PUT","PATCH","DELETE"].includes(t.method)?(a.credentials="include",a.body=JSON.stringify(n),a.headers["Content-Type"]="application/json"):c=l.a.stringify(n),i&&d.publish(p,25);try{const t=await fetch(`${r}${e}${c?`?${c}`:""}`,a);return i&&d.publish(p,100),t.json()}catch(e){if(i)return d.publish(h,"An error occurred"),[];throw e}}static format(e,t,n,r,s=!1){const i=Number.isNaN(t)?2:Math.abs(t),o=void 0===n?",":n,a=void 0===r?" ":r,l=Math.abs(e||0),c=Math.sign(e)>=0?"":"-";if(s){if(l>999999){return`${c}${y.format(l/1e6,1,n,r)}M`}if(l>999){return`${c}${y.format(l/1e3,1,n,r)}K`}}if(y.isNumber(l)){const e=String(parseInt(l.toFixed(i),10)),t=e.length>3?e.length%3:0;return`${c}${t?e.substr(0,t)+a:""}${e.substr(t).replace(/(\d{3})(?=\d)/g,`$1${a}`)}${i?o+Math.abs(l-e).toFixed(i).slice(2):""}`}return""}static formatCompact(e){return y.format(e,0,","," ",!0)}static formatBytes(e,t){const n=parseInt(e,10);if(y.isNumber(n)){if(0===n)return"0 Bytes";const e=1024,r=t||2,s=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**i).toFixed(r))} ${s[i]}`}return""}static getDomain(){if(y.checkNested(window,"location"))return window.location.hostname}static isStandalone(){return!!window.navigator.standalone||!!window.matchMedia("(display-mode: standalone)").matches}static isMobile(){return[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i].some((e=>window.navigator.userAgent.match(e)))}static getImageHostname(){return y.getImageServer()}static getImageSrc(e,t="220x",n=1,r="product"){return"object"==typeof e?e.newFilename?`${t}/${e.newFilename}`:`${t}/${e.prefix||r}_${n}_${e.filename}.${e.ext}`:""}static isCapsLock(e,t=(()=>{})){let n=!1;const r=e.charCode,s=e.shiftKey;r>=97&&r<=122?n=s:!(r>=65&&r<=90)||s&&b||(n=!s),t(n)}static validateEmail(e){return/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}static ucfirst(e,t=!1){return e.charAt(0).toUpperCase()+(t?"":e.slice(1))}static randomPassword(){return Math.random().toString(36).slice(-8)}static toggleDarkModeClasses(e){e?(document.body.classList.remove("bootstrap"),document.body.classList.add("bootstrap-dark")):(document.body.classList.remove("bootstrap-dark"),document.body.classList.add("bootstrap"))}static camelcasize(e){return e.replace(/-([a-z])/gi,((e,t)=>t.toUpperCase()))}static collectPropsFromElement(e,t={}){const n=e.attributes,r=o({},t);return Object.keys(n).forEach((e=>{if(n.hasOwnProperty(e)){const t=n[e].name;if(!t||"string"!=typeof t)return!1;let s=t.split(/(data-props?-)/).pop()||"";if(s=y.camelcasize(s),t!==s){r[s]=n[e].nodeValue}}return!1})),[].forEach.call(e.getElementsByTagName("script"),(e=>{let t={};if(e.hasAttribute("type")){if("text/props"!==e.getAttribute("type")&&"application/json"!==e.getAttribute("type"))return;try{t=JSON.parse(e.innerHTML)}catch(e){throw new Error(e)}o(r,t)}})),r}static encUri(e){return"string"==typeof e?encodeURIComponent(e.replace(/\s*\(.+?\)/g,"")):e}static makeId(e){let t="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length;for(let s=0;s<e;s+=1)t+=n.charAt(Math.floor(Math.random()*r));return t}static percentOfTotal(e,t){return t/e*100}static round(e,t=1){if(!`${e}`.includes("e"))return+`${Math.round(`${e}e+${t}`)}e-${t}`;const n=`${e}`.split("e");let r="";return+n[1]+t>0&&(r="+"),+`${Math.round(`${+n[0]}e${r}${+n[1]+t}`)}e-${t}`}static roundTo(e,t=100){return Math.round((e+Number.EPSILON)*t)/t}static range(e,t,n=1){const r=[];let s=e;for(;s<=t;)r.push(s),s+=n;return r}static monthRange(e,t){const n=y.parseInputDate(e),r=y.parseInputDate(t),s=n.getFullYear(),i=r.getFullYear(),o=[];for(let e=s;e<=i;e+=1){const t=e!==i?11:r.getMonth();for(let r=e===s?n.getMonth():0;r<=t;r+=1){o.push({month:r+1,year:e})}}return o}static weekRange(e,t){const n=y.parseInputDate(e),r=y.parseInputDate(t),s=n.getFullYear(),i=r.getFullYear(),o=[];for(let e=s;e<=i;e+=1){const t=e!==i?y.getWeeksInYear(e):y.getWeek(r);for(let r=e===s?y.getWeek(n):1;r<=t;r+=1)o.push({week:r,year:e})}return o}static dayRange(e,t){const n=y.parseInputDate(e),r=y.parseInputDate(t),s=[];for(let e=n;e<=r;e.setDate(e.getDate()+1)){const t=new Date(e);s.push({year:t.getFullYear(),week:y.getWeek(t),day:t.getDate(),month:t.getMonth()+1})}return s}static scorePassword(e){let t=0;if(!e)return t;const n={};for(let r=0;r<e.length;r+=1)n[e[r]]=(n[e[r]]||0)+1,t+=5/n[e[r]];const r={digits:/\d/.test(e),lower:/[a-z]/.test(e),upper:/[A-Z]/.test(e),nonWords:/\W/.test(e)};let s=0;const i=Object.keys(r);for(let e=0,t=i.length;e<t;e+=1){s+=!0===r[i[e]]?1:0}return t+=10*(s-1),parseInt(t,10)}static checkPassStrength(e,t=["veryweek","weak","good","strong"]){const n=y.scorePassword(e);return n>80?t[3]:n>60?t[2]:n>=30?t[1]:n>=5?t[0]:""}static normalizeBetween(e,t,n,r,s,i){const o=r+(e-t)*(s-r)/(n-t);return i&&o>i?i:o}static validateCode(e,t,n){let r=`${e}`.replace(/[^0-9]/g,"");return r=parseInt(r,10),r>=t&&r<=n}static age(e,t=new Date,n={year:"år",month:"mnd",week:"uker",day:"dager"}){const r=y.parseInputDate(e),s=y.parseInputDate(t).getTime()-r.getTime(),i={},o={year:31536e3,month:2592e3,week:604800,day:86400,hour:3600,minute:60};let a=Math.floor(s/1e3);const l=Object.keys(o);for(let e=0,t=l.length;e<t;e+=1){const t=l[e];i[t]=Math.floor(a/o[t]),a-=i[t]*o[t]}for(let e=0,t=l.length;e<t;e+=1){const t=l[e];if(i[t]>0)return`${i[t]} ${n[t]||t}`}return i}static secToHms(e,t=!1){const n=parseInt(e,10),r=Math.floor(n/3600),s=Math.floor(n%3600/60),i=Math.floor(n%3600%60);return t?`${y.padDate(r)}:${y.padDate(s)}`:`${y.padDate(r)}:${y.padDate(s)}:${y.padDate(i)}`}static formatDistance(e,t=new Date,n){const r=y.parseInputDate(e),s=y.parseInputDate(t).getTime()-r.getTime(),i=Math.floor(s/1e3),o=Math.floor(i/60),a=Math.floor(i/3600),l=Math.floor(i/86400),c=Math.floor(l/7);return Math.floor(c/4)>0?y.formatDate(r,n):c>0?`${c}w`:l>0?`${l}d`:a>0?`${a}h`:o>0?`${o}m`:`${i}s`}static hsl2Rgb(e,t,n){const r=e/360,s=t/100,i=n/100;let o,a,l;if(0===s)o=i,a=i,l=i;else{const e=(e,t,n)=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e),t=i<.5?i*(1+s):i+s-i*s,n=2*i-t;o=e(n,t,r+1/3),a=e(n,t,r),l=e(n,t,r-1/3)}return{r:Math.round(255*o),g:Math.round(255*a),b:Math.round(255*l)}}static yearRange(e=1980,t=(new Date).getFullYear()){const n=[];let r=e;for(;r<=t;)n.push(r+=1);return n}static getYear(){return(new Date).getFullYear()}static getWeek(e){let t;t=y.isUndefined(e)?new Date:new Date(e),t.setHours(0,0,0,0),t.setDate(t.getDate()+3-(t.getDay()+6)%7);const n=new Date(t.getFullYear(),0,4),r=(t.getTime()-n.getTime())/864e5,s=(n.getDay()+6)%7;return 1+Math.round((r-3+s)/7)}static getDaysInWeek(e,t,n){const r=[],s=y.getDateOfISOWeek(e,t,n);r.push(s);for(let e=1;e<7;e+=1){const t=new Date(s.getTime());t.setDate(s.getDate()+e),r.push(t)}return r}static getDaysInRange(e,t=7,n=!1){const r=[],s=y.parseInputDate(e);s.setHours(0,0,0,0),r.push(s);const i=t<0?-1:1,o=Math.abs(t);for(let e=1;e<=o;e+=1){const t=new Date(s.getTime());t.setDate(s.getDate()+e*i),r.push(t)}return n?r.map((e=>({day:e.getDate(),month:e.getMonth()+1,year:e.getFullYear()}))):r}static daysInMonth(e,t){return new Date(t,e,0).getDate()}static getDaysInMonth(e,t){const n=y.daysInMonth(e,t),r=[],s=new Date(t,e-1,1);r.push(s);for(let e=1;e<n;e+=1){const t=new Date(s.getTime());t.setDate(s.getDate()+e),r.push(t)}return r}static getWeeksInMonth(e,t,n="monday"){const r=[],s=new Date(t,e-1,1),i=new Date(t,e,0).getDate();let o=1,a=7-s.getDay();for("monday"===n&&(a=0===s.getDay()?1:7-s.getDay()+1);o<=i;)r.push({start:o,end:a,week:y.getWeek(new Date(s.getFullYear(),s.getMonth(),o))}),o=a+1,a+=7,a=1===o&&8===a?1:a,a>i&&(a=i);return r}static getWeeksInYear(e=(new Date).getFullYear()){return Math.max(y.getWeek(`${e}-12-31`),y.getWeek(`${e}-12-24`))}static getFirstWeekInYear(e=(new Date).getFullYear()){return y.getWeek(`${e}-01-01`)}static getDateOfWeek(e,t){return new Date(t,0,1+7*(e-1))}static getDateOfISOWeek(e,t,n){let r=parseInt(t,10);const s=parseInt(n,10),i=parseInt(e,10);1===s&&53===i&&(r-=1);const o=new Date(r,0,1+7*(i-1)),a=o.getDay(),l=o;return l.setDate(a<=4?o.getDate()-o.getDay()+1:o.getDate()+8-o.getDay()),l}static addDays(e,t){const n=new Date(e);return n.setDate(n.getDate()+t),n}}t.a=y},WNjl:function(e,t,n){function r(e,t,n){if(null==e)throw new Error("marked(): input parameter is undefined or null");if("string"!=typeof e)throw new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected");if(n||"function"==typeof t){n||(n=t,t=null),t=u({},r.defaults,t||{}),p(t);const o=t.highlight;let a,l,c=0;try{a=s.lex(e,t)}catch(e){return n(e)}l=a.length;const h=function(e){if(e)return t.highlight=o,n(e);let r;try{r=i.parse(a,t)}catch(t){e=t}return t.highlight=o,e?n(e):n(null,r)};if(!o||o.length<3)return h();if(delete t.highlight,!l)return h();for(;c<a.length;c++)!function(e){"code"!==e.type?--l||h():o(e.text,e.lang,(function(t,n){return t?h(t):null==n||n===e.text?--l||h():(e.text=n,e.escaped=!0,void(--l||h()))}))}(a[c])}else try{return t=u({},r.defaults,t||{}),p(t),i.parse(s.lex(e,t),t)}catch(e){if(e.message+="\nPlease report this to https://github.com/markedjs/marked.",(t||r.defaults).silent)return"<p>An error occurred:</p><pre>"+h(e.message+"",!0)+"</pre>";throw e}}const s=n("5y6D"),i=n("Kx7A"),o=n("ffMB"),a=n("F2rU"),l=n("/IQw"),c=n("0G4o"),{merge:u,checkSanitizeDeprecation:p,escape:h}=n("AkNA"),{getDefaults:d,changeDefaults:f,defaults:g}=n("bixo");r.options=r.setOptions=function(e){return u(r.defaults,e),f(r.defaults),r},r.getDefaults=d,r.defaults=g,r.Parser=i,r.parser=i.parse,r.Renderer=o,r.TextRenderer=a,r.Lexer=s,r.lexer=s.lex,r.InlineLexer=l,r.inlineLexer=l.output,r.Slugger=c,r.parse=r,e.exports=r},bixo:function(e){function t(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,xhtml:!1}}e.exports={defaults:{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,xhtml:!1},getDefaults:t,changeDefaults:function(t){e.exports.defaults=t}}},ffMB:function(e,t,n){const{defaults:r}=n("bixo"),{cleanUrl:s,escape:i}=n("AkNA");e.exports=class{constructor(e){this.options=e||r}code(e,t,n){const r=(t||"").match(/\S*/)[0];if(this.options.highlight){const t=this.options.highlight(e,r);null!=t&&t!==e&&(n=!0,e=t)}return r?'<pre><code class="'+this.options.langPrefix+i(r,!0)+'">'+(n?e:i(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:i(e,!0))+"</code></pre>"}blockquote(e){return"<blockquote>\n"+e+"</blockquote>\n"}html(e){return e}heading(e,t,n,r){return this.options.headerIds?"<h"+t+' id="'+this.options.headerPrefix+r.slug(n)+'">'+e+"</h"+t+">\n":"<h"+t+">"+e+"</h"+t+">\n"}hr(){return this.options.xhtml?"<hr/>\n":"<hr>\n"}list(e,t,n){const r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+r+">\n"}listitem(e){return"<li>"+e+"</li>\n"}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"'+(this.options.xhtml?" /":"")+"> "}paragraph(e){return"<p>"+e+"</p>\n"}table(e,t){return t&&(t="<tbody>"+t+"</tbody>"),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablerow(e){return"<tr>\n"+e+"</tr>\n"}tablecell(e,t){const n=t.header?"th":"td";return(t.align?"<"+n+' align="'+t.align+'">':"<"+n+">")+e+"</"+n+">\n"}strong(e){return"<strong>"+e+"</strong>"}em(e){return"<em>"+e+"</em>"}codespan(e){return"<code>"+e+"</code>"}br(){return this.options.xhtml?"<br/>":"<br>"}del(e){return"<del>"+e+"</del>"}link(e,t,n){if(null===(e=s(this.options.sanitize,this.options.baseUrl,e)))return n;let r='<a href="'+i(e)+'"';return t&&(r+=' title="'+t+'"'),r+=">"+n+"</a>",r}image(e,t,n){if(null===(e=s(this.options.sanitize,this.options.baseUrl,e)))return n;let r='<img src="'+e+'" alt="'+n+'"';return t&&(r+=' title="'+t+'"'),r+=this.options.xhtml?"/>":">",r}text(e){return e}}},fh8t:function(e,t,n){function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}const s=n("hosL"),i=n("RlRQ").default,o=n("WNjl");e.exports=function(e,t){const n=(t=t||{}).h||s.h;let a;if("string"==typeof e)a=e,e={};else{if(!e||"string"!=typeof e.markdown)throw new Error("Invalid arguments. Markdown requires either a `<String>` or object: `{markdown: <String>}`");a=e.markdown}const l=e.markupOpts||t.markupOpts||{};return n(i,r({markup:o(a,e.markdownOpts||t.markdownOpts||{}),trim:!1,type:"html"},l))}},hosL:function(e,t,n){"use strict";function r(e,t){for(var n in t)e[n]=t[n];return e}function s(e){var t=e.parentNode;t&&t.removeChild(e)}function i(e,t,n){var r,s,i,a={};for(i in t)"key"==i?r=t[i]:"ref"==i?s=t[i]:a[i]=t[i];if(arguments.length>2&&(a.children=arguments.length>3?C.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===a[i]&&(a[i]=e.defaultProps[i]);return o(e,a,r,s,null)}function o(e,t,n,r,s){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==s?++E:s};return null!=T.vnode&&T.vnode(i),i}function a(){return{current:null}}function l(e){return e.children}function c(e,t){this.props=e,this.context=t}function u(e,t){if(null==t)return e.__?u(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?u(e):null}function p(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return p(e)}}function h(e){(!e.__d&&(e.__d=!0)&&L.push(e)&&!d.__r++||R!==T.debounceRendering)&&((R=T.debounceRendering)||z)(d)}function d(){for(var e;d.__r=L.length;)e=L.sort((function(e,t){return e.__v.__b-t.__v.__b})),L=[],e.some((function(e){var t,n,s,i,o,a;e.__d&&(o=(i=(t=e).__v).__e,(a=t.__P)&&(n=[],(s=r({},i)).__v=i.__v+1,O(a,i,s,t.__n,void 0!==a.ownerSVGElement,null!=i.__h?[o]:null,n,null==o?u(i):o,i.__h),w(n,i),i.__e!=o&&p(i)))}))}function f(e,t,n,r,s,i,a,c,p,h){var d,f,m,b,y,v,k,w=r&&r.__k||F,x=w.length;for(n.__k=[],d=0;d<t.length;d++)if(null!=(b=n.__k[d]=null==(b=t[d])||"boolean"==typeof b?null:"string"==typeof b||"number"==typeof b||"bigint"==typeof b?o(null,b,null,null,b):Array.isArray(b)?o(l,{children:b},null,null,null):b.__b>0?o(b.type,b.props,b.key,null,b.__v):b)){if(b.__=n,b.__b=n.__b+1,null===(m=w[d])||m&&b.key==m.key&&b.type===m.type)w[d]=void 0;else for(f=0;f<x;f++){if((m=w[f])&&b.key==m.key&&b.type===m.type){w[f]=void 0;break}m=null}O(e,b,m=m||U,s,i,a,c,p,h),y=b.__e,(f=b.ref)&&m.ref!=f&&(k||(k=[]),m.ref&&k.push(m.ref,null,b),k.push(f,b.__c||y,b)),null!=y?(null==v&&(v=y),"function"==typeof b.type&&null!=b.__k&&b.__k===m.__k?b.__d=p=g(b,p,e):p=_(e,b,m,w,y,p),h||"option"!==n.type?"function"==typeof n.type&&(n.__d=p):e.value=""):p&&m.__e==p&&p.parentNode!=e&&(p=u(m))}for(n.__e=v,d=x;d--;)null!=w[d]&&("function"==typeof n.type&&null!=w[d].__e&&w[d].__e==n.__d&&(n.__d=u(r,d+1)),$(w[d],w[d]));if(k)for(d=0;d<k.length;d++)j(k[d],k[++d],k[++d])}function g(e,t,n){var r,s;for(r=0;r<e.__k.length;r++)(s=e.__k[r])&&(s.__=e,t="function"==typeof s.type?g(s,t,n):_(n,s,s,e.__k,s.__e,t));return t}function m(e,t){return t=t||[],null==e||"boolean"==typeof e||(Array.isArray(e)?e.some((function(e){m(e,t)})):t.push(e)),t}function _(e,t,n,r,s,i){var o,a,l;if(void 0!==t.__d)o=t.__d,t.__d=void 0;else if(null==n||s!=i||null==s.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(s),o=null;else{for(a=i,l=0;(a=a.nextSibling)&&l<r.length;l+=2)if(a==s)break e;e.insertBefore(s,i),o=i}return void 0!==o?o:s.nextSibling}function b(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||H.test(t)?n:n+"px"}function y(e,t,n,r,s){var i;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||b(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||b(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?k:v,i):e.removeEventListener(t,i?k:v,i);else if("dangerouslySetInnerHTML"!==t){if(s)t=t.replace(/xlink[H:h]/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function v(e){this.l[e.type+!1](T.event?T.event(e):e)}function k(e){this.l[e.type+!0](T.event?T.event(e):e)}function O(e,t,n,s,i,o,a,u,p){var h,d,g,m,_,b,y,v,k,O,w,j=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(p=n.__h,u=t.__e=n.__e,t.__h=null,o=[u]),(h=T.__b)&&h(t);try{e:if("function"==typeof j){if(v=t.props,k=(h=j.contextType)&&s[h.__c],O=h?k?k.props.value:h.__:s,n.__c?y=(d=t.__c=n.__c).__=d.__E:("prototype"in j&&j.prototype.render?t.__c=d=new j(v,O):(t.__c=d=new c(v,O),d.constructor=j,d.render=S),k&&k.sub(d),d.props=v,d.state||(d.state={}),d.context=O,d.__n=s,g=d.__d=!0,d.__h=[]),null==d.__s&&(d.__s=d.state),null!=j.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=r({},d.__s)),r(d.__s,j.getDerivedStateFromProps(v,d.__s))),m=d.props,_=d.state,g)null==j.getDerivedStateFromProps&&null!=d.componentWillMount&&d.componentWillMount(),null!=d.componentDidMount&&d.__h.push(d.componentDidMount);else{if(null==j.getDerivedStateFromProps&&v!==m&&null!=d.componentWillReceiveProps&&d.componentWillReceiveProps(v,O),!d.__e&&null!=d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(v,d.__s,O)||t.__v===n.__v){d.props=v,d.state=d.__s,t.__v!==n.__v&&(d.__d=!1),d.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),d.__h.length&&a.push(d);break e}null!=d.componentWillUpdate&&d.componentWillUpdate(v,d.__s,O),null!=d.componentDidUpdate&&d.__h.push((function(){d.componentDidUpdate(m,_,b)}))}d.context=O,d.props=v,d.state=d.__s,(h=T.__r)&&h(t),d.__d=!1,d.__v=t,d.__P=e,h=d.render(d.props,d.state,d.context),d.state=d.__s,null!=d.getChildContext&&(s=r(r({},s),d.getChildContext())),g||null==d.getSnapshotBeforeUpdate||(b=d.getSnapshotBeforeUpdate(m,_)),w=null!=h&&h.type===l&&null==h.key?h.props.children:h,f(e,Array.isArray(w)?w:[w],t,n,s,i,o,a,u,p),d.base=t.__e,t.__h=null,d.__h.length&&a.push(d),y&&(d.__E=d.__=null),d.__e=!1}else null==o&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=x(n.__e,t,n,s,i,o,a,p);(h=T.diffed)&&h(t)}catch(e){t.__v=null,(p||null!=o)&&(t.__e=u,t.__h=!!p,o[o.indexOf(u)]=null),T.__e(e,t,n)}}function w(e,t){T.__c&&T.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){T.__e(e,t.__v)}}))}function x(e,t,n,r,i,o,a,l){var c,p,h,d=n.props,g=t.props,m=t.type,_=0;if("svg"===m&&(i=!0),null!=o)for(;_<o.length;_++)if((c=o[_])&&(c===e||(m?c.localName==m:3==c.nodeType))){e=c,o[_]=null;break}if(null==e){if(null===m)return document.createTextNode(g);e=i?document.createElementNS("http://www.w3.org/2000/svg",m):document.createElement(m,g.is&&g),o=null,l=!1}if(null===m)d===g||l&&e.data===g||(e.data=g);else{if(o=o&&C.call(e.childNodes),p=(d=n.props||U).dangerouslySetInnerHTML,h=g.dangerouslySetInnerHTML,!l){if(null!=o)for(d={},_=0;_<e.attributes.length;_++)d[e.attributes[_].name]=e.attributes[_].value;(h||p)&&(h&&(p&&h.__html==p.__html||h.__html===e.innerHTML)||(e.innerHTML=h&&h.__html||""))}if(function(e,t,n,r,s){var i;for(i in n)"children"===i||"key"===i||i in t||y(e,i,null,n[i],r);for(i in t)s&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||y(e,i,t[i],n[i],r)}(e,g,d,i,l),h)t.__k=[];else if(_=t.props.children,f(e,Array.isArray(_)?_:[_],t,n,r,i&&"foreignObject"!==m,o,a,o?o[0]:n.__k&&u(n,0),l),null!=o)for(_=o.length;_--;)null!=o[_]&&s(o[_]);l||("value"in g&&void 0!==(_=g.value)&&(_!==e.value||"progress"===m&&!_)&&y(e,"value",_,d.value,!1),"checked"in g&&void 0!==(_=g.checked)&&_!==e.checked&&y(e,"checked",_,d.checked,!1))}return e}function j(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){T.__e(e,n)}}function $(e,t,n){var r,i;if(T.unmount&&T.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||j(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){T.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&$(r[i],t,"function"!=typeof e.type);n||null==e.__e||s(e.__e),e.__e=e.__d=void 0}function S(e,t,n){return this.constructor(e,n)}function D(e,t,n){var r,s,o;T.__&&T.__(e,t),s=(r="function"==typeof n)?null:n&&n.__k||t.__k,o=[],O(t,e=(!r&&n||t).__k=i(l,null,[e]),s||U,U,void 0!==t.ownerSVGElement,!r&&n?[n]:s?null:t.firstChild?C.call(t.childNodes):null,o,!r&&n?n:s?s.__e:t.firstChild,r),w(o,e)}function A(e,t){D(e,t,A)}function I(e,t,n){var s,i,a,l=r({},e.props);for(a in t)"key"==a?s=t[a]:"ref"==a?i=t[a]:l[a]=t[a];return arguments.length>2&&(l.children=arguments.length>3?C.call(arguments,2):n),o(e.type,l,s||e.key,i||e.ref,null)}function P(e,t){var n={__c:t="__cC"+N++,__:e,Consumer:function(e,t){return e.children(t)},Provider:function(e){var n,r;return this.getChildContext||(n=[],(r={})[t]=this,this.getChildContext=function(){return r},this.shouldComponentUpdate=function(e){this.props.value!==e.value&&n.some(h)},this.sub=function(e){n.push(e);var t=e.componentWillUnmount;e.componentWillUnmount=function(){n.splice(n.indexOf(e),1),t&&t.call(e)}}),e.children}};return n.Provider.__=n.Consumer.contextType=n}n.r(t),n.d(t,"render",(function(){return D})),n.d(t,"hydrate",(function(){return A})),n.d(t,"createElement",(function(){return i})),n.d(t,"h",(function(){return i})),n.d(t,"Fragment",(function(){return l})),n.d(t,"createRef",(function(){return a})),n.d(t,"isValidElement",(function(){return M})),n.d(t,"Component",(function(){return c})),n.d(t,"cloneElement",(function(){return I})),n.d(t,"createContext",(function(){return P})),n.d(t,"toChildArray",(function(){return m})),n.d(t,"options",(function(){return T}));var C,T,E,M,L,z,R,N,U={},F=[],H=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;C=F.slice,T={__e:function(e,t){for(var n,r,s;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&null!=r.getDerivedStateFromError&&(n.setState(r.getDerivedStateFromError(e)),s=n.__d),null!=n.componentDidCatch&&(n.componentDidCatch(e),s=n.__d),s)return n.__E=n}catch(t){e=t}throw e}},E=0,M=function(e){return null!=e&&void 0===e.constructor},c.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=r({},this.state),"function"==typeof e&&(e=e(r({},n),this.props)),e&&r(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),h(this))},c.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),h(this))},c.prototype.render=l,L=[],z="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,d.__r=0,N=0},jpFG:function(e,t,n){(function(e){!function(n){"use strict";var r={};n.PubSub=r,function(e){function t(e){var t;for(t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}function n(e){return function(){throw e}}function r(e,t,r){try{e(t,r)}catch(e){setTimeout(n(e),0)}}function s(e,t,n){e(t,n)}function i(e,t,n,i){var o,a=u[t],l=i?s:r;if(Object.prototype.hasOwnProperty.call(u,t))for(o in a)Object.prototype.hasOwnProperty.call(a,o)&&l(a[o],e,n)}function o(e,t,n){return function(){var r=String(e),s=r.lastIndexOf(".");for(i(e,e,t,n);-1!==s;)s=(r=r.substr(0,s)).lastIndexOf("."),i(e,r,t,n);i(e,h,t,n)}}function a(e){var n=String(e);return Boolean(Object.prototype.hasOwnProperty.call(u,n)&&t(u[n]))}function l(e){for(var t=String(e),n=a(t)||a(h),r=t.lastIndexOf(".");!n&&-1!==r;)r=(t=t.substr(0,r)).lastIndexOf("."),n=a(t);return n}function c(e,t,n,r){var s=o(e="symbol"==typeof e?e.toString():e,t,r);return!!l(e)&&(!0===n?s():setTimeout(s,0),!0)}var u={},p=-1,h="*";e.publish=function(t,n){return c(t,n,!1,e.immediateExceptions)},e.publishSync=function(t,n){return c(t,n,!0,e.immediateExceptions)},e.subscribe=function(e,t){if("function"!=typeof t)return!1;e="symbol"==typeof e?e.toString():e,Object.prototype.hasOwnProperty.call(u,e)||(u[e]={});var n="uid_"+String(++p);return u[e][n]=t,n},e.subscribeAll=function(t){return e.subscribe(h,t)},e.subscribeOnce=function(t,n){var r=e.subscribe(t,(function(){e.unsubscribe(r),n.apply(this,arguments)}));return e},e.clearAllSubscriptions=function(){u={}},e.clearSubscriptions=function(e){var t;for(t in u)Object.prototype.hasOwnProperty.call(u,t)&&0===t.indexOf(e)&&delete u[t]},e.countSubscriptions=function(e){var t,n,r=0;for(t in u)if(Object.prototype.hasOwnProperty.call(u,t)&&0===t.indexOf(e)){for(n in u[t])r++;break}return r},e.getSubscriptions=function(e){var t,n=[];for(t in u)Object.prototype.hasOwnProperty.call(u,t)&&0===t.indexOf(e)&&n.push(t);return n},e.unsubscribe=function(t){var n,r,s,i=function(e){var t;for(t in u)if(Object.prototype.hasOwnProperty.call(u,t)&&0===t.indexOf(e))return!0;return!1},o="string"==typeof t&&(Object.prototype.hasOwnProperty.call(u,t)||i(t)),a=!o&&"string"==typeof t,l="function"==typeof t,c=!1;if(!o){for(n in u)if(Object.prototype.hasOwnProperty.call(u,n)){if(r=u[n],a&&r[t]){delete r[t],c=t;break}if(l)for(s in r)Object.prototype.hasOwnProperty.call(r,s)&&r[s]===t&&(delete r[s],c=!0)}return c}e.clearSubscriptions(t)}}(r),void 0!==e&&e.exports&&(t=e.exports=r),t.PubSub=r,e.exports=t=r}("object"==typeof window&&window||this)}).call(this,n("RoC8")(e))},mdyV:function(e,t,n){"use strict";n.r(t);var r=n("hosL");const{h:s,render:i,hydrate:o}=r,a=e=>e&&e.default?e.default:e;if("function"==typeof a(n("QfWi"))){let e=document.getElementById("preact_root")||document.body.firstElementChild;0,(()=>{let t=a(n("QfWi")),r={};const o=document.querySelector('[type="__PREACT_CLI_DATA__"]');o&&(r=JSON.parse(decodeURI(o.innerHTML)).preRenderData||r);r.url&&(l=r.url);var l;e=i(s(t,{CLI_DATA:{preRenderData:r}}),document.body,e)})()}}}); //# sourceMappingURL=bundle.9ee2a.esm.js.map
/*! * jQuery JavaScript Library v1.11.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:42Z */ !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){function c(a){var b=a.length,c=eb.type(a);return"function"===c||eb.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}function d(a,b,c){if(eb.isFunction(b))return eb.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return eb.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(mb.test(b))return eb.filter(b,a,c);b=eb.filter(b,a)}return eb.grep(a,function(a){return eb.inArray(a,b)>=0!==c})}function e(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}function f(a){var b=ub[a]={};return eb.each(a.match(tb)||[],function(a,c){b[c]=!0}),b}function g(){ob.addEventListener?(ob.removeEventListener("DOMContentLoaded",h,!1),a.removeEventListener("load",h,!1)):(ob.detachEvent("onreadystatechange",h),a.detachEvent("onload",h))}function h(){(ob.addEventListener||"load"===event.type||"complete"===ob.readyState)&&(g(),eb.ready())}function i(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(zb,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:yb.test(c)?eb.parseJSON(c):c}catch(e){}eb.data(a,b,c)}else c=void 0}return c}function j(a){var b;for(b in a)if(("data"!==b||!eb.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function k(a,b,c,d){if(eb.acceptData(a)){var e,f,g=eb.expando,h=a.nodeType,i=h?eb.cache:a,j=h?a[g]:a[g]&&g;if(j&&i[j]&&(d||i[j].data)||void 0!==c||"string"!=typeof b)return j||(j=h?a[g]=W.pop()||eb.guid++:g),i[j]||(i[j]=h?{}:{toJSON:eb.noop}),("object"==typeof b||"function"==typeof b)&&(d?i[j]=eb.extend(i[j],b):i[j].data=eb.extend(i[j].data,b)),f=i[j],d||(f.data||(f.data={}),f=f.data),void 0!==c&&(f[eb.camelCase(b)]=c),"string"==typeof b?(e=f[b],null==e&&(e=f[eb.camelCase(b)])):e=f,e}}function l(a,b,c){if(eb.acceptData(a)){var d,e,f=a.nodeType,g=f?eb.cache:a,h=f?a[eb.expando]:eb.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){eb.isArray(b)?b=b.concat(eb.map(b,eb.camelCase)):b in d?b=[b]:(b=eb.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;for(;e--;)delete d[b[e]];if(c?!j(d):!eb.isEmptyObject(d))return}(c||(delete g[h].data,j(g[h])))&&(f?eb.cleanData([a],!0):cb.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}function m(){return!0}function n(){return!1}function o(){try{return ob.activeElement}catch(a){}}function p(a){var b=Kb.split("|"),c=a.createDocumentFragment();if(c.createElement)for(;b.length;)c.createElement(b.pop());return c}function q(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==xb?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==xb?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||eb.nodeName(d,b)?f.push(d):eb.merge(f,q(d,b));return void 0===b||b&&eb.nodeName(a,b)?eb.merge([a],f):f}function r(a){Eb.test(a.type)&&(a.defaultChecked=a.checked)}function s(a,b){return eb.nodeName(a,"table")&&eb.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function t(a){return a.type=(null!==eb.find.attr(a,"type"))+"/"+a.type,a}function u(a){var b=Vb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function v(a,b){for(var c,d=0;null!=(c=a[d]);d++)eb._data(c,"globalEval",!b||eb._data(b[d],"globalEval"))}function w(a,b){if(1===b.nodeType&&eb.hasData(a)){var c,d,e,f=eb._data(a),g=eb._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++)eb.event.add(b,c,h[c][d])}g.data&&(g.data=eb.extend({},g.data))}}function x(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!cb.noCloneEvent&&b[eb.expando]){e=eb._data(b);for(d in e.events)eb.removeEvent(b,d,e.handle);b.removeAttribute(eb.expando)}"script"===c&&b.text!==a.text?(t(b).text=a.text,u(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),cb.html5Clone&&a.innerHTML&&!eb.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Eb.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)}}function y(b,c){var d,e=eb(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:eb.css(e[0],"display");return e.detach(),f}function z(a){var b=ob,c=_b[a];return c||(c=y(a,b),"none"!==c&&c||($b=($b||eb("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=($b[0].contentWindow||$b[0].contentDocument).document,b.write(),b.close(),c=y(a,b),$b.detach()),_b[a]=c),c}function A(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}function B(a,b){if(b in a)return b;for(var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=mc.length;e--;)if(b=mc[e]+c,b in a)return b;return d}function C(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=eb._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&Cb(d)&&(f[g]=eb._data(d,"olddisplay",z(d.nodeName)))):(e=Cb(d),(c&&"none"!==c||!e)&&eb._data(d,"olddisplay",e?c:eb.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 D(a,b,c){var d=ic.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function E(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+=eb.css(a,c+Bb[f],!0,e)),d?("content"===c&&(g-=eb.css(a,"padding"+Bb[f],!0,e)),"margin"!==c&&(g-=eb.css(a,"border"+Bb[f]+"Width",!0,e))):(g+=eb.css(a,"padding"+Bb[f],!0,e),"padding"!==c&&(g+=eb.css(a,"border"+Bb[f]+"Width",!0,e)));return g}function F(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=ac(a),g=cb.boxSizing&&"border-box"===eb.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=bc(a,b,f),(0>e||null==e)&&(e=a.style[b]),dc.test(e))return e;d=g&&(cb.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+E(a,b,c||(g?"border":"content"),d,f)+"px"}function G(a,b,c,d,e){return new G.prototype.init(a,b,c,d,e)}function H(){return setTimeout(function(){nc=void 0}),nc=eb.now()}function I(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=Bb[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function J(a,b,c){for(var d,e=(tc[b]||[]).concat(tc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function K(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},n=a.style,o=a.nodeType&&Cb(a),p=eb._data(a,"fxshow");c.queue||(h=eb._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,eb.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[n.overflow,n.overflowX,n.overflowY],j=eb.css(a,"display"),k="none"===j?eb._data(a,"olddisplay")||z(a.nodeName):j,"inline"===k&&"none"===eb.css(a,"float")&&(cb.inlineBlockNeedsLayout&&"inline"!==z(a.nodeName)?n.zoom=1:n.display="inline-block")),c.overflow&&(n.overflow="hidden",cb.shrinkWrapBlocks()||l.always(function(){n.overflow=c.overflow[0],n.overflowX=c.overflow[1],n.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],pc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(o?"hide":"show")){if("show"!==e||!p||void 0===p[d])continue;o=!0}m[d]=p&&p[d]||eb.style(a,d)}else j=void 0;if(eb.isEmptyObject(m))"inline"===("none"===j?z(a.nodeName):j)&&(n.display=j);else{p?"hidden"in p&&(o=p.hidden):p=eb._data(a,"fxshow",{}),f&&(p.hidden=!o),o?eb(a).show():l.done(function(){eb(a).hide()}),l.done(function(){var b;eb._removeData(a,"fxshow");for(b in m)eb.style(a,b,m[b])});for(d in m)g=J(o?p[d]:0,d,l),d in p||(p[d]=g.start,o&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function L(a,b){var c,d,e,f,g;for(c in a)if(d=eb.camelCase(c),e=b[d],f=a[c],eb.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=eb.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 M(a,b,c){var d,e,f=0,g=sc.length,h=eb.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=nc||H(),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:eb.extend({},b),opts:eb.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:nc||H(),duration:c.duration,tweens:[],createTween:function(b,c){var d=eb.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(L(k,j.opts.specialEasing);g>f;f++)if(d=sc[f].call(j,a,k,j.opts))return d;return eb.map(k,J,j),eb.isFunction(j.opts.start)&&j.opts.start.call(a,j),eb.fx.timer(eb.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)}function N(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(tb)||[];if(eb.isFunction(c))for(;d=f[e++];)"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function O(a,b,c,d){function e(h){var i;return f[h]=!0,eb.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||g||f[j]?g?!(i=j):void 0:(b.dataTypes.unshift(j),e(j),!1)}),i}var f={},g=a===Rc;return e(b.dataTypes[0])||!f["*"]&&e("*")}function P(a,b){var c,d,e=eb.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&eb.extend(!0,a,c),a}function Q(a,b,c){for(var d,e,f,g,h=a.contents,i=a.dataTypes;"*"===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 R(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];for(f=k.shift();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}}function S(a,b,c,d){var e;if(eb.isArray(b))eb.each(b,function(b,e){c||Vc.test(a)?d(a,e):S(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==eb.type(b))d(a,b);else for(e in b)S(a+"["+e+"]",b[e],c,d)}function T(){try{return new a.XMLHttpRequest}catch(b){}}function U(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function V(a){return eb.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}var W=[],X=W.slice,Y=W.concat,Z=W.push,$=W.indexOf,_={},ab=_.toString,bb=_.hasOwnProperty,cb={},db="1.11.1",eb=function(a,b){return new eb.fn.init(a,b)},fb=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,gb=/^-ms-/,hb=/-([\da-z])/gi,ib=function(a,b){return b.toUpperCase()};eb.fn=eb.prototype={jquery:db,constructor:eb,selector:"",length:0,toArray:function(){return X.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:X.call(this)},pushStack:function(a){var b=eb.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return eb.each(this,a,b)},map:function(a){return this.pushStack(eb.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(X.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:Z,sort:W.sort,splice:W.splice},eb.extend=eb.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||eb.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&&(eb.isPlainObject(c)||(b=eb.isArray(c)))?(b?(b=!1,f=a&&eb.isArray(a)?a:[]):f=a&&eb.isPlainObject(a)?a:{},g[d]=eb.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},eb.extend({expando:"jQuery"+(db+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===eb.type(a)},isArray:Array.isArray||function(a){return"array"===eb.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!eb.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==eb.type(a)||a.nodeType||eb.isWindow(a))return!1;try{if(a.constructor&&!bb.call(a,"constructor")&&!bb.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(cb.ownLast)for(b in a)return bb.call(a,b);for(b in a);return void 0===b||bb.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?_[ab.call(a)]||"object":typeof a},globalEval:function(b){b&&eb.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(gb,"ms-").replace(hb,ib)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,d){var e,f=0,g=a.length,h=c(a);if(d){if(h)for(;g>f&&(e=b.apply(a[f],d),e!==!1);f++);else for(f in a)if(e=b.apply(a[f],d),e===!1)break}else if(h)for(;g>f&&(e=b.call(a[f],f,a[f]),e!==!1);f++);else for(f in a)if(e=b.call(a[f],f,a[f]),e===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(fb,"")},makeArray:function(a,b){var d=b||[];return null!=a&&(c(Object(a))?eb.merge(d,"string"==typeof a?[a]:a):Z.call(d,a)),d},inArray:function(a,b,c){var d;if(b){if($)return $.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){for(var c=+b.length,d=0,e=a.length;c>d;)a[e++]=b[d++];if(c!==c)for(;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,d){var e,f=0,g=a.length,h=c(a),i=[];if(h)for(;g>f;f++)e=b(a[f],f,d),null!=e&&i.push(e);else for(f in a)e=b(a[f],f,d),null!=e&&i.push(e);return Y.apply([],i)},guid:1,proxy:function(a,b){var c,d,e;return"string"==typeof b&&(e=a[b],b=a,a=e),eb.isFunction(a)?(c=X.call(arguments,2),d=function(){return a.apply(b||this,c.concat(X.call(arguments)))},d.guid=a.guid=a.guid||eb.guid++,d):void 0},now:function(){return+new Date},support:cb}),eb.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){_["[object "+b+"]"]=b.toLowerCase()});var jb=/*! * 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(a){function b(a,b,c,d){var e,f,g,h,i,j,l,n,o,p;if((b?b.ownerDocument||b:O)!==G&&F(b),b=b||G,c=c||[],!a||"string"!=typeof a)return c;if(1!==(h=b.nodeType)&&9!==h)return[];if(I&&!d){if(e=sb.exec(a))if(g=e[1]){if(9===h){if(f=b.getElementById(g),!f||!f.parentNode)return c;if(f.id===g)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(g))&&M(b,f)&&f.id===g)return c.push(f),c}else{if(e[2])return _.apply(c,b.getElementsByTagName(a)),c;if((g=e[3])&&v.getElementsByClassName&&b.getElementsByClassName)return _.apply(c,b.getElementsByClassName(g)),c}if(v.qsa&&(!J||!J.test(a))){if(n=l=N,o=b,p=9===h&&a,1===h&&"object"!==b.nodeName.toLowerCase()){for(j=z(a),(l=b.getAttribute("id"))?n=l.replace(ub,"\\$&"):b.setAttribute("id",n),n="[id='"+n+"'] ",i=j.length;i--;)j[i]=n+m(j[i]);o=tb.test(a)&&k(b.parentNode)||b,p=j.join(",")}if(p)try{return _.apply(c,o.querySelectorAll(p)),c}catch(q){}finally{l||b.removeAttribute("id")}}}return B(a.replace(ib,"$1"),b,c,d)}function c(){function a(c,d){return b.push(c+" ")>w.cacheLength&&delete a[b.shift()],a[c+" "]=d}var b=[];return a}function d(a){return a[N]=!0,a}function e(a){var b=G.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function f(a,b){for(var c=a.split("|"),d=a.length;d--;)w.attrHandle[c[d]]=b}function g(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||W)-(~a.sourceIndex||W);if(d)return d;if(c)for(;c=c.nextSibling;)if(c===b)return-1;return a?1:-1}function h(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function i(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function j(a){return d(function(b){return b=+b,d(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function k(a){return a&&typeof a.getElementsByTagName!==V&&a}function l(){}function m(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function n(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=Q++;return b.first?function(b,c,f){for(;b=b[d];)if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[P,f];if(g){for(;b=b[d];)if((1===b.nodeType||e)&&a(b,c,g))return!0}else for(;b=b[d];)if(1===b.nodeType||e){if(i=b[N]||(b[N]={}),(h=i[d])&&h[0]===P&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function o(a){return a.length>1?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:a[0]}function p(a,c,d){for(var e=0,f=c.length;f>e;e++)b(a,c[e],d);return d}function q(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 r(a,b,c,e,f,g){return e&&!e[N]&&(e=r(e)),f&&!f[N]&&(f=r(f,g)),d(function(d,g,h,i){var j,k,l,m=[],n=[],o=g.length,r=d||p(b||"*",h.nodeType?[h]:h,[]),s=!a||!d&&b?r:q(r,m,a,h,i),t=c?f||(d?a:o||e)?[]:g:s;if(c&&c(s,t,h,i),e)for(j=q(t,n),e(j,[],h,i),k=j.length;k--;)(l=j[k])&&(t[n[k]]=!(s[n[k]]=l));if(d){if(f||a){if(f){for(j=[],k=t.length;k--;)(l=t[k])&&j.push(s[k]=l);f(null,t=[],j,i)}for(k=t.length;k--;)(l=t[k])&&(j=f?bb.call(d,l):m[k])>-1&&(d[j]=!(g[j]=l))}}else t=q(t===g?t.splice(o,t.length):t),f?f(null,g,t,i):_.apply(g,t)})}function s(a){for(var b,c,d,e=a.length,f=w.relative[a[0].type],g=f||w.relative[" "],h=f?1:0,i=n(function(a){return a===b},g,!0),j=n(function(a){return bb.call(b,a)>-1},g,!0),k=[function(a,c,d){return!f&&(d||c!==C)||((b=c).nodeType?i(a,c,d):j(a,c,d))}];e>h;h++)if(c=w.relative[a[h].type])k=[n(o(k),c)];else{if(c=w.filter[a[h].type].apply(null,a[h].matches),c[N]){for(d=++h;e>d&&!w.relative[a[d].type];d++);return r(h>1&&o(k),h>1&&m(a.slice(0,h-1).concat({value:" "===a[h-2].type?"*":""})).replace(ib,"$1"),c,d>h&&s(a.slice(h,d)),e>d&&s(a=a.slice(d)),e>d&&m(a))}k.push(c)}return o(k)}function t(a,c){var e=c.length>0,f=a.length>0,g=function(d,g,h,i,j){var k,l,m,n=0,o="0",p=d&&[],r=[],s=C,t=d||f&&w.find.TAG("*",j),u=P+=null==s?1:Math.random()||.1,v=t.length;for(j&&(C=g!==G&&g);o!==v&&null!=(k=t[o]);o++){if(f&&k){for(l=0;m=a[l++];)if(m(k,g,h)){i.push(k);break}j&&(P=u)}e&&((k=!m&&k)&&n--,d&&p.push(k))}if(n+=o,e&&o!==n){for(l=0;m=c[l++];)m(p,r,g,h);if(d){if(n>0)for(;o--;)p[o]||r[o]||(r[o]=Z.call(i));r=q(r)}_.apply(i,r),j&&!d&&r.length>0&&n+c.length>1&&b.uniqueSort(i)}return j&&(P=u,C=s),p};return e?d(g):g}var u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N="sizzle"+-new Date,O=a.document,P=0,Q=0,R=c(),S=c(),T=c(),U=function(a,b){return a===b&&(E=!0),0},V="undefined",W=1<<31,X={}.hasOwnProperty,Y=[],Z=Y.pop,$=Y.push,_=Y.push,ab=Y.slice,bb=Y.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},cb="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",db="[\\x20\\t\\r\\n\\f]",eb="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",fb=eb.replace("w","w#"),gb="\\["+db+"*("+eb+")(?:"+db+"*([*^$|!~]?=)"+db+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+fb+"))|)"+db+"*\\]",hb=":("+eb+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+gb+")*)|.*)\\)|)",ib=new RegExp("^"+db+"+|((?:^|[^\\\\])(?:\\\\.)*)"+db+"+$","g"),jb=new RegExp("^"+db+"*,"+db+"*"),kb=new RegExp("^"+db+"*([>+~]|"+db+")"+db+"*"),lb=new RegExp("="+db+"*([^\\]'\"]*?)"+db+"*\\]","g"),mb=new RegExp(hb),nb=new RegExp("^"+fb+"$"),ob={ID:new RegExp("^#("+eb+")"),CLASS:new RegExp("^\\.("+eb+")"),TAG:new RegExp("^("+eb.replace("w","w*")+")"),ATTR:new RegExp("^"+gb),PSEUDO:new RegExp("^"+hb),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+db+"*(even|odd|(([+-]|)(\\d*)n|)"+db+"*(?:([+-]|)"+db+"*(\\d+)|))"+db+"*\\)|)","i"),bool:new RegExp("^(?:"+cb+")$","i"),needsContext:new RegExp("^"+db+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+db+"*((?:-\\d)?\\d*)"+db+"*\\)|)(?=[^-]|$)","i")},pb=/^(?:input|select|textarea|button)$/i,qb=/^h\d$/i,rb=/^[^{]+\{\s*\[native \w/,sb=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,tb=/[+~]/,ub=/'|\\/g,vb=new RegExp("\\\\([\\da-f]{1,6}"+db+"?|("+db+")|.)","ig"),wb=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)};try{_.apply(Y=ab.call(O.childNodes),O.childNodes),Y[O.childNodes.length].nodeType}catch(xb){_={apply:Y.length?function(a,b){$.apply(a,ab.call(b))}:function(a,b){for(var c=a.length,d=0;a[c++]=b[d++];);a.length=c-1}}}v=b.support={},y=b.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},F=b.setDocument=function(a){var b,c=a?a.ownerDocument||a:O,d=c.defaultView;return c!==G&&9===c.nodeType&&c.documentElement?(G=c,H=c.documentElement,I=!y(c),d&&d!==d.top&&(d.addEventListener?d.addEventListener("unload",function(){F()},!1):d.attachEvent&&d.attachEvent("onunload",function(){F()})),v.attributes=e(function(a){return a.className="i",!a.getAttribute("className")}),v.getElementsByTagName=e(function(a){return a.appendChild(c.createComment("")),!a.getElementsByTagName("*").length}),v.getElementsByClassName=rb.test(c.getElementsByClassName)&&e(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),v.getById=e(function(a){return H.appendChild(a).id=N,!c.getElementsByName||!c.getElementsByName(N).length}),v.getById?(w.find.ID=function(a,b){if(typeof b.getElementById!==V&&I){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},w.filter.ID=function(a){var b=a.replace(vb,wb);return function(a){return a.getAttribute("id")===b}}):(delete w.find.ID,w.filter.ID=function(a){var b=a.replace(vb,wb);return function(a){var c=typeof a.getAttributeNode!==V&&a.getAttributeNode("id");return c&&c.value===b}}),w.find.TAG=v.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==V?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){for(;c=f[e++];)1===c.nodeType&&d.push(c);return d}return f},w.find.CLASS=v.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==V&&I?b.getElementsByClassName(a):void 0},K=[],J=[],(v.qsa=rb.test(c.querySelectorAll))&&(e(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&J.push("[*^$]="+db+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||J.push("\\["+db+"*(?:value|"+cb+")"),a.querySelectorAll(":checked").length||J.push(":checked")}),e(function(a){var b=c.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&J.push("name"+db+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||J.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),J.push(",.*:")})),(v.matchesSelector=rb.test(L=H.matches||H.webkitMatchesSelector||H.mozMatchesSelector||H.oMatchesSelector||H.msMatchesSelector))&&e(function(a){v.disconnectedMatch=L.call(a,"div"),L.call(a,"[s!='']:x"),K.push("!=",hb)}),J=J.length&&new RegExp(J.join("|")),K=K.length&&new RegExp(K.join("|")),b=rb.test(H.compareDocumentPosition),M=b||rb.test(H.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)for(;b=b.parentNode;)if(b===a)return!0;return!1},U=b?function(a,b){if(a===b)return E=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!v.sortDetached&&b.compareDocumentPosition(a)===d?a===c||a.ownerDocument===O&&M(O,a)?-1:b===c||b.ownerDocument===O&&M(O,b)?1:D?bb.call(D,a)-bb.call(D,b):0:4&d?-1:1)}:function(a,b){if(a===b)return E=!0,0;var d,e=0,f=a.parentNode,h=b.parentNode,i=[a],j=[b];if(!f||!h)return a===c?-1:b===c?1:f?-1:h?1:D?bb.call(D,a)-bb.call(D,b):0;if(f===h)return g(a,b);for(d=a;d=d.parentNode;)i.unshift(d);for(d=b;d=d.parentNode;)j.unshift(d);for(;i[e]===j[e];)e++;return e?g(i[e],j[e]):i[e]===O?-1:j[e]===O?1:0},c):G},b.matches=function(a,c){return b(a,null,null,c)},b.matchesSelector=function(a,c){if((a.ownerDocument||a)!==G&&F(a),c=c.replace(lb,"='$1']"),!(!v.matchesSelector||!I||K&&K.test(c)||J&&J.test(c)))try{var d=L.call(a,c);if(d||v.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return b(c,G,null,[a]).length>0},b.contains=function(a,b){return(a.ownerDocument||a)!==G&&F(a),M(a,b)},b.attr=function(a,b){(a.ownerDocument||a)!==G&&F(a);var c=w.attrHandle[b.toLowerCase()],d=c&&X.call(w.attrHandle,b.toLowerCase())?c(a,b,!I):void 0;return void 0!==d?d:v.attributes||!I?a.getAttribute(b):(d=a.getAttributeNode(b))&&d.specified?d.value:null},b.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},b.uniqueSort=function(a){var b,c=[],d=0,e=0;if(E=!v.detectDuplicates,D=!v.sortStable&&a.slice(0),a.sort(U),E){for(;b=a[e++];)b===a[e]&&(d=c.push(e));for(;d--;)a.splice(c[d],1)}return D=null,a},x=b.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(1===e||9===e||11===e){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=x(a)}else if(3===e||4===e)return a.nodeValue}else for(;b=a[d++];)c+=x(b);return c},w=b.selectors={cacheLength:50,createPseudo:d,match:ob,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(vb,wb),a[3]=(a[3]||a[4]||a[5]||"").replace(vb,wb),"~="===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]||b.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]&&b.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return ob.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&mb.test(c)&&(b=z(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(vb,wb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=R[a+" "];return b||(b=new RegExp("(^|"+db+")"+a+"("+db+"|$)"))&&R(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==V&&a.getAttribute("class")||"")})},ATTR:function(a,c,d){return function(e){var f=b.attr(e,a);return null==f?"!="===c:c?(f+="","="===c?f===d:"!="===c?f!==d:"^="===c?d&&0===f.indexOf(d):"*="===c?d&&f.indexOf(d)>-1:"$="===c?d&&f.slice(-d.length)===d:"~="===c?(" "+f+" ").indexOf(d)>-1:"|="===c?f===d||f.slice(0,d.length+1)===d+"-":!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){for(;p;){for(l=b;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){for(k=q[N]||(q[N]={}),j=k[a]||[],n=j[0]===P&&j[1],m=j[0]===P&&j[2],l=n&&q.childNodes[n];l=++n&&l&&l[p]||(m=n=0)||o.pop();)if(1===l.nodeType&&++m&&l===b){k[a]=[P,n,m];break}}else if(s&&(j=(b[N]||(b[N]={}))[a])&&j[0]===P)m=j[1];else for(;(l=++n&&l&&l[p]||(m=n=0)||o.pop())&&((h?l.nodeName.toLowerCase()!==r:1!==l.nodeType)||!++m||(s&&((l[N]||(l[N]={}))[a]=[P,m]),l!==b)););return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,c){var e,f=w.pseudos[a]||w.setFilters[a.toLowerCase()]||b.error("unsupported pseudo: "+a);return f[N]?f(c):f.length>1?(e=[a,a,"",c],w.setFilters.hasOwnProperty(a.toLowerCase())?d(function(a,b){for(var d,e=f(a,c),g=e.length;g--;)d=bb.call(a,e[g]),a[d]=!(b[d]=e[g])}):function(a){return f(a,0,e)}):f}},pseudos:{not:d(function(a){var b=[],c=[],e=A(a.replace(ib,"$1"));return e[N]?d(function(a,b,c,d){for(var f,g=e(a,null,d,[]),h=a.length;h--;)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,d,f){return b[0]=a,e(b,null,f,c),!c.pop()}}),has:d(function(a){return function(c){return b(a,c).length>0}}),contains:d(function(a){return function(b){return(b.textContent||b.innerText||x(b)).indexOf(a)>-1}}),lang:d(function(a){return nb.test(a||"")||b.error("unsupported lang: "+a),a=a.replace(vb,wb).toLowerCase(),function(b){var c;do if(c=I?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===H},focus:function(a){return a===G.activeElement&&(!G.hasFocus||G.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!w.pseudos.empty(a)},header:function(a){return qb.test(a.nodeName)},input:function(a){return pb.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:j(function(){return[0]}),last:j(function(a,b){return[b-1]}),eq:j(function(a,b,c){return[0>c?c+b:c]}),even:j(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:j(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:j(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:j(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},w.pseudos.nth=w.pseudos.eq;for(u in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})w.pseudos[u]=h(u);for(u in{submit:!0,reset:!0})w.pseudos[u]=i(u);return l.prototype=w.filters=w.pseudos,w.setFilters=new l,z=b.tokenize=function(a,c){var d,e,f,g,h,i,j,k=S[a+" "];if(k)return c?0:k.slice(0);for(h=a,i=[],j=w.preFilter;h;){(!d||(e=jb.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),d=!1,(e=kb.exec(h))&&(d=e.shift(),f.push({value:d,type:e[0].replace(ib," ")}),h=h.slice(d.length));for(g in w.filter)!(e=ob[g].exec(h))||j[g]&&!(e=j[g](e))||(d=e.shift(),f.push({value:d,type:g,matches:e}),h=h.slice(d.length));if(!d)break}return c?h.length:h?b.error(a):S(a,i).slice(0)},A=b.compile=function(a,b){var c,d=[],e=[],f=T[a+" "];if(!f){for(b||(b=z(a)),c=b.length;c--;)f=s(b[c]),f[N]?d.push(f):e.push(f);f=T(a,t(e,d)),f.selector=a}return f},B=b.select=function(a,b,c,d){var e,f,g,h,i,j="function"==typeof a&&a,l=!d&&z(a=j.selector||a);if(c=c||[],1===l.length){if(f=l[0]=l[0].slice(0),f.length>2&&"ID"===(g=f[0]).type&&v.getById&&9===b.nodeType&&I&&w.relative[f[1].type]){if(b=(w.find.ID(g.matches[0].replace(vb,wb),b)||[])[0],!b)return c;j&&(b=b.parentNode),a=a.slice(f.shift().value.length)}for(e=ob.needsContext.test(a)?0:f.length;e--&&(g=f[e],!w.relative[h=g.type]);)if((i=w.find[h])&&(d=i(g.matches[0].replace(vb,wb),tb.test(f[0].type)&&k(b.parentNode)||b))){if(f.splice(e,1),a=d.length&&m(f),!a)return _.apply(c,d),c;break}}return(j||A(a,l))(d,b,!I,c,tb.test(a)&&k(b.parentNode)||b),c},v.sortStable=N.split("").sort(U).join("")===N,v.detectDuplicates=!!E,F(),v.sortDetached=e(function(a){return 1&a.compareDocumentPosition(G.createElement("div"))}),e(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||f("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),v.attributes&&e(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||f("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),e(function(a){return null==a.getAttribute("disabled")})||f(cb,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),b}(a);eb.find=jb,eb.expr=jb.selectors,eb.expr[":"]=eb.expr.pseudos,eb.unique=jb.uniqueSort,eb.text=jb.getText,eb.isXMLDoc=jb.isXML,eb.contains=jb.contains;var kb=eb.expr.match.needsContext,lb=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,mb=/^.[^:#\[\.,]*$/;eb.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?eb.find.matchesSelector(d,a)?[d]:[]:eb.find.matches(a,eb.grep(b,function(a){return 1===a.nodeType}))},eb.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(eb(a).filter(function(){for(b=0;e>b;b++)if(eb.contains(d[b],this))return!0}));for(b=0;e>b;b++)eb.find(a,d[b],c);return c=this.pushStack(e>1?eb.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(d(this,a||[],!1))},not:function(a){return this.pushStack(d(this,a||[],!0))},is:function(a){return!!d(this,"string"==typeof a&&kb.test(a)?eb(a):a||[],!1).length}});var nb,ob=a.document,pb=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,qb=eb.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]:pb.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||nb).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof eb?b[0]:b,eb.merge(this,eb.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:ob,!0)),lb.test(c[1])&&eb.isPlainObject(b))for(c in b)eb.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=ob.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return nb.find(a);this.length=1,this[0]=d}return this.context=ob,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):eb.isFunction(a)?"undefined"!=typeof nb.ready?nb.ready(a):a(eb):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),eb.makeArray(a,this))};qb.prototype=eb.fn,nb=eb(ob);var rb=/^(?:parents|prev(?:Until|All))/,sb={children:!0,contents:!0,next:!0,prev:!0};eb.extend({dir:function(a,b,c){for(var d=[],e=a[b];e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!eb(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}}),eb.fn.extend({has:function(a){var b,c=eb(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(eb.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=kb.test(a)||"string"!=typeof a?eb(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&&eb.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?eb.unique(f):f)},index:function(a){return a?"string"==typeof a?eb.inArray(this[0],eb(a)):eb.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(eb.unique(eb.merge(this.get(),eb(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}}),eb.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return eb.dir(a,"parentNode")},parentsUntil:function(a,b,c){return eb.dir(a,"parentNode",c)},next:function(a){return e(a,"nextSibling")},prev:function(a){return e(a,"previousSibling")},nextAll:function(a){return eb.dir(a,"nextSibling")},prevAll:function(a){return eb.dir(a,"previousSibling")},nextUntil:function(a,b,c){return eb.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return eb.dir(a,"previousSibling",c)},siblings:function(a){return eb.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return eb.sibling(a.firstChild)},contents:function(a){return eb.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:eb.merge([],a.childNodes)}},function(a,b){eb.fn[a]=function(c,d){var e=eb.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=eb.filter(d,e)),this.length>1&&(sb[a]||(e=eb.unique(e)),rb.test(a)&&(e=e.reverse())),this.pushStack(e)}});var tb=/\S+/g,ub={};eb.Callbacks=function(a){a="string"==typeof a?ub[a]||f(a):eb.extend({},a);var b,c,d,e,g,h,i=[],j=!a.once&&[],k=function(f){for(c=a.memory&&f,d=!0,g=h||0,h=0,e=i.length,b=!0;i&&e>g;g++)if(i[g].apply(f[0],f[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var d=i.length;!function f(b){eb.each(b,function(b,c){var d=eb.type(c);"function"===d?a.unique&&l.has(c)||i.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=i.length:c&&(h=d,k(c))}return this},remove:function(){return i&&eb.each(arguments,function(a,c){for(var d;(d=eb.inArray(c,i,d))>-1;)i.splice(d,1),b&&(e>=d&&e--,g>=d&&g--)}),this},has:function(a){return a?eb.inArray(a,i)>-1:!(!i||!i.length)},empty:function(){return i=[],e=0,this},disable:function(){return i=j=c=void 0,this},disabled:function(){return!i},lock:function(){return j=void 0,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,c){return!i||d&&!j||(c=c||[],c=[a,c.slice?c.slice():c],b?j.push(c):k(c)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},eb.extend({Deferred:function(a){var b=[["resolve","done",eb.Callbacks("once memory"),"resolved"],["reject","fail",eb.Callbacks("once memory"),"rejected"],["notify","progress",eb.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return eb.Deferred(function(c){eb.each(b,function(b,f){var g=eb.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&eb.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?eb.extend(a,d):d}},e={};return d.pipe=d.then,eb.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,c,d,e=0,f=X.call(arguments),g=f.length,h=1!==g||a&&eb.isFunction(a.promise)?g:0,i=1===h?a:eb.Deferred(),j=function(a,c,d){return function(e){c[a]=this,d[a]=arguments.length>1?X.call(arguments):e,d===b?i.notifyWith(c,d):--h||i.resolveWith(c,d)}};if(g>1)for(b=new Array(g),c=new Array(g),d=new Array(g);g>e;e++)f[e]&&eb.isFunction(f[e].promise)?f[e].promise().done(j(e,d,f)).fail(i.reject).progress(j(e,c,b)):--h;return h||i.resolveWith(d,f),i.promise()}});var vb;eb.fn.ready=function(a){return eb.ready.promise().done(a),this},eb.extend({isReady:!1,readyWait:1,holdReady:function(a){a?eb.readyWait++:eb.ready(!0)},ready:function(a){if(a===!0?!--eb.readyWait:!eb.isReady){if(!ob.body)return setTimeout(eb.ready);eb.isReady=!0,a!==!0&&--eb.readyWait>0||(vb.resolveWith(ob,[eb]),eb.fn.triggerHandler&&(eb(ob).triggerHandler("ready"),eb(ob).off("ready")))}}}),eb.ready.promise=function(b){if(!vb)if(vb=eb.Deferred(),"complete"===ob.readyState)setTimeout(eb.ready);else if(ob.addEventListener)ob.addEventListener("DOMContentLoaded",h,!1),a.addEventListener("load",h,!1);else{ob.attachEvent("onreadystatechange",h),a.attachEvent("onload",h);var c=!1;try{c=null==a.frameElement&&ob.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!eb.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}g(),eb.ready()}}()}return vb.promise(b)};var wb,xb="undefined";for(wb in eb(cb))break;cb.ownLast="0"!==wb,cb.inlineBlockNeedsLayout=!1,eb(function(){var a,b,c,d;c=ob.getElementsByTagName("body")[0],c&&c.style&&(b=ob.createElement("div"),d=ob.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!==xb&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",cb.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=ob.createElement("div");if(null==cb.deleteExpando){cb.deleteExpando=!0;try{delete a.test}catch(b){cb.deleteExpando=!1}}a=null}(),eb.acceptData=function(a){var b=eb.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var yb=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,zb=/([A-Z])/g;eb.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?eb.cache[a[eb.expando]]:a[eb.expando],!!a&&!j(a)},data:function(a,b,c){return k(a,b,c)},removeData:function(a,b){return l(a,b)},_data:function(a,b,c){return k(a,b,c,!0)},_removeData:function(a,b){return l(a,b,!0)}}),eb.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=eb.data(f),1===f.nodeType&&!eb._data(f,"parsedAttrs"))){for(c=g.length;c--;)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=eb.camelCase(d.slice(5)),i(f,d,e[d])));eb._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){eb.data(this,a)}):arguments.length>1?this.each(function(){eb.data(this,a,b)}):f?i(f,a,eb.data(f,a)):void 0},removeData:function(a){return this.each(function(){eb.removeData(this,a)})}}),eb.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=eb._data(a,b),c&&(!d||eb.isArray(c)?d=eb._data(a,b,eb.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=eb.queue(a,b),d=c.length,e=c.shift(),f=eb._queueHooks(a,b),g=function(){eb.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 eb._data(a,c)||eb._data(a,c,{empty:eb.Callbacks("once memory").add(function(){eb._removeData(a,b+"queue"),eb._removeData(a,c)})})}}),eb.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?eb.queue(this[0],a):void 0===b?this:this.each(function(){var c=eb.queue(this,a,b);eb._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&eb.dequeue(this,a)})},dequeue:function(a){return this.each(function(){eb.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=eb.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};for("string"!=typeof a&&(b=a,a=void 0),a=a||"fx";g--;)c=eb._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Ab=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Bb=["Top","Right","Bottom","Left"],Cb=function(a,b){return a=b||a,"none"===eb.css(a,"display")||!eb.contains(a.ownerDocument,a)},Db=eb.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===eb.type(c)){e=!0;for(h in c)eb.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,eb.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(eb(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},Eb=/^(?:checkbox|radio)$/i;!function(){var a=ob.createElement("input"),b=ob.createElement("div"),c=ob.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",cb.leadingWhitespace=3===b.firstChild.nodeType,cb.tbody=!b.getElementsByTagName("tbody").length,cb.htmlSerialize=!!b.getElementsByTagName("link").length,cb.html5Clone="<:nav></:nav>"!==ob.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),cb.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",cb.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",cb.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,cb.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){cb.noCloneEvent=!1}),b.cloneNode(!0).click()),null==cb.deleteExpando){cb.deleteExpando=!0;try{delete b.test}catch(d){cb.deleteExpando=!1}}}(),function(){var b,c,d=ob.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(cb[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),cb[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Fb=/^(?:input|select|textarea)$/i,Gb=/^key/,Hb=/^(?:mouse|pointer|contextmenu)|click/,Ib=/^(?:focusinfocus|focusoutblur)$/,Jb=/^([^.]*)(?:\.(.+)|)$/;eb.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=eb._data(a);if(q){for(c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=eb.guid++),(g=q.events)||(g=q.events={}),(k=q.handle)||(k=q.handle=function(a){return typeof eb===xb||a&&eb.event.triggered===a.type?void 0:eb.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(tb)||[""],h=b.length;h--;)f=Jb.exec(b[h])||[],n=p=f[1],o=(f[2]||"").split(".").sort(),n&&(j=eb.event.special[n]||{},n=(e?j.delegateType:j.bindType)||n,j=eb.event.special[n]||{},l=eb.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&eb.expr.match.needsContext.test(e),namespace:o.join(".")},i),(m=g[n])||(m=g[n]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,o,k)!==!1||(a.addEventListener?a.addEventListener(n,k,!1):a.attachEvent&&a.attachEvent("on"+n,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),eb.event.global[n]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=eb.hasData(a)&&eb._data(a);if(q&&(k=q.events)){for(b=(b||"").match(tb)||[""],j=b.length;j--;)if(h=Jb.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){for(l=eb.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=k[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;f--;)g=m[f],!e&&p!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g)); i&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||eb.removeEvent(a,n,q.handle),delete k[n])}else for(n in k)eb.event.remove(a,n+b[j],c,d,!0);eb.isEmptyObject(k)&&(delete q.handle,eb._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,j,k,l,m=[d||ob],n=bb.call(b,"type")?b.type:b,o=bb.call(b,"namespace")?b.namespace.split("."):[];if(h=k=d=d||ob,3!==d.nodeType&&8!==d.nodeType&&!Ib.test(n+eb.event.triggered)&&(n.indexOf(".")>=0&&(o=n.split("."),n=o.shift(),o.sort()),g=n.indexOf(":")<0&&"on"+n,b=b[eb.expando]?b:new eb.Event(n,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=o.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:eb.makeArray(c,[b]),j=eb.event.special[n]||{},e||!j.trigger||j.trigger.apply(d,c)!==!1)){if(!e&&!j.noBubble&&!eb.isWindow(d)){for(i=j.delegateType||n,Ib.test(i+n)||(h=h.parentNode);h;h=h.parentNode)m.push(h),k=h;k===(d.ownerDocument||ob)&&m.push(k.defaultView||k.parentWindow||a)}for(l=0;(h=m[l++])&&!b.isPropagationStopped();)b.type=l>1?i:j.bindType||n,f=(eb._data(h,"events")||{})[b.type]&&eb._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&eb.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=n,!e&&!b.isDefaultPrevented()&&(!j._default||j._default.apply(m.pop(),c)===!1)&&eb.acceptData(d)&&g&&d[n]&&!eb.isWindow(d)){k=d[g],k&&(d[g]=null),eb.event.triggered=n;try{d[n]()}catch(p){}eb.event.triggered=void 0,k&&(d[g]=k)}return b.result}},dispatch:function(a){a=eb.event.fix(a);var b,c,d,e,f,g=[],h=X.call(arguments),i=(eb._data(this,"events")||{})[a.type]||[],j=eb.event.special[a.type]||{};if(h[0]=a,a.delegateTarget=this,!j.preDispatch||j.preDispatch.call(this,a)!==!1){for(g=eb.event.handlers.call(this,a,i),b=0;(e=g[b++])&&!a.isPropagationStopped();)for(a.currentTarget=e.elem,f=0;(d=e.handlers[f++])&&!a.isImmediatePropagationStopped();)(!a.namespace_re||a.namespace_re.test(d.namespace))&&(a.handleObj=d,a.data=d.data,c=((eb.event.special[d.origType]||{}).handle||d.handler).apply(e.elem,h),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()));return j.postDispatch&&j.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?eb(c,this).index(i)>=0:eb.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[eb.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];for(g||(this.fixHooks[e]=g=Hb.test(e)?this.mouseHooks:Gb.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new eb.Event(f),b=d.length;b--;)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||ob),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||ob,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!==o()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===o()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return eb.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return eb.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=eb.extend(new eb.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?eb.event.trigger(e,null,b):eb.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},eb.removeEvent=ob.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]===xb&&(a[d]=null),a.detachEvent(d,c))},eb.Event=function(a,b){return this instanceof eb.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?m:n):this.type=a,b&&eb.extend(this,b),this.timeStamp=a&&a.timeStamp||eb.now(),void(this[eb.expando]=!0)):new eb.Event(a,b)},eb.Event.prototype={isDefaultPrevented:n,isPropagationStopped:n,isImmediatePropagationStopped:n,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=m,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=m,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=m,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},eb.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){eb.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!eb.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),cb.submitBubbles||(eb.event.special.submit={setup:function(){return eb.nodeName(this,"form")?!1:void eb.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=eb.nodeName(b,"input")||eb.nodeName(b,"button")?b.form:void 0;c&&!eb._data(c,"submitBubbles")&&(eb.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),eb._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&eb.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return eb.nodeName(this,"form")?!1:void eb.event.remove(this,"._submit")}}),cb.changeBubbles||(eb.event.special.change={setup:function(){return Fb.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(eb.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),eb.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),eb.event.simulate("change",this,a,!0)})),!1):void eb.event.add(this,"beforeactivate._change",function(a){var b=a.target;Fb.test(b.nodeName)&&!eb._data(b,"changeBubbles")&&(eb.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||eb.event.simulate("change",this.parentNode,a,!0)}),eb._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 eb.event.remove(this,"._change"),!Fb.test(this.nodeName)}}),cb.focusinBubbles||eb.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){eb.event.simulate(b,a.target,eb.event.fix(a),!0)};eb.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=eb._data(d,b);e||d.addEventListener(a,c,!0),eb._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=eb._data(d,b)-1;e?eb._data(d,b,e):(d.removeEventListener(a,c,!0),eb._removeData(d,b))}}}),eb.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=n;else if(!d)return this;return 1===e&&(g=d,d=function(a){return eb().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=eb.guid++)),this.each(function(){eb.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,eb(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=n),this.each(function(){eb.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){eb.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?eb.event.trigger(a,b,c,!0):void 0}});var Kb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Lb=/ jQuery\d+="(?:null|\d+)"/g,Mb=new RegExp("<(?:"+Kb+")[\\s/>]","i"),Nb=/^\s+/,Ob=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Pb=/<([\w:]+)/,Qb=/<tbody/i,Rb=/<|&#?\w+;/,Sb=/<(?:script|style|link)/i,Tb=/checked\s*(?:[^=]|=\s*.checked.)/i,Ub=/^$|\/(?:java|ecma)script/i,Vb=/^true\/(.*)/,Wb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Xb={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:cb.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Yb=p(ob),Zb=Yb.appendChild(ob.createElement("div"));Xb.optgroup=Xb.option,Xb.tbody=Xb.tfoot=Xb.colgroup=Xb.caption=Xb.thead,Xb.th=Xb.td,eb.extend({clone:function(a,b,c){var d,e,f,g,h,i=eb.contains(a.ownerDocument,a);if(cb.html5Clone||eb.isXMLDoc(a)||!Mb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Zb.innerHTML=a.outerHTML,Zb.removeChild(f=Zb.firstChild)),!(cb.noCloneEvent&&cb.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||eb.isXMLDoc(a)))for(d=q(f),h=q(a),g=0;null!=(e=h[g]);++g)d[g]&&x(e,d[g]);if(b)if(c)for(h=h||q(a),d=d||q(f),g=0;null!=(e=h[g]);g++)w(e,d[g]);else w(a,f);return d=q(f,"script"),d.length>0&&v(d,!i&&q(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,l=a.length,m=p(b),n=[],o=0;l>o;o++)if(f=a[o],f||0===f)if("object"===eb.type(f))eb.merge(n,f.nodeType?[f]:f);else if(Rb.test(f)){for(h=h||m.appendChild(b.createElement("div")),i=(Pb.exec(f)||["",""])[1].toLowerCase(),k=Xb[i]||Xb._default,h.innerHTML=k[1]+f.replace(Ob,"<$1></$2>")+k[2],e=k[0];e--;)h=h.lastChild;if(!cb.leadingWhitespace&&Nb.test(f)&&n.push(b.createTextNode(Nb.exec(f)[0])),!cb.tbody)for(f="table"!==i||Qb.test(f)?"<table>"!==k[1]||Qb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;e--;)eb.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j);for(eb.merge(n,h.childNodes),h.textContent="";h.firstChild;)h.removeChild(h.firstChild);h=m.lastChild}else n.push(b.createTextNode(f));for(h&&m.removeChild(h),cb.appendChecked||eb.grep(q(n,"input"),r),o=0;f=n[o++];)if((!d||-1===eb.inArray(f,d))&&(g=eb.contains(f.ownerDocument,f),h=q(m.appendChild(f),"script"),g&&v(h),c))for(e=0;f=h[e++];)Ub.test(f.type||"")&&c.push(f);return h=null,m},cleanData:function(a,b){for(var c,d,e,f,g=0,h=eb.expando,i=eb.cache,j=cb.deleteExpando,k=eb.event.special;null!=(c=a[g]);g++)if((b||eb.acceptData(c))&&(e=c[h],f=e&&i[e])){if(f.events)for(d in f.events)k[d]?eb.event.remove(c,d):eb.removeEvent(c,d,f.handle);i[e]&&(delete i[e],j?delete c[h]:typeof c.removeAttribute!==xb?c.removeAttribute(h):c[h]=null,W.push(e))}}}),eb.fn.extend({text:function(a){return Db(this,function(a){return void 0===a?eb.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ob).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=s(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=s(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?eb.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||eb.cleanData(q(c)),c.parentNode&&(b&&eb.contains(c.ownerDocument,c)&&v(q(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){for(1===a.nodeType&&eb.cleanData(q(a,!1));a.firstChild;)a.removeChild(a.firstChild);a.options&&eb.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 eb.clone(this,a,b)})},html:function(a){return Db(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(Lb,""):void 0;if(!("string"!=typeof a||Sb.test(a)||!cb.htmlSerialize&&Mb.test(a)||!cb.leadingWhitespace&&Nb.test(a)||Xb[(Pb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(Ob,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(eb.cleanData(q(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,eb.cleanData(q(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=Y.apply([],a);var c,d,e,f,g,h,i=0,j=this.length,k=this,l=j-1,m=a[0],n=eb.isFunction(m);if(n||j>1&&"string"==typeof m&&!cb.checkClone&&Tb.test(m))return this.each(function(c){var d=k.eq(c);n&&(a[0]=m.call(this,c,d.html())),d.domManip(a,b)});if(j&&(h=eb.buildFragment(a,this[0].ownerDocument,!1,this),c=h.firstChild,1===h.childNodes.length&&(h=c),c)){for(f=eb.map(q(h,"script"),t),e=f.length;j>i;i++)d=h,i!==l&&(d=eb.clone(d,!0,!0),e&&eb.merge(f,q(d,"script"))),b.call(this[i],d,i);if(e)for(g=f[f.length-1].ownerDocument,eb.map(f,u),i=0;e>i;i++)d=f[i],Ub.test(d.type||"")&&!eb._data(d,"globalEval")&&eb.contains(g,d)&&(d.src?eb._evalUrl&&eb._evalUrl(d.src):eb.globalEval((d.text||d.textContent||d.innerHTML||"").replace(Wb,"")));h=c=null}return this}}),eb.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){eb.fn[a]=function(a){for(var c,d=0,e=[],f=eb(a),g=f.length-1;g>=d;d++)c=d===g?this:this.clone(!0),eb(f[d])[b](c),Z.apply(e,c.get());return this.pushStack(e)}});var $b,_b={};!function(){var a;cb.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=ob.getElementsByTagName("body")[0],c&&c.style?(b=ob.createElement("div"),d=ob.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!==xb&&(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(ob.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var ac,bc,cc=/^margin/,dc=new RegExp("^("+Ab+")(?!px)[a-z%]+$","i"),ec=/^(top|right|bottom|left)$/;a.getComputedStyle?(ac=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},bc=function(a,b,c){var d,e,f,g,h=a.style;return c=c||ac(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||eb.contains(a.ownerDocument,a)||(g=eb.style(a,b)),dc.test(g)&&cc.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+""}):ob.documentElement.currentStyle&&(ac=function(a){return a.currentStyle},bc=function(a,b,c){var d,e,f,g,h=a.style;return c=c||ac(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),dc.test(g)&&!ec.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(){function b(){var b,c,d,e;c=ob.getElementsByTagName("body")[0],c&&c.style&&(b=ob.createElement("div"),d=ob.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",f=g=!1,i=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(b,null)||{}).top,g="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,e=b.appendChild(ob.createElement("div")),e.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",e.style.marginRight=e.style.width="0",b.style.width="1px",i=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",e=b.getElementsByTagName("td"),e[0].style.cssText="margin:0;border:0;padding:0;display:none",h=0===e[0].offsetHeight,h&&(e[0].style.display="",e[1].style.display="none",h=0===e[0].offsetHeight),c.removeChild(d))}var c,d,e,f,g,h,i;c=ob.createElement("div"),c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",e=c.getElementsByTagName("a")[0],d=e&&e.style,d&&(d.cssText="float:left;opacity:.5",cb.opacity="0.5"===d.opacity,cb.cssFloat=!!d.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",cb.clearCloneStyle="content-box"===c.style.backgroundClip,cb.boxSizing=""===d.boxSizing||""===d.MozBoxSizing||""===d.WebkitBoxSizing,eb.extend(cb,{reliableHiddenOffsets:function(){return null==h&&b(),h},boxSizingReliable:function(){return null==g&&b(),g},pixelPosition:function(){return null==f&&b(),f},reliableMarginRight:function(){return null==i&&b(),i}}))}(),eb.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 fc=/alpha\([^)]*\)/i,gc=/opacity\s*=\s*([^)]*)/,hc=/^(none|table(?!-c[ea]).+)/,ic=new RegExp("^("+Ab+")(.*)$","i"),jc=new RegExp("^([+-])=("+Ab+")","i"),kc={position:"absolute",visibility:"hidden",display:"block"},lc={letterSpacing:"0",fontWeight:"400"},mc=["Webkit","O","Moz","ms"];eb.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bc(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":cb.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=eb.camelCase(b),i=a.style;if(b=eb.cssProps[h]||(eb.cssProps[h]=B(i,h)),g=eb.cssHooks[b]||eb.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=jc.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(eb.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||eb.cssNumber[h]||(c+="px"),cb.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=eb.camelCase(b);return b=eb.cssProps[h]||(eb.cssProps[h]=B(a.style,h)),g=eb.cssHooks[b]||eb.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=bc(a,b,d)),"normal"===f&&b in lc&&(f=lc[b]),""===c||c?(e=parseFloat(f),c===!0||eb.isNumeric(e)?e||0:f):f}}),eb.each(["height","width"],function(a,b){eb.cssHooks[b]={get:function(a,c,d){return c?hc.test(eb.css(a,"display"))&&0===a.offsetWidth?eb.swap(a,kc,function(){return F(a,b,d)}):F(a,b,d):void 0},set:function(a,c,d){var e=d&&ac(a);return D(a,c,d?E(a,b,d,cb.boxSizing&&"border-box"===eb.css(a,"boxSizing",!1,e),e):0)}}}),cb.opacity||(eb.cssHooks.opacity={get:function(a,b){return gc.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=eb.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===eb.trim(f.replace(fc,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=fc.test(f)?f.replace(fc,e):f+" "+e)}}),eb.cssHooks.marginRight=A(cb.reliableMarginRight,function(a,b){return b?eb.swap(a,{display:"inline-block"},bc,[a,"marginRight"]):void 0}),eb.each({margin:"",padding:"",border:"Width"},function(a,b){eb.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+Bb[d]+b]=f[d]||f[d-2]||f[0];return e}},cc.test(a)||(eb.cssHooks[a+b].set=D)}),eb.fn.extend({css:function(a,b){return Db(this,function(a,b,c){var d,e,f={},g=0;if(eb.isArray(b)){for(d=ac(a),e=b.length;e>g;g++)f[b[g]]=eb.css(a,b[g],!1,d);return f}return void 0!==c?eb.style(a,b,c):eb.css(a,b)},a,b,arguments.length>1)},show:function(){return C(this,!0)},hide:function(){return C(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){Cb(this)?eb(this).show():eb(this).hide()})}}),eb.Tween=G,G.prototype={constructor:G,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||(eb.cssNumber[c]?"":"px")},cur:function(){var a=G.propHooks[this.prop];return a&&a.get?a.get(this):G.propHooks._default.get(this)},run:function(a){var b,c=G.propHooks[this.prop];return this.pos=b=this.options.duration?eb.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):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):G.propHooks._default.set(this),this}},G.prototype.init.prototype=G.prototype,G.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=eb.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){eb.fx.step[a.prop]?eb.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[eb.cssProps[a.prop]]||eb.cssHooks[a.prop])?eb.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},G.propHooks.scrollTop=G.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},eb.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},eb.fx=G.prototype.init,eb.fx.step={};var nc,oc,pc=/^(?:toggle|show|hide)$/,qc=new RegExp("^(?:([+-])=|)("+Ab+")([a-z%]*)$","i"),rc=/queueHooks$/,sc=[K],tc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=qc.exec(b),f=e&&e[3]||(eb.cssNumber[a]?"":"px"),g=(eb.cssNumber[a]||"px"!==f&&+d)&&qc.exec(eb.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,eb.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}]};eb.Animation=eb.extend(M,{tweener:function(a,b){eb.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],tc[c]=tc[c]||[],tc[c].unshift(b)},prefilter:function(a,b){b?sc.unshift(a):sc.push(a)}}),eb.speed=function(a,b,c){var d=a&&"object"==typeof a?eb.extend({},a):{complete:c||!c&&b||eb.isFunction(a)&&a,duration:a,easing:c&&b||b&&!eb.isFunction(b)&&b};return d.duration=eb.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in eb.fx.speeds?eb.fx.speeds[d.duration]:eb.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){eb.isFunction(d.old)&&d.old.call(this),d.queue&&eb.dequeue(this,d.queue)},d},eb.fn.extend({fadeTo:function(a,b,c,d){return this.filter(Cb).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=eb.isEmptyObject(a),f=eb.speed(b,c,d),g=function(){var b=M(this,eb.extend({},a),f);(e||eb._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=eb.timers,g=eb._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&rc.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)&&eb.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=eb._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=eb.timers,g=d?d.length:0;for(c.finish=!0,eb.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})}}),eb.each(["toggle","show","hide"],function(a,b){var c=eb.fn[b];eb.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(I(b,!0),a,d,e)}}),eb.each({slideDown:I("show"),slideUp:I("hide"),slideToggle:I("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){eb.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),eb.timers=[],eb.fx.tick=function(){var a,b=eb.timers,c=0;for(nc=eb.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||eb.fx.stop(),nc=void 0},eb.fx.timer=function(a){eb.timers.push(a),a()?eb.fx.start():eb.timers.pop()},eb.fx.interval=13,eb.fx.start=function(){oc||(oc=setInterval(eb.fx.tick,eb.fx.interval))},eb.fx.stop=function(){clearInterval(oc),oc=null},eb.fx.speeds={slow:600,fast:200,_default:400},eb.fn.delay=function(a,b){return a=eb.fx?eb.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=ob.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=ob.createElement("select"),e=c.appendChild(ob.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",cb.getSetAttribute="t"!==b.className,cb.style=/top/.test(d.getAttribute("style")),cb.hrefNormalized="/a"===d.getAttribute("href"),cb.checkOn=!!a.value,cb.optSelected=e.selected,cb.enctype=!!ob.createElement("form").enctype,c.disabled=!0,cb.optDisabled=!e.disabled,a=ob.createElement("input"),a.setAttribute("value",""),cb.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),cb.radioValue="t"===a.value}();var uc=/\r/g;eb.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=eb.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,eb(this).val()):a,null==e?e="":"number"==typeof e?e+="":eb.isArray(e)&&(e=eb.map(e,function(a){return null==a?"":a+""})),b=eb.valHooks[this.type]||eb.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=eb.valHooks[e.type]||eb.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(uc,""):null==c?"":c)}}}),eb.extend({valHooks:{option:{get:function(a){var b=eb.find.attr(a,"value");return null!=b?b:eb.trim(eb.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||(cb.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&eb.nodeName(c.parentNode,"optgroup"))){if(b=eb(c).val(),f)return b;g.push(b)}return g},set:function(a,b){for(var c,d,e=a.options,f=eb.makeArray(b),g=e.length;g--;)if(d=e[g],eb.inArray(eb.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}}}}),eb.each(["radio","checkbox"],function(){eb.valHooks[this]={set:function(a,b){return eb.isArray(b)?a.checked=eb.inArray(eb(a).val(),b)>=0:void 0}},cb.checkOn||(eb.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var vc,wc,xc=eb.expr.attrHandle,yc=/^(?:checked|selected)$/i,zc=cb.getSetAttribute,Ac=cb.input;eb.fn.extend({attr:function(a,b){return Db(this,eb.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){eb.removeAttr(this,a)})}}),eb.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===xb?eb.prop(a,b,c):(1===f&&eb.isXMLDoc(a)||(b=b.toLowerCase(),d=eb.attrHooks[b]||(eb.expr.match.bool.test(b)?wc:vc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=eb.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 eb.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(tb);if(f&&1===a.nodeType)for(;c=f[e++];)d=eb.propFix[c]||c,eb.expr.match.bool.test(c)?Ac&&zc||!yc.test(c)?a[d]=!1:a[eb.camelCase("default-"+c)]=a[d]=!1:eb.attr(a,c,""),a.removeAttribute(zc?c:d)},attrHooks:{type:{set:function(a,b){if(!cb.radioValue&&"radio"===b&&eb.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),wc={set:function(a,b,c){return b===!1?eb.removeAttr(a,c):Ac&&zc||!yc.test(c)?a.setAttribute(!zc&&eb.propFix[c]||c,c):a[eb.camelCase("default-"+c)]=a[c]=!0,c}},eb.each(eb.expr.match.bool.source.match(/\w+/g),function(a,b){var c=xc[b]||eb.find.attr;xc[b]=Ac&&zc||!yc.test(b)?function(a,b,d){var e,f;return d||(f=xc[b],xc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,xc[b]=f),e}:function(a,b,c){return c?void 0:a[eb.camelCase("default-"+b)]?b.toLowerCase():null}}),Ac&&zc||(eb.attrHooks.value={set:function(a,b,c){return eb.nodeName(a,"input")?void(a.defaultValue=b):vc&&vc.set(a,b,c)}}),zc||(vc={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}},xc.id=xc.name=xc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},eb.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:vc.set},eb.attrHooks.contenteditable={set:function(a,b,c){vc.set(a,""===b?!1:b,c)}},eb.each(["width","height"],function(a,b){eb.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),cb.style||(eb.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var Bc=/^(?:input|select|textarea|button|object)$/i,Cc=/^(?:a|area)$/i;eb.fn.extend({prop:function(a,b){return Db(this,eb.prop,a,b,arguments.length>1)},removeProp:function(a){return a=eb.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),eb.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||!eb.isXMLDoc(a),f&&(b=eb.propFix[b]||b,e=eb.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=eb.find.attr(a,"tabindex");return b?parseInt(b,10):Bc.test(a.nodeName)||Cc.test(a.nodeName)&&a.href?0:-1}}}}),cb.hrefNormalized||eb.each(["href","src"],function(a,b){eb.propHooks[b]={get:function(a){return a.getAttribute(b,4) }}}),cb.optSelected||(eb.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),eb.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){eb.propFix[this.toLowerCase()]=this}),cb.enctype||(eb.propFix.enctype="encoding");var Dc=/[\t\r\n\f]/g;eb.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(eb.isFunction(a))return this.each(function(b){eb(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(tb)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(Dc," "):" ")){for(f=0;e=b[f++];)d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=eb.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(eb.isFunction(a))return this.each(function(b){eb(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(tb)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(Dc," "):"")){for(f=0;e=b[f++];)for(;d.indexOf(" "+e+" ")>=0;)d=d.replace(" "+e+" "," ");g=a?eb.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(eb.isFunction(a)?function(c){eb(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c)for(var b,d=0,e=eb(this),f=a.match(tb)||[];b=f[d++];)e.hasClass(b)?e.removeClass(b):e.addClass(b);else(c===xb||"boolean"===c)&&(this.className&&eb._data(this,"__className__",this.className),this.className=this.className||a===!1?"":eb._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(Dc," ").indexOf(b)>=0)return!0;return!1}}),eb.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){eb.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),eb.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 Ec=eb.now(),Fc=/\?/,Gc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;eb.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=eb.trim(b+"");return e&&!eb.trim(e.replace(Gc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():eb.error("Invalid JSON: "+b)},eb.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||eb.error("Invalid XML: "+b),c};var Hc,Ic,Jc=/#.*$/,Kc=/([?&])_=[^&]*/,Lc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Mc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nc=/^(?:GET|HEAD)$/,Oc=/^\/\//,Pc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Qc={},Rc={},Sc="*/".concat("*");try{Ic=location.href}catch(Tc){Ic=ob.createElement("a"),Ic.href="",Ic=Ic.href}Hc=Pc.exec(Ic.toLowerCase())||[],eb.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ic,type:"GET",isLocal:Mc.test(Hc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Sc,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":eb.parseJSON,"text xml":eb.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?P(P(a,eb.ajaxSettings),b):P(eb.ajaxSettings,a)},ajaxPrefilter:N(Qc),ajaxTransport:N(Rc),ajax:function(a,b){function c(a,b,c,d){var e,k,r,s,u,w=b;2!==t&&(t=2,h&&clearTimeout(h),j=void 0,g=d||"",v.readyState=a>0?4:0,e=a>=200&&300>a||304===a,c&&(s=Q(l,v,c)),s=R(l,s,v,e),e?(l.ifModified&&(u=v.getResponseHeader("Last-Modified"),u&&(eb.lastModified[f]=u),u=v.getResponseHeader("etag"),u&&(eb.etag[f]=u)),204===a||"HEAD"===l.type?w="nocontent":304===a?w="notmodified":(w=s.state,k=s.data,r=s.error,e=!r)):(r=w,(a||!w)&&(w="error",0>a&&(a=0))),v.status=a,v.statusText=(b||w)+"",e?o.resolveWith(m,[k,w,v]):o.rejectWith(m,[v,w,r]),v.statusCode(q),q=void 0,i&&n.trigger(e?"ajaxSuccess":"ajaxError",[v,l,e?k:r]),p.fireWith(m,[v,w]),i&&(n.trigger("ajaxComplete",[v,l]),--eb.active||eb.event.trigger("ajaxStop")))}"object"==typeof a&&(b=a,a=void 0),b=b||{};var d,e,f,g,h,i,j,k,l=eb.ajaxSetup({},b),m=l.context||l,n=l.context&&(m.nodeType||m.jquery)?eb(m):eb.event,o=eb.Deferred(),p=eb.Callbacks("once memory"),q=l.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!k)for(k={};b=Lc.exec(g);)k[b[1].toLowerCase()]=b[2];b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?g: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||(l.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 j&&j.abort(b),c(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,l.url=((a||l.url||Ic)+"").replace(Jc,"").replace(Oc,Hc[1]+"//"),l.type=b.method||b.type||l.method||l.type,l.dataTypes=eb.trim(l.dataType||"*").toLowerCase().match(tb)||[""],null==l.crossDomain&&(d=Pc.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===Hc[1]&&d[2]===Hc[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(Hc[3]||("http:"===Hc[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=eb.param(l.data,l.traditional)),O(Qc,l,b,v),2===t)return v;i=l.global,i&&0===eb.active++&&eb.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!Nc.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(Fc.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=Kc.test(f)?f.replace(Kc,"$1_="+Ec++):f+(Fc.test(f)?"&":"?")+"_="+Ec++)),l.ifModified&&(eb.lastModified[f]&&v.setRequestHeader("If-Modified-Since",eb.lastModified[f]),eb.etag[f]&&v.setRequestHeader("If-None-Match",eb.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",l.contentType),v.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Sc+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)v.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,v,l)===!1||2===t))return v.abort();u="abort";for(e in{success:1,error:1,complete:1})v[e](l[e]);if(j=O(Rc,l,b,v)){v.readyState=1,i&&n.trigger("ajaxSend",[v,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){v.abort("timeout")},l.timeout));try{t=1,j.send(r,c)}catch(w){if(!(2>t))throw w;c(-1,w)}}else c(-1,"No Transport");return v},getJSON:function(a,b,c){return eb.get(a,b,c,"json")},getScript:function(a,b){return eb.get(a,void 0,b,"script")}}),eb.each(["get","post"],function(a,b){eb[b]=function(a,c,d,e){return eb.isFunction(c)&&(e=e||d,d=c,c=void 0),eb.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),eb.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){eb.fn[b]=function(a){return this.on(b,a)}}),eb._evalUrl=function(a){return eb.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},eb.fn.extend({wrapAll:function(a){if(eb.isFunction(a))return this.each(function(b){eb(this).wrapAll(a.call(this,b))});if(this[0]){var b=eb(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){for(var a=this;a.firstChild&&1===a.firstChild.nodeType;)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(eb.isFunction(a)?function(b){eb(this).wrapInner(a.call(this,b))}:function(){var b=eb(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=eb.isFunction(a);return this.each(function(c){eb(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){eb.nodeName(this,"body")||eb(this).replaceWith(this.childNodes)}).end()}}),eb.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!cb.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||eb.css(a,"display"))},eb.expr.filters.visible=function(a){return!eb.expr.filters.hidden(a)};var Uc=/%20/g,Vc=/\[\]$/,Wc=/\r?\n/g,Xc=/^(?:submit|button|image|reset|file)$/i,Yc=/^(?:input|select|textarea|keygen)/i;eb.param=function(a,b){var c,d=[],e=function(a,b){b=eb.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=eb.ajaxSettings&&eb.ajaxSettings.traditional),eb.isArray(a)||a.jquery&&!eb.isPlainObject(a))eb.each(a,function(){e(this.name,this.value)});else for(c in a)S(c,a[c],b,e);return d.join("&").replace(Uc,"+")},eb.fn.extend({serialize:function(){return eb.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=eb.prop(this,"elements");return a?eb.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!eb(this).is(":disabled")&&Yc.test(this.nodeName)&&!Xc.test(a)&&(this.checked||!Eb.test(a))}).map(function(a,b){var c=eb(this).val();return null==c?null:eb.isArray(c)?eb.map(c,function(a){return{name:b.name,value:a.replace(Wc,"\r\n")}}):{name:b.name,value:c.replace(Wc,"\r\n")}}).get()}}),eb.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&T()||U()}:T;var Zc=0,$c={},_c=eb.ajaxSettings.xhr();a.ActiveXObject&&eb(a).on("unload",function(){for(var a in $c)$c[a](void 0,!0)}),cb.cors=!!_c&&"withCredentials"in _c,_c=cb.ajax=!!_c,_c&&eb.ajaxTransport(function(a){if(!a.crossDomain||cb.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Zc;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 $c[g],b=void 0,f.onreadystatechange=eb.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=$c[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}}),eb.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return eb.globalEval(a),a}}}),eb.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),eb.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=ob.head||eb("head")[0]||ob.documentElement;return{send:function(d,e){b=ob.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 ad=[],bd=/(=)\?(?=&|$)|\?\?/;eb.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||eb.expando+"_"+Ec++;return this[a]=!0,a}}),eb.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=eb.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(Fc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||eb.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,ad.push(e)),g&&eb.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),eb.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||ob;var d=lb.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=eb.buildFragment([a],b,e),e&&e.length&&eb(e).remove(),eb.merge([],d.childNodes))};var cd=eb.fn.load;eb.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=eb.trim(a.slice(h,a.length)),a=a.slice(0,h)),eb.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&eb.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?eb("<div>").append(eb.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},eb.expr.filters.animated=function(a){return eb.grep(eb.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;eb.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=eb.css(a,"position"),l=eb(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=eb.css(a,"top"),i=eb.css(a,"left"),j=("absolute"===k||"fixed"===k)&&eb.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),eb.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},eb.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){eb.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,eb.contains(b,e)?(typeof e.getBoundingClientRect!==xb&&(d=e.getBoundingClientRect()),c=V(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"===eb.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),eb.nodeName(a[0],"html")||(c=a.offset()),c.top+=eb.css(a[0],"borderTopWidth",!0),c.left+=eb.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-eb.css(d,"marginTop",!0),left:b.left-c.left-eb.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||dd;a&&!eb.nodeName(a,"html")&&"static"===eb.css(a,"position");)a=a.offsetParent;return a||dd})}}),eb.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);eb.fn[a]=function(d){return Db(this,function(a,d,e){var f=V(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?eb(f).scrollLeft():e,c?e:eb(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),eb.each(["top","left"],function(a,b){eb.cssHooks[b]=A(cb.pixelPosition,function(a,c){return c?(c=bc(a,b),dc.test(c)?eb(a).position()[b]+"px":c):void 0})}),eb.each({Height:"height",Width:"width"},function(a,b){eb.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){eb.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return Db(this,function(b,c,d){var e;return eb.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?eb.css(b,c,g):eb.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),eb.fn.size=function(){return this.length},eb.fn.andSelf=eb.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return eb});var ed=a.jQuery,fd=a.$;return eb.noConflict=function(b){return a.$===eb&&(a.$=fd),b&&a.jQuery===eb&&(a.jQuery=ed),eb},typeof b===xb&&(a.jQuery=a.$=eb),eb});
(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":4,"../lib/Shim.IE8":27}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; this._keys = []; 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, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { // Convert the index object to an array of key val objects this.keys(this.extractKeys(index)); } return this.$super.call(this, index); }); BinaryTree.prototype.extractKeys = 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._keys.length; i++) { indexData = this._keys[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._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._keys[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 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use) * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRange(type, key, from, to, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ BinaryTree.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(), indexKeyArr = pathSolver.parseArr(this._index), 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); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":23,"./Shared":26}],3:[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'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); 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.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } 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) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } 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()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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 = this.jStringify(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.isDropped()) { throw(this.logIdentifier() + ' 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.isDropped()) { throw(this.logIdentifier() + ' 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.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } 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, oldDoc, 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(this.logIdentifier() + ' 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': case '$min': case '$max': // 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], options, '', {})) { 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': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { 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(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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], options, '', {})) { 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(this.logIdentifier() + ' 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 = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(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(this.logIdentifier() + ' 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(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' 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], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' 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(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; 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.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } 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); }; /** * 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); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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 = this.jStringify(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 = this.jStringify(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 this._subsetOf === collection; }; /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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 = this.jStringify(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) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } 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.isDropped()) { throw(this.logIdentifier() + ' 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 = {}, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, '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) { // Don't 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); } op.time('tableScan: ' + scanLength); } // 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'); } 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(this.logIdentifier() + ' 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 = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ // 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], options, '', {})) { // 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], options, '', {})) { // 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') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value return new Path(query.substr(3, query.length - 3)).value(item)[0]; } 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 = String(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, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } 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(this.logIdentifier() + ' $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, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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 with no name (generates a random 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} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * 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(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' 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":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":26}],4:[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'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // 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":6,"./Metrics.js":10,"./Overload":22,"./Shared":26}],5:[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 }; },{}],6:[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 = {}; }; Shared.addModule('Db', Db); 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'); Shared.mixin(Db.prototype, 'Mixin.Tags'); 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'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * 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; }; 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. * @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.isDropped()) { 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.isDropped()) { 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.isDropped()) { 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.isDropped()) { 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); this._db[name].mongoEmulation(this.mongoEmulation()); 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; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":22,"./Shared":26}],7:[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":2,"./Path":23,"./Shared":26}],8:[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":23,"./Shared":26}],9:[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":26}],10:[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":21,"./Shared":26}],11:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],12:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } 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.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } 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 }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // 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; },{}],13:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * 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 this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * 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; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":22,"./Serialiser":25}],14:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],15:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ 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; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), 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, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.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 listenerIdArr = this._listeners[event]; 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++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * 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. */ 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(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":22}],16:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ 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 {Object} queryOptions The options the query was passed 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, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // 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 // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 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], queryOptions, 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], queryOptions, 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], queryOptions, 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], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, 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], queryOptions, 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], queryOptions, 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, queryOptions, 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], queryOptions, '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], queryOptions, '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(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; } return -1; } }; module.exports = Matching; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ 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; },{}],18:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],19:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ 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":22}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ 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(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * 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(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * 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 or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],21:[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":23,"./Shared":26}],22:[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: ' + this.jStringify(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; },{}],23:[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.Common'); 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; }; /** * 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; }; /** * 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":26}],24:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ 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); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { 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.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":26}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Register our handlers this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.392', modules: {}, plugins: {}, _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) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this 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]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } 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: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * 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: 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'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Tags":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],27:[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 = {}; },{}]},{},[1]);
/*! * vue-i18n v9.0.0-rc.7 * (c) 2021 kazuya kawaguchi * Released under the MIT License. */ var VueI18n = (function (exports, vue) { 'use strict'; /** * Original Utilities * written by kazuya kawaguchi */ const inBrowser = typeof window !== 'undefined'; let mark; let measure; { const perf = inBrowser && window.performance; if (perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures) { mark = (tag) => perf.mark(tag); measure = (name, startTag, endTag) => { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); }; } } const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g; /* eslint-disable */ function format(message, ...args) { if (args.length === 1 && isObject(args[0])) { args = args[0]; } if (!args || !args.hasOwnProperty) { args = {}; } return message.replace(RE_ARGS, (match, identifier) => { return args.hasOwnProperty(identifier) ? args[identifier] : ''; }); } const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; const makeSymbol = (name) => hasSymbol ? Symbol(name) : name; const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source }); const friendlyJSONstringify = (json) => JSON.stringify(json) .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') .replace(/\u0027/g, '\\u0027'); const isNumber = (val) => typeof val === 'number' && isFinite(val); const isDate = (val) => toTypeString(val) === '[object Date]'; const isRegExp = (val) => toTypeString(val) === '[object RegExp]'; const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0; function warn(msg, err) { if (typeof console !== 'undefined') { console.warn(`[intlify] ` + msg); /* istanbul ignore if */ if (err) { console.warn(err.stack); } } } let _globalThis; const getGlobalThis = () => { // prettier-ignore return (_globalThis || (_globalThis = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {})); }; function escapeHtml(rawText) { return rawText .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); } /* eslint-enable */ /** * Useful Utilities By Evan you * Modified by kazuya kawaguchi * MIT License * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts */ const isArray = Array.isArray; const isFunction = (val) => typeof val === 'function'; const isString = (val) => typeof val === 'string'; const isBoolean = (val) => typeof val === 'boolean'; const isObject = (val) => // eslint-disable-line val !== null && typeof val === 'object'; const objectToString = Object.prototype.toString; const toTypeString = (value) => objectToString.call(value); const isPlainObject = (val) => toTypeString(val) === '[object Object]'; // for converting list and named values to displayed strings. const toDisplayString = (val) => { return val == null ? '' : isArray(val) || (isPlainObject(val) && val.toString === objectToString) ? JSON.stringify(val, null, 2) : String(val); }; const RANGE = 2; function generateCodeFrame(source, start = 0, end = source.length) { const lines = source.split(/\r?\n/); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (let j = i - RANGE; j <= i + RANGE || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { // push underline const pad = start - (count - lineLength) + 1; const length = Math.max(1, end > count ? lineLength - pad : end - start); res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + '^'.repeat(length)); } count += lineLength + 1; } } break; } } return res.join('\n'); } /** * Vue I18n Version * * @remarks * Semver format. Same format as the package.json `version` field. * * @VueI18nGeneral */ const VERSION = '9.0.0-rc.7'; /** * This is only called development env * istanbul-ignore-next */ function initDev() { const target = getGlobalThis(); target.__INTLIFY__ = true; { console.info(`You are running a development build of vue-i18n.\n` + `Make sure to use the production build (*.prod.js) when deploying for production.`); } } const pathStateMachine = []; pathStateMachine[0 /* BEFORE_PATH */] = { ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */], ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */], ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */] }; pathStateMachine[1 /* IN_PATH */] = { ["w" /* WORKSPACE */]: [1 /* IN_PATH */], ["." /* DOT */]: [2 /* BEFORE_IDENT */], ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */], ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */] }; pathStateMachine[2 /* BEFORE_IDENT */] = { ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */], ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */] }; pathStateMachine[3 /* IN_IDENT */] = { ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */], ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */], ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */], ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */] }; pathStateMachine[4 /* IN_SUB_PATH */] = { ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */], ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */], ["[" /* LEFT_BRACKET */]: [ 4 /* IN_SUB_PATH */, 2 /* INC_SUB_PATH_DEPTH */ ], ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */], ["o" /* END_OF_FAIL */]: 8 /* ERROR */, ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */] }; pathStateMachine[5 /* IN_SINGLE_QUOTE */] = { ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */], ["o" /* END_OF_FAIL */]: 8 /* ERROR */, ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */] }; pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = { ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */], ["o" /* END_OF_FAIL */]: 8 /* ERROR */, ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */] }; /** * Check if an expression is a literal value. */ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/; function isLiteral(exp) { return literalValueRE.test(exp); } /** * Strip quotes from a string */ function stripQuotes(str) { const a = str.charCodeAt(0); const b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; } /** * Determine the type of a character in a keypath. */ function getPathCharType(ch) { if (ch === undefined || ch === null) { return "o" /* END_OF_FAIL */; } const code = ch.charCodeAt(0); switch (code) { case 0x5b: // [ case 0x5d: // ] case 0x2e: // . case 0x22: // " case 0x27: // ' return ch; case 0x5f: // _ case 0x24: // $ case 0x2d: // - return "i" /* IDENT */; case 0x09: // Tab (HT) case 0x0a: // Newline (LF) case 0x0d: // Return (CR) case 0xa0: // No-break space (NBSP) case 0xfeff: // Byte Order Mark (BOM) case 0x2028: // Line Separator (LS) case 0x2029: // Paragraph Separator (PS) return "w" /* WORKSPACE */; } return "i" /* IDENT */; } /** * Format a subPath, return its plain form if it is * a literal string or number. Otherwise prepend the * dynamic indicator (*). */ function formatSubPath(path) { const trimmed = path.trim(); // invalid leading 0 if (path.charAt(0) === '0' && isNaN(parseInt(path))) { return false; } return isLiteral(trimmed) ? stripQuotes(trimmed) : "*" /* ASTARISK */ + trimmed; } /** * Parse a string path into an array of segments */ function parse(path) { const keys = []; let index = -1; let mode = 0 /* BEFORE_PATH */; let subPathDepth = 0; let c; let key; // eslint-disable-line let newChar; let type; let transition; let action; let typeMap; const actions = []; actions[0 /* APPEND */] = () => { if (key === undefined) { key = newChar; } else { key += newChar; } }; actions[1 /* PUSH */] = () => { if (key !== undefined) { keys.push(key); key = undefined; } }; actions[2 /* INC_SUB_PATH_DEPTH */] = () => { actions[0 /* APPEND */](); subPathDepth++; }; actions[3 /* PUSH_SUB_PATH */] = () => { if (subPathDepth > 0) { subPathDepth--; mode = 4 /* IN_SUB_PATH */; actions[0 /* APPEND */](); } else { subPathDepth = 0; if (key === undefined) { return false; } key = formatSubPath(key); if (key === false) { return false; } else { actions[1 /* PUSH */](); } } }; function maybeUnescapeQuote() { const nextChar = path[index + 1]; if ((mode === 5 /* IN_SINGLE_QUOTE */ && nextChar === "'" /* SINGLE_QUOTE */) || (mode === 6 /* IN_DOUBLE_QUOTE */ && nextChar === "\"" /* DOUBLE_QUOTE */)) { index++; newChar = '\\' + nextChar; actions[0 /* APPEND */](); return true; } } while (mode !== null) { index++; c = path[index]; if (c === '\\' && maybeUnescapeQuote()) { continue; } type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */; // check parse error if (transition === 8 /* ERROR */) { return; } mode = transition[0]; if (transition[1] !== undefined) { action = actions[transition[1]]; if (action) { newChar = c; if (action() === false) { return; } } } // check parse finish if (mode === 7 /* AFTER_PATH */) { return keys; } } } // path token cache const cache = new Map(); function resolveValue(obj, path) { // check object if (!isObject(obj)) { return null; } // parse path let hit = cache.get(path); if (!hit) { hit = parse(path); if (hit) { cache.set(path, hit); } } // check hit if (!hit) { return null; } // resolve path value const len = hit.length; let last = obj; let i = 0; while (i < len) { const val = last[hit[i]]; if (val === undefined) { return null; } last = val; i++; } return last; } const DEFAULT_MODIFIER = (str) => str; const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line const DEFAULT_MESSAGE_DATA_TYPE = 'text'; const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join(''); const DEFAULT_INTERPOLATE = toDisplayString; function pluralDefault(choice, choicesLength) { choice = Math.abs(choice); if (choicesLength === 2) { // prettier-ignore return choice ? choice > 1 ? 1 : 0 : 1; } return choice ? Math.min(choice, 2) : 0; } function getPluralIndex(options) { // prettier-ignore const index = isNumber(options.pluralIndex) ? options.pluralIndex : -1; // prettier-ignore return options.named && (isNumber(options.named.count) || isNumber(options.named.n)) ? isNumber(options.named.count) ? options.named.count : isNumber(options.named.n) ? options.named.n : index : index; } function normalizeNamed(pluralIndex, props) { if (!props.count) { props.count = pluralIndex; } if (!props.n) { props.n = pluralIndex; } } function createMessageContext(options = {}) { const locale = options.locale; const pluralIndex = getPluralIndex(options); const pluralRule = isObject(options.pluralRules) && isString(locale) && isFunction(options.pluralRules[locale]) ? options.pluralRules[locale] : pluralDefault; const orgPluralRule = isObject(options.pluralRules) && isString(locale) && isFunction(options.pluralRules[locale]) ? pluralDefault : undefined; const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)]; const _list = options.list || []; const list = (index) => _list[index]; // eslint-disable-next-line @typescript-eslint/no-explicit-any const _named = options.named || {}; isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named); const named = (key) => _named[key]; // TODO: need to design resolve message function? function message(key) { // prettier-ignore const msg = isFunction(options.messages) ? options.messages(key) : isObject(options.messages) ? options.messages[key] : false; return !msg ? options.parent ? options.parent.message(key) // resolve from parent messages : DEFAULT_MESSAGE : msg; } const _modifier = (name) => options.modifiers ? options.modifiers[name] : DEFAULT_MODIFIER; const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize) ? options.processor.normalize : DEFAULT_NORMALIZE; const interpolate = isPlainObject(options.processor) && isFunction(options.processor.interpolate) ? options.processor.interpolate : DEFAULT_INTERPOLATE; const type = isPlainObject(options.processor) && isString(options.processor.type) ? options.processor.type : DEFAULT_MESSAGE_DATA_TYPE; const ctx = { ["list" /* LIST */]: list, ["named" /* NAMED */]: named, ["plural" /* PLURAL */]: plural, ["linked" /* LINKED */]: (key, modifier) => { // TODO: should check `key` const msg = message(key)(ctx); return isString(modifier) ? _modifier(modifier)(msg) : msg; }, ["message" /* MESSAGE */]: message, ["type" /* TYPE */]: type, ["interpolate" /* INTERPOLATE */]: interpolate, ["normalize" /* NORMALIZE */]: normalize }; return ctx; } /** @internal */ const errorMessages = { // tokenizer error messages [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, // parser error messages [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` }; function createCompileError(code, loc, options = {}) { const { domain, messages, args } = options; const msg = format((messages || errorMessages)[code] || '', ...(args || [])) ; const error = new SyntaxError(String(msg)); error.code = code; if (loc) { error.location = loc; } error.domain = domain; return error; } /** @internal */ const warnMessages = { [0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`, [1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`, [2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`, [3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`, [4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`, [5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.` }; function getWarnMessage(code, ...args) { return format(warnMessages[code], ...args); } const NOT_REOSLVED = -1; const MISSING_RESOLVE_VALUE = ''; function getDefaultLinkedModifiers() { return { upper: (val) => (isString(val) ? val.toUpperCase() : val), lower: (val) => (isString(val) ? val.toLowerCase() : val), // prettier-ignore capitalize: (val) => (isString(val) ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}` : val) }; } let _compiler; function createCoreContext(options = {}) { // setup options const locale = isString(options.locale) ? options.locale : 'en-US'; const fallbackLocale = isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || isString(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : locale; const messages = isPlainObject(options.messages) ? options.messages : { [locale]: {} }; const datetimeFormats = isPlainObject(options.datetimeFormats) ? options.datetimeFormats : { [locale]: {} }; const numberFormats = isPlainObject(options.numberFormats) ? options.numberFormats : { [locale]: {} }; const modifiers = Object.assign({}, options.modifiers || {}, getDefaultLinkedModifiers()); const pluralRules = options.pluralRules || {}; const missing = isFunction(options.missing) ? options.missing : null; const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn) ? options.missingWarn : true; const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) ? options.fallbackWarn : true; const fallbackFormat = !!options.fallbackFormat; const unresolving = !!options.unresolving; const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null; const processor = isPlainObject(options.processor) ? options.processor : null; const warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true; const escapeParameter = !!options.escapeParameter; const messageCompiler = isFunction(options.messageCompiler) ? options.messageCompiler : _compiler; const onWarn = isFunction(options.onWarn) ? options.onWarn : warn; // setup internal options const internalOptions = options; const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters) ? internalOptions.__datetimeFormatters : new Map(); const __numberFormatters = isObject(internalOptions.__numberFormatters) ? internalOptions.__numberFormatters : new Map(); const context = { locale, fallbackLocale, messages, datetimeFormats, numberFormats, modifiers, pluralRules, missing, missingWarn, fallbackWarn, fallbackFormat, unresolving, postTranslation, processor, warnHtmlMessage, escapeParameter, messageCompiler, onWarn, __datetimeFormatters, __numberFormatters }; // for vue-devtools timeline event { context.__emitter = internalOptions.__emitter != null ? internalOptions.__emitter : undefined; } return context; } /** @internal */ function isTranslateFallbackWarn(fallback, key) { return fallback instanceof RegExp ? fallback.test(key) : fallback; } /** @internal */ function isTranslateMissingWarn(missing, key) { return missing instanceof RegExp ? missing.test(key) : missing; } /** @internal */ function handleMissing(context, key, locale, missingWarn, type) { const { missing, onWarn } = context; // for vue-devtools timeline event { const emitter = context.__emitter; if (emitter) { emitter.emit("missing" /* MISSING */, { locale, key, type, groupId: `${type}:${key}` }); } } if (missing !== null) { const ret = missing(context, locale, key, type); return isString(ret) ? ret : key; } else { if ( isTranslateMissingWarn(missingWarn, key)) { onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale })); } return key; } } /** @internal */ function getLocaleChain(ctx, fallback, start) { const context = ctx; if (!context.__localeChainCache) { context.__localeChainCache = new Map(); } let chain = context.__localeChainCache.get(start); if (!chain) { chain = []; // first block defined by start let block = [start]; // while any intervening block found while (isArray(block)) { block = appendBlockToChain(chain, block, fallback); } // prettier-ignore // last block defined by default const defaults = isArray(fallback) ? fallback : isPlainObject(fallback) ? fallback['default'] ? fallback['default'] : null : fallback; // convert defaults to array block = isString(defaults) ? [defaults] : defaults; if (isArray(block)) { appendBlockToChain(chain, block, false); } context.__localeChainCache.set(start, chain); } return chain; } function appendBlockToChain(chain, block, blocks) { let follow = true; for (let i = 0; i < block.length && isBoolean(follow); i++) { const locale = block[i]; if (isString(locale)) { follow = appendLocaleToChain(chain, block[i], blocks); } } return follow; } function appendLocaleToChain(chain, locale, blocks) { let follow; const tokens = locale.split('-'); do { const target = tokens.join('-'); follow = appendItemToChain(chain, target, blocks); tokens.splice(-1, 1); } while (tokens.length && follow === true); return follow; } function appendItemToChain(chain, target, blocks) { let follow = false; if (!chain.includes(target)) { follow = true; if (target) { follow = target[target.length - 1] !== '!'; const locale = target.replace(/!/g, ''); chain.push(locale); if ((isArray(blocks) || isPlainObject(blocks)) && blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any ) { // eslint-disable-next-line @typescript-eslint/no-explicit-any follow = blocks[locale]; } } } return follow; } /** @internal */ function updateFallbackLocale(ctx, locale, fallback) { const context = ctx; context.__localeChainCache = new Map(); getLocaleChain(ctx, fallback, locale); } function createCoreError(code) { return createCompileError(code, null, { messages: errorMessages$1 } ); } /** @internal */ const errorMessages$1 = { [14 /* INVALID_ARGUMENT */]: 'Invalid arguments', [15 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' + 'Make sure your Date represents a valid date.', [16 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string' }; const NOOP_MESSAGE_FUNCTION = () => ''; const isMessageFunction = (val) => isFunction(val); // implementation of `translate` function function translate(context, ...args) { const { fallbackFormat, postTranslation, unresolving, fallbackLocale } = context; const [key, options] = parseTranslateArgs(...args); const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn; const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn; const escapeParameter = isBoolean(options.escapeParameter) ? options.escapeParameter : context.escapeParameter; // prettier-ignore const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option ? !isBoolean(options.default) ? options.default : key : fallbackFormat // default by `fallbackFormat` option ? key : ''; const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== ''; const locale = isString(options.locale) ? options.locale : context.locale; // escape params escapeParameter && escapeParams(options); // resolve message format // eslint-disable-next-line prefer-const let [format, targetLocale, message] = resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn); // if you use default message, set it as message format! let cacheBaseKey = key; if (!(isString(format) || isMessageFunction(format))) { if (enableDefaultMsg) { format = defaultMsgOrKey; cacheBaseKey = format; } } // checking message format and target locale if (!(isString(format) || isMessageFunction(format)) || !isString(targetLocale)) { return unresolving ? NOT_REOSLVED : key; } if ( isString(format) && context.messageCompiler == null) { warn(`The message format compilation is not supported in this build. ` + `Because message compiler isn't included. ` + `You need to pre-compilation all message format. ` + `So translate function return '${key}'.`); return key; } // setup compile error detecting let occurred = false; const errorDetector = () => { occurred = true; }; // compile message format const msg = compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector); // if occurred compile error, return the message format if (occurred) { return format; } // evaluate message with context const ctxOptions = getMessageContextOptions(context, targetLocale, message, options); const msgContext = createMessageContext(ctxOptions); const messaged = evaluateMessage(context, msg, msgContext); // if use post translation option, proceed it with handler return postTranslation ? postTranslation(messaged) : messaged; } function escapeParams(options) { if (isArray(options.list)) { options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item); } else if (isObject(options.named)) { Object.keys(options.named).forEach(key => { if (isString(options.named[key])) { options.named[key] = escapeHtml(options.named[key]); } }); } } function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) { const { messages, onWarn } = context; const locales = getLocaleChain(context, fallbackLocale, locale); let message = {}; let targetLocale; let format = null; let from = locale; let to = null; const type = 'translate'; for (let i = 0; i < locales.length; i++) { targetLocale = to = locales[i]; if ( locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) { onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, { key, target: targetLocale })); } // for vue-devtools timeline event if ( locale !== targetLocale) { const emitter = context.__emitter; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type, key, from, to, groupId: `${type}:${key}` }); } } message = messages[targetLocale] || {}; // for vue-devtools timeline event let start = null; let startTag; let endTag; if ( inBrowser) { start = window.performance.now(); startTag = 'intlify-message-resolve-start'; endTag = 'intlify-message-resolve-end'; mark && mark(startTag); } if ((format = resolveValue(message, key)) === null) { // if null, resolve with object key path format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any } // for vue-devtools timeline event if ( inBrowser) { const end = window.performance.now(); const emitter = context.__emitter; if (emitter && start && format) { emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, { type: "message-resolve" /* MESSAGE_RESOLVE */, key, message: format, time: end - start, groupId: `${type}:${key}` }); } if (startTag && endTag && mark && measure) { mark(endTag); measure('intlify message resolve', startTag, endTag); } } if (isString(format) || isFunction(format)) break; const missingRet = handleMissing(context, key, targetLocale, missingWarn, type); if (missingRet !== key) { format = missingRet; } from = to; } return [format, targetLocale, message]; } function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) { const { messageCompiler, warnHtmlMessage } = context; if (isMessageFunction(format)) { const msg = format; msg.locale = msg.locale || targetLocale; msg.key = msg.key || key; return msg; } // for vue-devtools timeline event let start = null; let startTag; let endTag; if ( inBrowser) { start = window.performance.now(); startTag = 'intlify-message-compilation-start'; endTag = 'intlify-message-compilation-end'; mark && mark(startTag); } const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector)); // for vue-devtools timeline event if ( inBrowser) { const end = window.performance.now(); const emitter = context.__emitter; if (emitter && start) { emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, { type: "message-compilation" /* MESSAGE_COMPILATION */, message: format, time: end - start, groupId: `${'translate'}:${key}` }); } if (startTag && endTag && mark && measure) { mark(endTag); measure('intlify message compilation', startTag, endTag); } } msg.locale = targetLocale; msg.key = key; msg.source = format; return msg; } function evaluateMessage(context, msg, msgCtx) { // for vue-devtools timeline event let start = null; let startTag; let endTag; if ( inBrowser) { start = window.performance.now(); startTag = 'intlify-message-evaluation-start'; endTag = 'intlify-message-evaluation-end'; mark && mark(startTag); } const messaged = msg(msgCtx); // for vue-devtools timeline event if ( inBrowser) { const end = window.performance.now(); const emitter = context.__emitter; if (emitter && start) { emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, { type: "message-evaluation" /* MESSAGE_EVALUATION */, value: messaged, time: end - start, groupId: `${'translate'}:${msg.key}` }); } if (startTag && endTag && mark && measure) { mark(endTag); measure('intlify message evaluation', startTag, endTag); } } return messaged; } /** @internal */ function parseTranslateArgs(...args) { const [arg1, arg2, arg3] = args; const options = {}; if (!isString(arg1) && !isNumber(arg1)) { throw createCoreError(14 /* INVALID_ARGUMENT */); } const key = isNumber(arg1) ? String(arg1) : arg1; if (isNumber(arg2)) { options.plural = arg2; } else if (isString(arg2)) { options.default = arg2; } else if (isPlainObject(arg2) && !isEmptyObject(arg2)) { options.named = arg2; } else if (isArray(arg2)) { options.list = arg2; } if (isNumber(arg3)) { options.plural = arg3; } else if (isString(arg3)) { options.default = arg3; } else if (isPlainObject(arg3)) { Object.assign(options, arg3); } return [key, options]; } function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) { return { warnHtmlMessage, onError: (err) => { errorDetector && errorDetector(err); { const message = `Message compilation error: ${err.message}`; const codeFrame = err.location && generateCodeFrame(source, err.location.start.offset, err.location.end.offset); const emitter = context.__emitter; if (emitter) { emitter.emit("compile-error" /* COMPILE_ERROR */, { message: source, error: err.message, start: err.location && err.location.start.offset, end: err.location && err.location.end.offset, groupId: `${'translate'}:${key}` }); } console.error(codeFrame ? `${message}\n${codeFrame}` : message); } }, onCacheKey: (source) => generateFormatCacheKey(locale, key, source) }; } function getMessageContextOptions(context, locale, message, options) { const { modifiers, pluralRules } = context; const resolveMessage = (key) => { const val = resolveValue(message, key); if (isString(val)) { let occurred = false; const errorDetector = () => { occurred = true; }; const msg = compileMessageFormat(context, key, locale, val, key, errorDetector); return !occurred ? msg : NOOP_MESSAGE_FUNCTION; } else if (isMessageFunction(val)) { return val; } else { // TODO: should be implemented warning message return NOOP_MESSAGE_FUNCTION; } }; const ctxOptions = { locale, modifiers, pluralRules, messages: resolveMessage }; if (context.processor) { ctxOptions.processor = context.processor; } if (options.list) { ctxOptions.list = options.list; } if (options.named) { ctxOptions.named = options.named; } if (isNumber(options.plural)) { ctxOptions.pluralIndex = options.plural; } return ctxOptions; } const intlDefined = typeof Intl !== 'undefined'; const Availabilities = { dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined', numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined' }; // implementation of `datetime` function function datetime(context, ...args) { const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context; const { __datetimeFormatters } = context; if ( !Availabilities.dateTimeFormat) { onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */)); return MISSING_RESOLVE_VALUE; } const [key, value, options, overrides] = parseDateTimeArgs(...args); const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn; const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn; const part = !!options.part; const locale = isString(options.locale) ? options.locale : context.locale; const locales = getLocaleChain(context, fallbackLocale, locale); if (!isString(key) || key === '') { return new Intl.DateTimeFormat(locale).format(value); } // resolve format let datetimeFormat = {}; let targetLocale; let format = null; let from = locale; let to = null; const type = 'datetime format'; for (let i = 0; i < locales.length; i++) { targetLocale = to = locales[i]; if ( locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) { onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, { key, target: targetLocale })); } // for vue-devtools timeline event if ( locale !== targetLocale) { const emitter = context.__emitter; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type, key, from, to, groupId: `${type}:${key}` }); } } datetimeFormat = datetimeFormats[targetLocale] || {}; format = datetimeFormat[key]; if (isPlainObject(format)) break; handleMissing(context, key, targetLocale, missingWarn, type); from = to; } // checking format and target locale if (!isPlainObject(format) || !isString(targetLocale)) { return unresolving ? NOT_REOSLVED : key; } let id = `${targetLocale}__${key}`; if (!isEmptyObject(overrides)) { id = `${id}__${JSON.stringify(overrides)}`; } let formatter = __datetimeFormatters.get(id); if (!formatter) { formatter = new Intl.DateTimeFormat(targetLocale, Object.assign({}, format, overrides)); __datetimeFormatters.set(id, formatter); } return !part ? formatter.format(value) : formatter.formatToParts(value); } /** @internal */ function parseDateTimeArgs(...args) { const [arg1, arg2, arg3, arg4] = args; let options = {}; let overrides = {}; let value; if (isString(arg1)) { // Only allow ISO strings - other date formats are often supported, // but may cause different results in different browsers. if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) { throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */); } value = new Date(arg1); try { // This will fail if the date is not valid value.toISOString(); } catch (e) { throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */); } } else if (isDate(arg1)) { if (isNaN(arg1.getTime())) { throw createCoreError(15 /* INVALID_DATE_ARGUMENT */); } value = arg1; } else if (isNumber(arg1)) { value = arg1; } else { throw createCoreError(14 /* INVALID_ARGUMENT */); } if (isString(arg2)) { options.key = arg2; } else if (isPlainObject(arg2)) { options = arg2; } if (isString(arg3)) { options.locale = arg3; } else if (isPlainObject(arg3)) { overrides = arg3; } if (isPlainObject(arg4)) { overrides = arg4; } return [options.key || '', value, options, overrides]; } /** @internal */ function clearDateTimeFormat(ctx, locale, format) { const context = ctx; for (const key in format) { const id = `${locale}__${key}`; if (!context.__datetimeFormatters.has(id)) { continue; } context.__datetimeFormatters.delete(id); } } // implementation of `number` function function number(context, ...args) { const { numberFormats, unresolving, fallbackLocale, onWarn } = context; const { __numberFormatters } = context; if ( !Availabilities.numberFormat) { onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */)); return MISSING_RESOLVE_VALUE; } const [key, value, options, overrides] = parseNumberArgs(...args); const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn; const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn; const part = !!options.part; const locale = isString(options.locale) ? options.locale : context.locale; const locales = getLocaleChain(context, fallbackLocale, locale); if (!isString(key) || key === '') { return new Intl.NumberFormat(locale).format(value); } // resolve format let numberFormat = {}; let targetLocale; let format = null; let from = locale; let to = null; const type = 'number format'; for (let i = 0; i < locales.length; i++) { targetLocale = to = locales[i]; if ( locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) { onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, { key, target: targetLocale })); } // for vue-devtools timeline event if ( locale !== targetLocale) { const emitter = context.__emitter; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type, key, from, to, groupId: `${type}:${key}` }); } } numberFormat = numberFormats[targetLocale] || {}; format = numberFormat[key]; if (isPlainObject(format)) break; handleMissing(context, key, targetLocale, missingWarn, type); from = to; } // checking format and target locale if (!isPlainObject(format) || !isString(targetLocale)) { return unresolving ? NOT_REOSLVED : key; } let id = `${targetLocale}__${key}`; if (!isEmptyObject(overrides)) { id = `${id}__${JSON.stringify(overrides)}`; } let formatter = __numberFormatters.get(id); if (!formatter) { formatter = new Intl.NumberFormat(targetLocale, Object.assign({}, format, overrides)); __numberFormatters.set(id, formatter); } return !part ? formatter.format(value) : formatter.formatToParts(value); } /** @internal */ function parseNumberArgs(...args) { const [arg1, arg2, arg3, arg4] = args; let options = {}; let overrides = {}; if (!isNumber(arg1)) { throw createCoreError(14 /* INVALID_ARGUMENT */); } const value = arg1; if (isString(arg2)) { options.key = arg2; } else if (isPlainObject(arg2)) { options = arg2; } if (isString(arg3)) { options.locale = arg3; } else if (isPlainObject(arg3)) { overrides = arg3; } if (isPlainObject(arg4)) { overrides = arg4; } return [options.key || '', value, options, overrides]; } /** @internal */ function clearNumberFormat(ctx, locale, format) { const context = ctx; for (const key in format) { const id = `${locale}__${key}`; if (!context.__numberFormatters.has(id)) { continue; } context.__numberFormatters.delete(id); } } const DevToolsLabels = { ["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools', ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources', ["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n' }; const DevToolsPlaceholders = { ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...' }; const DevToolsTimelineColors = { ["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19 }; /** * Event emitter, forked from the below: * - original repository url: https://github.com/developit/mitt * - code url: https://github.com/developit/mitt/blob/master/src/index.ts * - author: Jason Miller (https://github.com/developit) * - license: MIT */ /** * Create a event emitter * * @returns An event emitter */ function createEmitter() { const events = new Map(); const emitter = { events, on(event, handler) { const handlers = events.get(event); const added = handlers && handlers.push(handler); if (!added) { events.set(event, [handler]); } }, off(event, handler) { const handlers = events.get(event); if (handlers) { handlers.splice(handlers.indexOf(handler) >>> 0, 1); } }, emit(event, payload) { (events.get(event) || []) .slice() .map(handler => handler(payload)); (events.get('*') || []) .slice() .map(handler => handler(event, payload)); } }; return emitter; } const warnMessages$1 = { [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` }; function getWarnMessage$1(code, ...args) { return format(warnMessages$1[code], ...args); } function createI18nError(code, ...args) { return createCompileError(code, null, { messages: errorMessages$2, args } ); } const errorMessages$2 = { [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', [15 /* INVALID_ARGUMENT */]: 'Invalid argument', [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, [20 /* INVALID_VALUE */]: `Invalid value`, [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` }; const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); const DatetimePartsSymbol = makeSymbol('__datetimeParts'); const NumberPartsSymbol = makeSymbol('__numberParts'); const EnableEmitter = makeSymbol('__enableEmitter'); const DisableEmitter = makeSymbol('__disableEmitter'); let composerID = 0; function defineCoreMissingHandler(missing) { return ((ctx, locale, key, type) => { return missing(locale, key, vue.getCurrentInstance() || undefined, type); }); } function getLocaleMessages(locale, options) { const { messages, __i18n } = options; // prettier-ignore const ret = isPlainObject(messages) ? messages : isArray(__i18n) ? {} : { [locale]: {} }; // merge locale messages of i18n custom block if (isArray(__i18n)) { __i18n.forEach(({ locale, resource }) => { if (locale) { ret[locale] = ret[locale] || {}; deepCopy(resource, ret[locale]); } else { deepCopy(resource, ret); } }); } return ret; } const hasOwnProperty = Object.prototype.hasOwnProperty; // eslint-disable-next-line @typescript-eslint/no-explicit-any function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); // eslint-disable-next-line @typescript-eslint/no-explicit-any function deepCopy(src, des) { // src and des should both be objects, and non of then can be a array if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { throw createI18nError(20 /* INVALID_VALUE */); } for (const key in src) { if (hasOwn(src, key)) { if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { // replace with src[key] when: // src[key] or des[key] is not a object, or // src[key] or des[key] is a array des[key] = src[key]; } else { // src[key] and des[key] are both object, merge them deepCopy(src[key], des[key]); } } } } /** * Create composer interface factory * * @internal */ function createComposer(options = {}) { const { __root } = options; const _isGlobal = __root === undefined; let _inheritLocale = isBoolean(options.inheritLocale) ? options.inheritLocale : true; const _locale = vue.ref( // prettier-ignore __root && _inheritLocale ? __root.locale.value : isString(options.locale) ? options.locale : 'en-US'); const _fallbackLocale = vue.ref( // prettier-ignore __root && _inheritLocale ? __root.fallbackLocale.value : isString(options.fallbackLocale) || isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : _locale.value); const _messages = vue.ref(getLocaleMessages(_locale.value, options)); const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats) ? options.datetimeFormats : { [_locale.value]: {} }); const _numberFormats = vue.ref(isPlainObject(options.numberFormats) ? options.numberFormats : { [_locale.value]: {} }); // warning suppress options // prettier-ignore let _missingWarn = __root ? __root.missingWarn : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) ? options.missingWarn : true; // prettier-ignore let _fallbackWarn = __root ? __root.fallbackWarn : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) ? options.fallbackWarn : true; // prettier-ignore let _fallbackRoot = __root ? __root.fallbackRoot : isBoolean(options.fallbackRoot) ? options.fallbackRoot : true; // configure fall back to root let _fallbackFormat = !!options.fallbackFormat; // runtime missing let _missing = isFunction(options.missing) ? options.missing : null; let _runtimeMissing = isFunction(options.missing) ? defineCoreMissingHandler(options.missing) : null; // postTranslation handler let _postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null; let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true; let _escapeParameter = !!options.escapeParameter; // custom linked modifiers // prettier-ignore const _modifiers = __root ? __root.modifiers : isPlainObject(options.modifiers) ? options.modifiers : {}; // pluralRules const _pluralRules = options.pluralRules; // runtime context // eslint-disable-next-line prefer-const let _context; function getCoreContext() { return createCoreContext({ locale: _locale.value, fallbackLocale: _fallbackLocale.value, messages: _messages.value, datetimeFormats: _datetimeFormats.value, numberFormats: _numberFormats.value, modifiers: _modifiers, pluralRules: _pluralRules, missing: _runtimeMissing === null ? undefined : _runtimeMissing, missingWarn: _missingWarn, fallbackWarn: _fallbackWarn, fallbackFormat: _fallbackFormat, unresolving: true, postTranslation: _postTranslation === null ? undefined : _postTranslation, warnHtmlMessage: _warnHtmlMessage, escapeParameter: _escapeParameter, __datetimeFormatters: isPlainObject(_context) ? _context.__datetimeFormatters : undefined, __numberFormatters: isPlainObject(_context) ? _context.__numberFormatters : undefined, __emitter: isPlainObject(_context) ? _context.__emitter : undefined }); } _context = getCoreContext(); updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); // locale const locale = vue.computed({ get: () => _locale.value, set: val => { _locale.value = val; _context.locale = _locale.value; } }); // fallbackLocale const fallbackLocale = vue.computed({ get: () => _fallbackLocale.value, set: val => { _fallbackLocale.value = val; _context.fallbackLocale = _fallbackLocale.value; updateFallbackLocale(_context, _locale.value, val); } }); // messages const messages = vue.computed(() => _messages.value); // datetimeFormats const datetimeFormats = vue.computed(() => _datetimeFormats.value); // numberFormats const numberFormats = vue.computed(() => _numberFormats.value); // getPostTranslationHandler function getPostTranslationHandler() { return isFunction(_postTranslation) ? _postTranslation : null; } // setPostTranslationHandler function setPostTranslationHandler(handler) { _postTranslation = handler; _context.postTranslation = handler; } // getMissingHandler function getMissingHandler() { return _missing; } // setMissingHandler function setMissingHandler(handler) { if (handler !== null) { _runtimeMissing = defineCoreMissingHandler(handler); } _missing = handler; _context.missing = _runtimeMissing; } function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { const context = getCoreContext(); const ret = fn(context); // track reactive dependency, see the getRuntimeContext if (isNumber(ret) && ret === NOT_REOSLVED) { const key = argumentParser(); if ( __root) { if (!_fallbackRoot) { warn(getWarnMessage$1(6 /* FALLBACK_TO_ROOT */, { key, type: warnType })); } // for vue-devtools timeline event { const { __emitter: emitter } = context; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type: warnType, key, to: 'global', groupId: `${warnType}:${key}` }); } } } return __root && _fallbackRoot ? fallbackSuccess(__root) : fallbackFail(key); } else if (successCondition(ret)) { return ret; } else { /* istanbul ignore next */ throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); } } // t function t(...args) { return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val)); } // d function d(...args) { return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); } // n function n(...args) { return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); } // for custom processor function normalize(values) { return values.map(val => isString(val) ? vue.createVNode(vue.Text, null, val, 0) : val); } const interpolate = (val) => val; const processor = { normalize, interpolate, type: 'vnode' }; // __transrateVNode, using for `i18n-t` component function __transrateVNode(...args) { return wrapWithDeps(context => { let ret; const _context = context; try { _context.processor = processor; ret = translate(_context, ...args); } finally { _context.processor = null; } return ret; }, () => parseTranslateArgs(...args)[0], 'translate', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[TransrateVNodeSymbol](...args), key => [vue.createVNode(vue.Text, null, key, 0)], val => isArray(val)); } // __numberParts, using for `i18n-n` component function __numberParts(...args) { return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); } // __datetimeParts, using for `i18n-d` component function __datetimeParts(...args) { return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); } // te function te(key, locale) { const targetLocale = isString(locale) ? locale : _locale.value; const message = getLocaleMessage(targetLocale); return resolveValue(message, key) !== null; } // tm function tm(key) { const messages = _messages.value[_locale.value] || {}; const target = resolveValue(messages, key); // prettier-ignore return target != null ? target : __root ? __root.tm(key) || {} : {}; } // getLocaleMessage function getLocaleMessage(locale) { return (_messages.value[locale] || {}); } // setLocaleMessage function setLocaleMessage(locale, message) { _messages.value[locale] = message; _context.messages = _messages.value; } // mergeLocaleMessage function mergeLocaleMessage(locale, message) { _messages.value[locale] = _messages.value[locale] || {}; deepCopy(message, _messages.value[locale]); _context.messages = _messages.value; } // getDateTimeFormat function getDateTimeFormat(locale) { return _datetimeFormats.value[locale] || {}; } // setDateTimeFormat function setDateTimeFormat(locale, format) { _datetimeFormats.value[locale] = format; _context.datetimeFormats = _datetimeFormats.value; clearDateTimeFormat(_context, locale, format); } // mergeDateTimeFormat function mergeDateTimeFormat(locale, format) { _datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format); _context.datetimeFormats = _datetimeFormats.value; clearDateTimeFormat(_context, locale, format); } // getNumberFormat function getNumberFormat(locale) { return _numberFormats.value[locale] || {}; } // setNumberFormat function setNumberFormat(locale, format) { _numberFormats.value[locale] = format; _context.numberFormats = _numberFormats.value; clearNumberFormat(_context, locale, format); } // mergeNumberFormat function mergeNumberFormat(locale, format) { _numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format); _context.numberFormats = _numberFormats.value; clearNumberFormat(_context, locale, format); } // for debug composerID++; // watch root locale & fallbackLocale if (__root) { vue.watch(__root.locale, (val) => { if (_inheritLocale) { _locale.value = val; _context.locale = val; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }); vue.watch(__root.fallbackLocale, (val) => { if (_inheritLocale) { _fallbackLocale.value = val; _context.fallbackLocale = val; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }); } // export composition API! const composer = { id: composerID, locale, fallbackLocale, get inheritLocale() { return _inheritLocale; }, set inheritLocale(val) { _inheritLocale = val; if (val && __root) { _locale.value = __root.locale.value; _fallbackLocale.value = __root.fallbackLocale.value; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }, get availableLocales() { return Object.keys(_messages.value).sort(); }, messages, datetimeFormats, numberFormats, get modifiers() { return _modifiers; }, get pluralRules() { return _pluralRules || {}; }, get isGlobal() { return _isGlobal; }, get missingWarn() { return _missingWarn; }, set missingWarn(val) { _missingWarn = val; _context.missingWarn = _missingWarn; }, get fallbackWarn() { return _fallbackWarn; }, set fallbackWarn(val) { _fallbackWarn = val; _context.fallbackWarn = _fallbackWarn; }, get fallbackRoot() { return _fallbackRoot; }, set fallbackRoot(val) { _fallbackRoot = val; }, get fallbackFormat() { return _fallbackFormat; }, set fallbackFormat(val) { _fallbackFormat = val; _context.fallbackFormat = _fallbackFormat; }, get warnHtmlMessage() { return _warnHtmlMessage; }, set warnHtmlMessage(val) { _warnHtmlMessage = val; _context.warnHtmlMessage = val; }, get escapeParameter() { return _escapeParameter; }, set escapeParameter(val) { _escapeParameter = val; _context.escapeParameter = val; }, t, d, n, te, tm, getLocaleMessage, setLocaleMessage, mergeLocaleMessage, getDateTimeFormat, setDateTimeFormat, mergeDateTimeFormat, getNumberFormat, setNumberFormat, mergeNumberFormat, getPostTranslationHandler, setPostTranslationHandler, getMissingHandler, setMissingHandler, [TransrateVNodeSymbol]: __transrateVNode, [NumberPartsSymbol]: __numberParts, [DatetimePartsSymbol]: __datetimeParts }; // for vue-devtools timeline event { composer[EnableEmitter] = (emitter) => { _context.__emitter = emitter; }; composer[DisableEmitter] = () => { _context.__emitter = undefined; }; } return composer; } /** * Convert to I18n Composer Options from VueI18n Options * * @internal */ function convertComposerOptions(options) { const locale = isString(options.locale) ? options.locale : 'en-US'; const fallbackLocale = isString(options.fallbackLocale) || isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : locale; const missing = isFunction(options.missing) ? options.missing : undefined; const missingWarn = isBoolean(options.silentTranslationWarn) || isRegExp(options.silentTranslationWarn) ? !options.silentTranslationWarn : true; const fallbackWarn = isBoolean(options.silentFallbackWarn) || isRegExp(options.silentFallbackWarn) ? !options.silentFallbackWarn : true; const fallbackRoot = isBoolean(options.fallbackRoot) ? options.fallbackRoot : true; const fallbackFormat = !!options.formatFallbackMessages; const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; const pluralizationRules = options.pluralizationRules; const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : undefined; const warnHtmlMessage = isString(options.warnHtmlInMessage) ? options.warnHtmlInMessage !== 'off' : true; const escapeParameter = !!options.escapeParameterHtml; const inheritLocale = isBoolean(options.sync) ? options.sync : true; if ( options.formatter) { warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */)); } if ( options.preserveDirectiveContent) { warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); } let messages = options.messages; if (isPlainObject(options.sharedMessages)) { const sharedMessages = options.sharedMessages; const locales = Object.keys(sharedMessages); messages = locales.reduce((messages, locale) => { const message = messages[locale] || (messages[locale] = {}); Object.assign(message, sharedMessages[locale]); return messages; }, (messages || {})); } const { __i18n, __root } = options; const datetimeFormats = options.datetimeFormats; const numberFormats = options.numberFormats; return { locale, fallbackLocale, messages, datetimeFormats, numberFormats, missing, missingWarn, fallbackWarn, fallbackRoot, fallbackFormat, modifiers, pluralRules: pluralizationRules, postTranslation, warnHtmlMessage, escapeParameter, inheritLocale, __i18n, __root }; } /** * create VueI18n interface factory * * @internal */ function createVueI18n(options = {}) { const composer = createComposer(convertComposerOptions(options)); // defines VueI18n const vueI18n = { // id id: composer.id, // locale get locale() { return composer.locale.value; }, set locale(val) { composer.locale.value = val; }, // fallbackLocale get fallbackLocale() { return composer.fallbackLocale.value; }, set fallbackLocale(val) { composer.fallbackLocale.value = val; }, // messages get messages() { return composer.messages.value; }, // datetimeFormats get datetimeFormats() { return composer.datetimeFormats.value; }, // numberFormats get numberFormats() { return composer.numberFormats.value; }, // availableLocales get availableLocales() { return composer.availableLocales; }, // formatter get formatter() { warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */)); // dummy return { interpolate() { return []; } }; }, set formatter(val) { warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */)); }, // missing get missing() { return composer.getMissingHandler(); }, set missing(handler) { composer.setMissingHandler(handler); }, // silentTranslationWarn get silentTranslationWarn() { return isBoolean(composer.missingWarn) ? !composer.missingWarn : composer.missingWarn; }, set silentTranslationWarn(val) { composer.missingWarn = isBoolean(val) ? !val : val; }, // silentFallbackWarn get silentFallbackWarn() { return isBoolean(composer.fallbackWarn) ? !composer.fallbackWarn : composer.fallbackWarn; }, set silentFallbackWarn(val) { composer.fallbackWarn = isBoolean(val) ? !val : val; }, // modifiers get modifiers() { return composer.modifiers; }, // formatFallbackMessages get formatFallbackMessages() { return composer.fallbackFormat; }, set formatFallbackMessages(val) { composer.fallbackFormat = val; }, // postTranslation get postTranslation() { return composer.getPostTranslationHandler(); }, set postTranslation(handler) { composer.setPostTranslationHandler(handler); }, // sync get sync() { return composer.inheritLocale; }, set sync(val) { composer.inheritLocale = val; }, // warnInHtmlMessage get warnHtmlInMessage() { return composer.warnHtmlMessage ? 'warn' : 'off'; }, set warnHtmlInMessage(val) { composer.warnHtmlMessage = val !== 'off'; }, // escapeParameterHtml get escapeParameterHtml() { return composer.escapeParameter; }, set escapeParameterHtml(val) { composer.escapeParameter = val; }, // preserveDirectiveContent get preserveDirectiveContent() { warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); return true; }, set preserveDirectiveContent(val) { warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); }, // pluralizationRules get pluralizationRules() { return composer.pluralRules || {}; }, // for internal __composer: composer, // t t(...args) { const [arg1, arg2, arg3] = args; const options = {}; let list = null; let named = null; if (!isString(arg1)) { throw createI18nError(15 /* INVALID_ARGUMENT */); } const key = arg1; if (isString(arg2)) { options.locale = arg2; } else if (isArray(arg2)) { list = arg2; } else if (isPlainObject(arg2)) { named = arg2; } if (isArray(arg3)) { list = arg3; } else if (isPlainObject(arg3)) { named = arg3; } return composer.t(key, list || named || {}, options); }, // tc tc(...args) { const [arg1, arg2, arg3] = args; const options = { plural: 1 }; let list = null; let named = null; if (!isString(arg1)) { throw createI18nError(15 /* INVALID_ARGUMENT */); } const key = arg1; if (isString(arg2)) { options.locale = arg2; } else if (isNumber(arg2)) { options.plural = arg2; } else if (isArray(arg2)) { list = arg2; } else if (isPlainObject(arg2)) { named = arg2; } if (isString(arg3)) { options.locale = arg3; } else if (isArray(arg3)) { list = arg3; } else if (isPlainObject(arg3)) { named = arg3; } return composer.t(key, list || named || {}, options); }, // te te(key, locale) { return composer.te(key, locale); }, // tm tm(key) { return composer.tm(key); }, // getLocaleMessage getLocaleMessage(locale) { return composer.getLocaleMessage(locale); }, // setLocaleMessage setLocaleMessage(locale, message) { composer.setLocaleMessage(locale, message); }, // mergeLocaleMessage mergeLocaleMessage(locale, message) { composer.mergeLocaleMessage(locale, message); }, // d d(...args) { return composer.d(...args); }, // getDateTimeFormat getDateTimeFormat(locale) { return composer.getDateTimeFormat(locale); }, // setDateTimeFormat setDateTimeFormat(locale, format) { composer.setDateTimeFormat(locale, format); }, // mergeDateTimeFormat mergeDateTimeFormat(locale, format) { composer.mergeDateTimeFormat(locale, format); }, // n n(...args) { return composer.n(...args); }, // getNumberFormat getNumberFormat(locale) { return composer.getNumberFormat(locale); }, // setNumberFormat setNumberFormat(locale, format) { composer.setNumberFormat(locale, format); }, // mergeNumberFormat mergeNumberFormat(locale, format) { composer.mergeNumberFormat(locale, format); }, // getChoiceIndex // eslint-disable-next-line @typescript-eslint/no-unused-vars getChoiceIndex(choice, choicesLength) { warn(getWarnMessage$1(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); return -1; }, // for internal __onComponentInstanceCreated(target) { const { componentInstanceCreatedListener } = options; if (componentInstanceCreatedListener) { componentInstanceCreatedListener(target, vueI18n); } } }; // for vue-devtools timeline event { vueI18n.__enableEmitter = (emitter) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const __composer = composer; __composer[EnableEmitter] && __composer[EnableEmitter](emitter); }; vueI18n.__disableEmitter = () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const __composer = composer; __composer[DisableEmitter] && __composer[DisableEmitter](); }; } return vueI18n; } const baseFormatProps = { tag: { type: [String, Object] }, locale: { type: String }, scope: { type: String, validator: (val) => val === 'parent' || val === 'global', default: 'parent' } }; /** * Translation Component * * @remarks * See the following items for property about details * * @VueI18nSee [TranslationProps](component#translationprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Component Interpolation](../../guide/advanced/component) * * @example * ```html * <div id="app"> * <!-- ... --> * <i18n path="term" tag="label" for="tos"> * <a :href="url" target="_blank">{{ $t('tos') }}</a> * </i18n> * <!-- ... --> * </div> * ``` * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * const messages = { * en: { * tos: 'Term of Service', * term: 'I accept xxx {0}.' * }, * ja: { * tos: '利用規約', * term: '私は xxx の{0}に同意します。' * } * } * * const i18n = createI18n({ * locale: 'en', * messages * }) * * const app = createApp({ * data: { * url: '/term' * } * }).use(i18n).mount('#app') * ``` * * @VueI18nComponent */ const Translation = { /* eslint-disable */ name: 'i18n-t', props: { ...baseFormatProps, keypath: { type: String, required: true }, plural: { type: [Number, String], // eslint-disable-next-line @typescript-eslint/no-explicit-any validator: (val) => isNumber(val) || !isNaN(val) } }, /* eslint-enable */ setup(props, context) { const { slots, attrs } = context; const i18n = useI18n({ useScope: props.scope }); const keys = Object.keys(slots).filter(key => key !== '_'); return () => { const options = {}; if (props.locale) { options.locale = props.locale; } if (props.plural !== undefined) { options.plural = isString(props.plural) ? +props.plural : props.plural; } const arg = getInterpolateArg(context, keys); // eslint-disable-next-line @typescript-eslint/no-explicit-any const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); // prettier-ignore return isString(props.tag) ? vue.h(props.tag, { ...attrs }, children) : isObject(props.tag) ? vue.h(props.tag, { ...attrs }, children) : vue.h(vue.Fragment, { ...attrs }, children); }; } }; function getInterpolateArg({ slots }, keys) { if (keys.length === 1 && keys[0] === 'default') { // default slot only return slots.default ? slots.default() : []; } else { // named slots return keys.reduce((arg, key) => { const slot = slots[key]; if (slot) { arg[key] = slot(); } return arg; }, {}); } } function renderFormatter(props, context, slotKeys, partFormatter) { const { slots, attrs } = context; return () => { const options = { part: true }; let overrides = {}; if (props.locale) { options.locale = props.locale; } if (isString(props.format)) { options.key = props.format; } else if (isObject(props.format)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (isString(props.format.key)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any options.key = props.format.key; } // Filter out number format options only overrides = Object.keys(props.format).reduce((options, prop) => { return slotKeys.includes(prop) ? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any : options; }, {}); } const parts = partFormatter(...[props.value, options, overrides]); let children = [options.key]; if (isArray(parts)) { children = parts.map((part, index) => { const slot = slots[part.type]; return slot ? slot({ [part.type]: part.value, index, parts }) : [part.value]; }); } else if (isString(parts)) { children = [parts]; } // prettier-ignore return isString(props.tag) ? vue.h(props.tag, { ...attrs }, children) : isObject(props.tag) ? vue.h(props.tag, { ...attrs }, children) : vue.h(vue.Fragment, { ...attrs }, children); }; } const NUMBER_FORMAT_KEYS = [ 'localeMatcher', 'style', 'unit', 'unitDisplay', 'currency', 'currencyDisplay', 'useGrouping', 'numberingSystem', 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits', 'notation', 'formatMatcher' ]; /** * Number Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../../guide/essentials/number#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) * * @VueI18nComponent */ const NumberFormat = { /* eslint-disable */ name: 'i18n-n', props: { ...baseFormatProps, value: { type: Number, required: true }, format: { type: [String, Object] } }, /* eslint-enable */ setup(props, context) { const i18n = useI18n({ useScope: 'parent' }); return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => // eslint-disable-next-line @typescript-eslint/no-explicit-any i18n[NumberPartsSymbol](...args)); } }; const DATETIME_FORMAT_KEYS = [ 'dateStyle', 'timeStyle', 'fractionalSecondDigits', 'calendar', 'dayPeriod', 'numberingSystem', 'localeMatcher', 'timeZone', 'hour12', 'hourCycle', 'formatMatcher', 'weekday', 'era', 'year', 'month', 'day', 'hour', 'minute', 'second', 'timeZoneName' ]; /** * Datetime Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../../guide/essentials/datetime#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) * * @VueI18nComponent */ const DatetimeFormat = { /* eslint-disable */ name: 'i18n-d', props: { ...baseFormatProps, value: { type: [Number, Date], required: true }, format: { type: [String, Object] } }, /* eslint-enable */ setup(props, context) { const i18n = useI18n({ useScope: 'parent' }); return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => // eslint-disable-next-line @typescript-eslint/no-explicit-any i18n[DatetimePartsSymbol](...args)); } }; function getComposer(i18n, instance) { const i18nInternal = i18n; if (i18n.mode === 'composition') { return (i18nInternal.__getInstance(instance) || i18n.global); } else { const vueI18n = i18nInternal.__getInstance(instance); return vueI18n != null ? vueI18n.__composer : i18n.global.__composer; } } function vTDirective(i18n) { const bind = (el, { instance, value, modifiers }) => { /* istanbul ignore if */ if (!instance || !instance.$) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } const composer = getComposer(i18n, instance.$); if ( modifiers.preserve) { warn(getWarnMessage$1(7 /* NOT_SUPPORTED_PRESERVE */)); } const parsedValue = parseValue(value); el.textContent = composer.t(...makeParams(parsedValue)); }; return { beforeMount: bind, beforeUpdate: bind }; } function parseValue(value) { if (isString(value)) { return { path: value }; } else if (isPlainObject(value)) { if (!('path' in value)) { throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); } return value; } else { throw createI18nError(20 /* INVALID_VALUE */); } } function makeParams(value) { const { path, locale, args, choice, plural } = value; const options = {}; const named = args || {}; if (isString(locale)) { options.locale = locale; } if (isNumber(choice)) { options.plural = choice; } if (isNumber(plural)) { options.plural = plural; } return [path, named, options]; } function apply(app, i18n, ...options) { const pluginOptions = isPlainObject(options[0]) ? options[0] : {}; const useI18nComponentName = !!pluginOptions.useI18nComponentName; const globalInstall = isBoolean(pluginOptions.globalInstall) ? pluginOptions.globalInstall : true; if ( globalInstall && useI18nComponentName) { warn(getWarnMessage$1(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { name: Translation.name })); } if (globalInstall) { // install components app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); app.component(NumberFormat.name, NumberFormat); app.component(DatetimeFormat.name, DatetimeFormat); } // install directive app.directive('t', vTDirective(i18n)); } var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); function getDevtoolsGlobalHook() { return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__; } function getTarget() { // @ts-ignore return typeof navigator !== 'undefined' ? window : typeof global$1 !== 'undefined' ? global$1 : {}; } const HOOK_SETUP = 'devtools-plugin:setup'; function setupDevtoolsPlugin(pluginDescriptor, setupFn) { const hook = getDevtoolsGlobalHook(); if (hook) { hook.emit(HOOK_SETUP, pluginDescriptor, setupFn); } else { const target = getTarget(); const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || []; list.push({ pluginDescriptor, setupFn }); } } let devtoolsApi; async function enableDevTools(app, i18n) { return new Promise((resolve, reject) => { try { setupDevtoolsPlugin({ id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], app }, api => { devtoolsApi = api; api.on.walkComponentTree((payload, ctx) => { updateComponentTreeDataTags(ctx.currentAppRecord, payload.componentTreeData, i18n); }); api.on.inspectComponent(payload => { const componentInstance = payload.componentInstance; if (componentInstance.vnode.el.__INTLIFY__ && payload.instanceData) { if (i18n.mode === 'legacy') { // ignore global scope on legacy mode if (componentInstance.vnode.el.__INTLIFY__ !== i18n.global.__composer) { inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__); } } else { inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__); } } }); api.addInspector({ id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], icon: 'language', treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] }); api.on.getInspectorTree(payload => { if (payload.app === app && payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { registerScope(payload, i18n); } }); api.on.getInspectorState(payload => { if (payload.app === app && payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { inspectScope(payload, i18n); } }); api.addTimelineLayer({ id: "vue-i18n-timeline" /* TIMELINE */, label: DevToolsLabels["vue-i18n-timeline" /* TIMELINE */], color: DevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] }); resolve(true); }); } catch (e) { console.error(e); reject(false); } }); } function updateComponentTreeDataTags(appRecord, treeData, i18n) { // prettier-ignore const global = i18n.mode === 'composition' ? i18n.global : i18n.global.__composer; for (const node of treeData) { const instance = appRecord.instanceMap.get(node.id); if (instance && instance.vnode.el.__INTLIFY__) { // add custom tags local scope only if (instance.vnode.el.__INTLIFY__ !== global) { const label = instance.type.name || instance.type.displayName || instance.type.__file; const tag = { label: `i18n (${label} Scope)`, textColor: 0x000000, backgroundColor: 0xffcd19 }; node.tags.push(tag); } } updateComponentTreeDataTags(appRecord, node.children, i18n); } } function inspectComposer(instanceData, composer) { const type = 'vue-i18n: composer properties'; instanceData.state.push({ type, key: 'locale', editable: false, value: composer.locale.value }); instanceData.state.push({ type, key: 'availableLocales', editable: false, value: composer.availableLocales }); instanceData.state.push({ type, key: 'fallbackLocale', editable: false, value: composer.fallbackLocale.value }); instanceData.state.push({ type, key: 'inheritLocale', editable: false, value: composer.inheritLocale }); instanceData.state.push({ type, key: 'messages', editable: false, value: getLocaleMessageValue(composer.messages.value) }); instanceData.state.push({ type, key: 'datetimeFormats', editable: false, value: composer.datetimeFormats.value }); instanceData.state.push({ type, key: 'numberFormats', editable: false, value: composer.numberFormats.value }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any function getLocaleMessageValue(messages) { const value = {}; Object.keys(messages).forEach((key) => { const v = messages[key]; if (isFunction(v) && 'source' in v) { value[key] = getMessageFunctionDetails(v); } else if (isObject(v)) { value[key] = getLocaleMessageValue(v); } else { value[key] = v; } }); return value; } const ESC = { '<': '&lt;', '>': '&gt;', '"': '&quot;', '&': '&amp;' }; function escape(s) { return s.replace(/[<>"&]/g, escapeChar); } function escapeChar(a) { return ESC[a] || a; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function getMessageFunctionDetails(func) { const argString = func.source ? `("${escape(func.source)}")` : `(?)`; return { _custom: { type: 'function', display: `<span>ƒ</span> ${argString}` } }; } function registerScope(payload, i18n) { payload.rootNodes.push({ id: 'global', label: 'Global Scope' }); // prettier-ignore const global = i18n.mode === 'composition' ? i18n.global : i18n.global.__composer; for (const [keyInstance, instance] of i18n.__instances) { // prettier-ignore const composer = i18n.mode === 'composition' ? instance : instance.__composer; if (global === composer) { continue; } const label = keyInstance.type.name || keyInstance.type.displayName || keyInstance.type.__file; payload.rootNodes.push({ id: composer.id.toString(), label: `${label} Scope` }); } } function inspectScope(payload, i18n) { if (payload.nodeId === 'global') { payload.state = makeScopeInspectState(i18n.mode === 'composition' ? i18n.global : i18n.global.__composer); } else { const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId); if (instance) { const composer = i18n.mode === 'composition' ? instance : instance.__composer; payload.state = makeScopeInspectState(composer); } } } function makeScopeInspectState(composer) { const state = {}; const localeType = 'Locale related info'; const localeStates = [ { type: localeType, key: 'locale', editable: false, value: composer.locale.value }, { type: localeType, key: 'fallbackLocale', editable: false, value: composer.fallbackLocale.value }, { type: localeType, key: 'availableLocales', editable: false, value: composer.availableLocales }, { type: localeType, key: 'inheritLocale', editable: false, value: composer.inheritLocale } ]; state[localeType] = localeStates; const localeMessagesType = 'Locale messages info'; const localeMessagesStates = [ { type: localeMessagesType, key: 'messages', editable: false, value: getLocaleMessageValue(composer.messages.value) } ]; state[localeMessagesType] = localeMessagesStates; const datetimeFormatsType = 'Datetime formats info'; const datetimeFormatsStates = [ { type: datetimeFormatsType, key: 'datetimeFormats', editable: false, value: composer.datetimeFormats.value } ]; state[datetimeFormatsType] = datetimeFormatsStates; const numberFormatsType = 'Datetime formats info'; const numberFormatsStates = [ { type: numberFormatsType, key: 'numberFormats', editable: false, value: composer.numberFormats.value } ]; state[numberFormatsType] = numberFormatsStates; return state; } function addTimelineEvent(event, payload) { if (devtoolsApi) { let groupId; if (payload && 'groupId' in payload) { groupId = payload.groupId; delete payload.groupId; } devtoolsApi.addTimelineEvent({ layerId: "vue-i18n-timeline" /* TIMELINE */, event: { title: event, groupId, time: Date.now(), meta: {}, data: payload || {}, logType: event === "compile-error" /* COMPILE_ERROR */ ? 'error' : event === "fallback" /* FALBACK */ || event === "missing" /* MISSING */ ? 'warning' : 'default' } }); } } // supports compatibility for legacy vue-i18n APIs function defineMixin(vuei18n, composer, i18n) { return { beforeCreate() { const instance = vue.getCurrentInstance(); /* istanbul ignore if */ if (!instance) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } const options = this.$options; if (options.i18n) { const optionsI18n = options.i18n; if (options.__i18n) { optionsI18n.__i18n = options.__i18n; } optionsI18n.__root = composer; if (this === this.$root) { this.$i18n = mergeToRoot(vuei18n, optionsI18n); } else { this.$i18n = createVueI18n(optionsI18n); } } else if (options.__i18n) { if (this === this.$root) { this.$i18n = mergeToRoot(vuei18n, options); } else { this.$i18n = createVueI18n({ __i18n: options.__i18n, __root: composer }); } } else { // set global this.$i18n = vuei18n; } vuei18n.__onComponentInstanceCreated(this.$i18n); i18n.__setInstance(instance, this.$i18n); // defines vue-i18n legacy APIs this.$t = (...args) => this.$i18n.t(...args); this.$tc = (...args) => this.$i18n.tc(...args); this.$te = (key, locale) => this.$i18n.te(key, locale); this.$d = (...args) => this.$i18n.d(...args); this.$n = (...args) => this.$i18n.n(...args); this.$tm = (key) => this.$i18n.tm(key); }, mounted() { /* istanbul ignore if */ { this.$el.__INTLIFY__ = this.$i18n.__composer; const emitter = (this.__emitter = createEmitter()); const _vueI18n = this.$i18n; _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); emitter.on('*', addTimelineEvent); } }, beforeUnmount() { const instance = vue.getCurrentInstance(); /* istanbul ignore if */ if (!instance) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } /* istanbul ignore if */ { if (this.__emitter) { this.__emitter.off('*', addTimelineEvent); delete this.__emitter; } const _vueI18n = this.$i18n; _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); delete this.$el.__INTLIFY__; } delete this.$t; delete this.$tc; delete this.$te; delete this.$d; delete this.$n; delete this.$tm; i18n.__deleteInstance(instance); delete this.$i18n; } }; } function mergeToRoot(root, options) { root.locale = options.locale || root.locale; root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; root.missing = options.missing || root.missing; root.silentTranslationWarn = options.silentTranslationWarn || root.silentFallbackWarn; root.silentFallbackWarn = options.silentFallbackWarn || root.silentFallbackWarn; root.formatFallbackMessages = options.formatFallbackMessages || root.formatFallbackMessages; root.postTranslation = options.postTranslation || root.postTranslation; root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; root.escapeParameterHtml = options.escapeParameterHtml || root.escapeParameterHtml; root.sync = options.sync || root.sync; const messages = getLocaleMessages(root.locale, { messages: options.messages, __i18n: options.__i18n }); Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); if (options.datetimeFormats) { Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); } if (options.numberFormats) { Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); } return root; } /** * Vue I18n factory * * @param options - An options, see the {@link I18nOptions} * * @returns {@link I18n} instance * * @remarks * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. * * If you use composition API mode, you need to specify {@link ComposerOptions}. * * @VueI18nSee [Getting Started](../../guide/) * @VueI18nSee [Composition API](../../guide/advanced/composition) * * @example * case: for Legacy API * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * // ... * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @example * case: for composition API * ```js * import { createApp } from 'vue' * import { createI18n, useI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * legacy: false, // you must specify 'legacy: false' option * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * setup() { * // ... * const { t } = useI18n({ ... }) * return { ... , t } * } * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @VueI18nGeneral */ function createI18n(options = {}) { // prettier-ignore const __legacyMode = isBoolean(options.legacy) ? options.legacy : true; const __globalInjection = !!options.globalInjection; const __instances = new Map(); // prettier-ignore const __global = __legacyMode ? createVueI18n(options) : createComposer(options); const symbol = makeSymbol( 'vue-i18n' ); const i18n = { // mode get mode() { // prettier-ignore return __legacyMode ? 'legacy' : 'composition' ; }, // install plugin async install(app, ...options) { { app.__VUE_I18N__ = i18n; } // setup global provider app.__VUE_I18N_SYMBOL__ = symbol; app.provide(app.__VUE_I18N_SYMBOL__, i18n); // global method and properties injection for Composition API if (!__legacyMode && __globalInjection) { injectGlobalFields(app, i18n.global); } // install built-in components and directive { apply(app, i18n, ...options); } // setup mixin for Legacy API if ( __legacyMode) { app.mixin(defineMixin(__global, __global.__composer, i18n)); } // setup vue-devtools plugin { const ret = await enableDevTools(app, i18n); if (!ret) { throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); } const emitter = createEmitter(); if (__legacyMode) { const _vueI18n = __global; _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = __global; _composer[EnableEmitter] && _composer[EnableEmitter](emitter); } emitter.on('*', addTimelineEvent); } }, // global accessor get global() { return __global; }, // @internal __instances, // @internal __getInstance(component) { return __instances.get(component) || null; }, // @internal __setInstance(component, instance) { __instances.set(component, instance); }, // @internal __deleteInstance(component) { __instances.delete(component); } }; return i18n; } /** * Use Composition API for Vue I18n * * @param options - An options, see {@link UseI18nOptions} * * @returns {@link Composer} instance * * @remarks * This function is mainly used by `setup`. * * If options are specified, Composer instance is created for each component and you can be localized on the component. * * If options are not specified, you can be localized using the global Composer. * * @example * case: Component resource base localization * ```html * <template> * <form> * <label>{{ t('language') }}</label> * <select v-model="locale"> * <option value="en">en</option> * <option value="ja">ja</option> * </select> * </form> * <p>message: {{ t('hello') }}</p> * </template> * * <script> * import { useI18n } from 'vue-i18n' * * export default { * setup() { * const { t, locale } = useI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * // Something to do ... * * return { ..., t, locale } * } * } * </script> * ``` * * @VueI18nComposition */ function useI18n(options = {}) { const instance = vue.getCurrentInstance(); if (instance == null) { throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); } if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { throw createI18nError(17 /* NOT_INSLALLED */); } const i18n = vue.inject(instance.appContext.app.__VUE_I18N_SYMBOL__); /* istanbul ignore if */ if (!i18n) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } // prettier-ignore const global = i18n.mode === 'composition' ? i18n.global : i18n.global.__composer; // prettier-ignore const scope = isEmptyObject(options) ? ('__i18n' in instance.type) ? 'local' : 'global' : !options.useScope ? 'local' : options.useScope; if (scope === 'global') { let messages = isObject(options.messages) ? options.messages : {}; if ('__i18nGlobal' in instance.type) { messages = getLocaleMessages(global.locale.value, { messages, __i18n: instance.type.__i18nGlobal }); } // merge locale messages const locales = Object.keys(messages); if (locales.length) { locales.forEach(locale => { global.mergeLocaleMessage(locale, messages[locale]); }); } // merge datetime formats if (isObject(options.datetimeFormats)) { const locales = Object.keys(options.datetimeFormats); if (locales.length) { locales.forEach(locale => { global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); }); } } // merge number formats if (isObject(options.numberFormats)) { const locales = Object.keys(options.numberFormats); if (locales.length) { locales.forEach(locale => { global.mergeNumberFormat(locale, options.numberFormats[locale]); }); } } return global; } if (scope === 'parent') { let composer = getComposer$1(i18n, instance); if (composer == null) { { warn(getWarnMessage$1(12 /* NOT_FOUND_PARENT_SCOPE */)); } composer = global; } return composer; } // scope 'local' case if (i18n.mode === 'legacy') { throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); } const i18nInternal = i18n; let composer = i18nInternal.__getInstance(instance); if (composer == null) { const type = instance.type; const composerOptions = { ...options }; if (type.__i18n) { composerOptions.__i18n = type.__i18n; } if (global) { composerOptions.__root = global; } composer = createComposer(composerOptions); setupLifeCycle(i18nInternal, instance, composer); i18nInternal.__setInstance(instance, composer); } return composer; } function getComposer$1(i18n, target) { let composer = null; const root = target.root; let current = target.parent; while (current != null) { const i18nInternal = i18n; if (i18n.mode === 'composition') { composer = i18nInternal.__getInstance(current); } else { const vueI18n = i18nInternal.__getInstance(current); if (vueI18n != null) { composer = vueI18n .__composer; } } if (composer != null) { break; } if (root === current) { break; } current = current.parent; } return composer; } function setupLifeCycle(i18n, target, composer) { let emitter = null; vue.onMounted(() => { // inject composer instance to DOM for intlify-devtools if ( target.vnode.el) { target.vnode.el.__INTLIFY__ = composer; emitter = createEmitter(); // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = composer; _composer[EnableEmitter] && _composer[EnableEmitter](emitter); emitter.on('*', addTimelineEvent); } }, target); vue.onUnmounted(() => { // remove composer instance from DOM for intlify-devtools if ( target.vnode.el && target.vnode.el.__INTLIFY__) { emitter && emitter.off('*', addTimelineEvent); // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = composer; _composer[DisableEmitter] && _composer[DisableEmitter](); delete target.vnode.el.__INTLIFY__; } i18n.__deleteInstance(target); }, target); } const globalExportProps = [ 'locale', 'fallbackLocale', 'availableLocales' ]; const globalExportMethods = ['t', 'd', 'n', 'tm']; function injectGlobalFields(app, composer) { const i18n = Object.create(null); globalExportProps.forEach(prop => { const desc = Object.getOwnPropertyDescriptor(composer, prop); if (!desc) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } const wrap = vue.isRef(desc.value) // check computed props ? { get() { return desc.value.value; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any set(val) { desc.value.value = val; } } : { get() { return desc.get && desc.get(); } }; Object.defineProperty(i18n, prop, wrap); }); app.config.globalProperties.$i18n = i18n; globalExportMethods.forEach(method => { const desc = Object.getOwnPropertyDescriptor(composer, method); if (!desc) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } Object.defineProperty(app.config.globalProperties, `$${method}`, desc); }); } initDev(); exports.DatetimeFormat = DatetimeFormat; exports.NumberFormat = NumberFormat; exports.Translation = Translation; exports.VERSION = VERSION; exports.createI18n = createI18n; exports.useI18n = useI18n; exports.vTDirective = vTDirective; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}, Vue));
/*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function( window, undefined ) { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute on DOM ready readyList = [], // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, indexOf = Array.prototype.indexOf; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); if ( elem ) { // 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: $("TAG") } else if ( !context && /^\w+$/.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // 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 jQuery( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.4.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // 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 this.toArray() : // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // 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 ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( fn ); } return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || jQuery(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // 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 ( length === i ) { 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 object literal values or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src : jQuery.isArray(copy) ? [] : {}; // 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({ noConflict: function( deep ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 13 ); } // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( readyList ) { // Execute all of them var fn, i = 0; while ( (fn = readyList[ i++ ]) ) { fn.call( document, jQuery ); } // Reset the list of functions readyList = null; } // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { return jQuery.ready(); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // 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 toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { return toString.call(obj) === "[object Array]"; }, isPlainObject: function( obj ) { // 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 || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwnProperty.call(obj, "constructor") && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwnProperty.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, trim: function( text ) { return (text || "").replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { if ( !inv !== !callback( elems[ i ], i ) ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, browser: {} }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch( error ) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function function access( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; } function now() { return (new Date).getTime(); } (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: div.getElementsByTagName("input")[0].value === "on", // 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) optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected, parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null, // Will be defined later deleteExpando: true, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null }; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; document.body.removeChild( div ).style.display = 'none'; div = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; var expando = "jQuery" + now(), uuid = 0, windowData = {}; jQuery.extend({ cache: {}, expando:expando, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, "object": true, "applet": true }, data: function( elem, name, data ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache; if ( !id && typeof name === "string" && data === undefined ) { return null; } // Compute a unique ID for the element if ( !id ) { id = ++uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { elem[ expando ] = id; thisCache = cache[ id ] = jQuery.extend(true, {}, name); } else if ( !cache[ id ] ) { elem[ expando ] = id; cache[ id ] = {}; } thisCache = cache[ id ]; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } // Completely remove the data cache delete cache[ id ]; } } }); jQuery.fn.extend({ data: function( key, value ) { if ( typeof key === "undefined" && this.length ) { return jQuery.data( this[0] ); } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { jQuery.data( this, key, value ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i, elem ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t]/g, rspace = /\s+/, rreturn = /\r/g, rspecialurl = /href|src|style/, rtype = /(button|input)/i, rfocusable = /(button|input|object|select|textarea)/i, rclickable = /^(a|area)$/i, rradiocheck = /radio|checkbox/; jQuery.fn.extend({ attr: function( name, value ) { return access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split(rspace); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery(this), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery.data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( value === undefined ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { return (elem.attributes.value || {}).specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; if ( option.selected ) { // Get the specifc 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; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Typecast each time if the value is a Function and the appended // value is therefore different each time. if ( typeof val === "number" ) { val += ""; } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // 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/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // Using attr for specific style information is now deprecated. Use style instead. return jQuery.style( elem, name, value ); } }); var rnamespaces = /\.(.*)$/, fcleanup = function( nm ) { return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { return "\\" + ch; }); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { elem = window; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery.data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events = elemData.events || {}, eventHandle = elemData.handle, eventHandle; if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; handleObj.guid = handler.guid; // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // 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 the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)") } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( var j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( var j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var target = event.target, old, isClick = jQuery.nodeName(target, "a") && type === "click", special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ type ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + type ]; if ( old ) { target[ "on" + type ] = null; } jQuery.event.triggered = true; target[ type ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( old ) { target[ "on" + type ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace, events; event = arguments[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); } var events = jQuery.data(this, "events"), handlers = events[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, arguments ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { event.which = event.charCode || event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) ); }, remove: function( handleObj ) { var remove = true, type = handleObj.origType.replace(rnamespaces, ""); jQuery.each( jQuery.data(this, "events").live || [], function() { if ( type === this.origType.replace(rnamespaces, "") ) { remove = false; return false; } }); if ( remove ) { jQuery.event.remove( this, handleObj.origType, liveHandler ); } } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( this.setInterval ) { this.onbeforeunload = eventHandle; } return false; }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; var removeEvent = document.removeEventListener ? function( elem, type, handle ) { elem.removeEventListener( type, handle, false ); } : function( elem, type, handle ) { elem.detachEvent( "on" + type, handle ); }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = now(); // Mark it as fixed this[ expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return 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 = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); } // otherwise set the returnValue property of the original event to false (IE) e.returnValue = false; }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { return trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var formElems = /textarea|input|select/i, changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery.data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery.data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information/focus[in] is not needed anymore beforeactivate: function( e ) { var elem = e.target; jQuery.data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return formElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return formElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { this.addEventListener( orig, handler, true ); }, teardown: function() { this.removeEventListener( orig, handler, true ); } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.handle.call( this, e ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler context.each(function(){ jQuery.event.add( this, liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); }); } else { // unbind live handler context.unbind( liveConvert( type, selector ), fn ); } } return this; } }); function liveHandler( event ) { var stop, elems = [], selectors = [], args = arguments, related, match, handleObj, elem, j, i, l, data, events = jQuery.data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { return; } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( match[i].selector === handleObj.selector ) { elem = match[i].elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) { stop = false; break; } } return stop; } function liveConvert( type, selector ) { return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); } 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").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { window.attachEvent("onunload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.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|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } else { Sizzle.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ return "\\" + (num - 0 + 1); })); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return a.compareDocumentPosition ? -1 : 1; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return a.ownerDocument ? -1 : 1; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // Utility function for retreiving the text value of an array of DOM nodes function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date).getTime(); form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); root = form = null; // release memory in IE })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function(elem){ return elem.getAttribute("href", 2); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function(query, context, extra, seed){ context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); } (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context, isXML) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var 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 : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = getText; jQuery.isXMLDoc = isXML; jQuery.contains = contains; return; window.Sizzle = Sizzle; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, slice = Array.prototype.slice; // Implement the identical functionality for filter and not var winnow = function( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); }; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { if ( jQuery.isArray( selectors ) ) { var ret = [], cur = this[0], match, matches = {}, selector; if ( cur && selectors.length ) { for ( var i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur }); delete matches[selector]; } } cur = cur.parentNode; } } return ret; } var pos = jQuery.expr.match.POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; return this.map(function( i, cur ) { while ( cur && cur.ownerDocument && cur !== context ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { return cur; } cur = cur.parentNode; } return null; }); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // 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 || this.context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } 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 jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "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.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return jQuery.find.matches(expr, elems); }, 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; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<script|<object|<embed|<option|<style/i, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) fcloseTag = function( all, front, tag ) { return rselfClosing.test( tag ) ? all : front + "></" + tag + ">"; }, wrapMap = { 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, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery(this); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, 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 ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(/=([^="'>\s]+\/)>/g, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, fcloseTag); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery(this), old = self.html(); self.empty().append(function(){ return value.call( this, i, old ); }); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery(value).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery(this).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, value = args[0], scripts = [], fragment, parent; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(true) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } } }); function cloneCopyEvent(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } function buildFragment( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; } jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, fcloseTag); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( var i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); } else { removeEvent( elem, type, data.handle ); } } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); // exclude the following css properties to add px var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, ralpha = /alpha\([^)]*\)/, ropacity = /opacity=([^)]*)/, rfloat = /float/i, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display:"block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], // cache check for defaultView.getComputedStyle getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, // normalize float css property styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { return access( this, name, value, true, function( elem, name, value ) { if ( value === undefined ) { return jQuery.curCSS( elem, name ); } if ( typeof value === "number" && !rexclude.test(name) ) { value += "px"; } jQuery.style( elem, name, value ); }); }; jQuery.extend({ style: function( elem, name, value ) { // don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // ignore negative width and height values #1599 if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { value = undefined; } var style = elem.style || elem, set = value !== undefined; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; } return style.filter && style.filter.indexOf("opacity=") >= 0 ? (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": ""; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } name = name.replace(rdashAlpha, fcamelCase); if ( set ) { style[ name ] = value; } return style[ name ]; }, css: function( elem, name, force, extra ) { if ( name === "width" || name === "height" ) { var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; function getWH() { val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; } else { val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; } }); } if ( elem.offsetWidth !== 0 ) { getWH(); } else { jQuery.swap( elem, props, getWH ); } return Math.max(0, Math.round(val)); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { var ret, style = elem.style, filter; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { ret = ropacity.test(elem.currentStyle.filter || "") ? (parseFloat(RegExp.$1) / 100) + "" : ""; return ret === "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } if ( !force && style && style[ name ] ) { ret = style[ name ]; } else if ( getComputedStyle ) { // Only "float" is needed here if ( rfloat.test( name ) ) { name = "float"; } name = name.replace( rupper, "-$1" ).toLowerCase(); var defaultView = elem.ownerDocument.defaultView; if ( !defaultView ) { return null; } var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) { ret = computedStyle.getPropertyValue( name ); } // We should always get a number back from opacity if ( name === "opacity" && ret === "" ) { ret = "1"; } } else if ( elem.currentStyle ) { var camelCase = name.replace(rdashAlpha, fcamelCase); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // 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 if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = camelCase === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) { elem.style[ name ] = old[ name ]; } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; return width === 0 && height === 0 && !skip ? true : width > 0 && height > 0 && !skip ? false : jQuery.curCSS(elem, "display") === "none"; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = now(), rscript = /<script(.|\s)*?\/script>/gi, rselectTextarea = /select|textarea/i, rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, jsre = /=\?(&|$)/, rquery = /\?/, rts = /(\?|&)_=.*?(&|$)/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, // Keep a copy of the old load method _load = jQuery.fn.load; jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" ) { return _load.call( this, url ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div />") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); return this; }, serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function() { return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function() { return this.name && !this.disabled && (this.checked || rselectTextarea.test(this.nodeName) || rinput.test(this.type)); }) .map(function( i, elem ) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map( val, function( val, i ) { return { name: elem.name, value: val }; }) : { name: elem.name, value: val }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { jQuery.fn[o] = function( f ) { return this.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7 (can't request local files), // so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function() { return new window.XMLHttpRequest(); } : function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); var jsonp, status, data, callbackContext = origSettings && origSettings.context || s, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && type === "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type === "GET" ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data || origSettings && origSettings.contentType ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { trigger("ajaxSend", [xhr, s]); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { complete(); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(err) { status = "parsererror"; errMsg = err; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { success(); } } else { jQuery.handleError(s, xhr, status, errMsg); } // Fire the complete handlers complete(); if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { oldAbort.call( xhr ); } onreadystatechange( "abort" ); }; } catch(e) { } // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); } catch(e) { jQuery.handleError(s, xhr, null, e); // Fire the complete handlers complete(); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } function success() { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( callbackContext, data, status, xhr ); } // Fire the global callback if ( s.global ) { trigger( "ajaxSuccess", [xhr, s] ); } } function complete() { // Process result if ( s.complete ) { s.complete.call( callbackContext, xhr, status); } // The request was completed if ( s.global ) { trigger( "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } function trigger(type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || // Opera returns 0 when status is 304 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } // Opera returns 0 when status is 304 return xhr.status === 304 || xhr.status === 0; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = []; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray(a) || a.jquery ) { // 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 ( var prefix in a ) { buildParams( prefix, a[prefix] ); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); function buildParams( prefix, obj ) { if ( jQuery.isArray(obj) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || /\[\]$/.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v ); }); } else { // Serialize scalar item. add( prefix, obj ); } } function add( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : value; s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); } } }); var elemdisplay = {}, rfxtypes = /toggle|show|hide/, rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, callback ) { if ( speed || speed === 0) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var nodeName = this[i].nodeName, display; if ( elemdisplay[ nodeName ] ) { display = elemdisplay[ nodeName ]; } else { var elem = jQuery("<" + nodeName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) { display = "block"; } elem.remove(); elemdisplay[ nodeName ] = display; } jQuery.data(this[i], "olddisplay", display); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; } return this; } }, hide: function( speed, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) { jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2); } return this; }, fadeTo: function( speed, to, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { var opt = jQuery.extend({}, optall), p, hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = p.replace(rdashAlpha, fcamelCase); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( ( p === "height" || p === "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = start + unit; } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, callback ) { return this.animate( props, speed, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? 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 : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); // Set display property to block for height/width animations if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { this.elem.style.display = "block"; } }, // Get the current size cur: function( force ) { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(jQuery.fx.tick, 13); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display var old = jQuery.data(this.elem, "olddisplay"); this.elem.style.display = old ? old : this.options.display; if ( jQuery.css(this.elem, "display") === "none" ) { this.elem.style.display = "block"; } } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style(this.elem, p, this.options.orig[p]); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style(fx.elem, "opacity", fx.now); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed", checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0; left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { // set position first, in-case top/left are set even on static elem if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } var props = { top: (options.top - curOffset.top) + curTop, left: (options.left - curOffset.left) + curLeft }; if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract 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 offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0; offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return ("scrollTo" in elem && elem.document) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? jQuery.css( this[0], type, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ] : // Get document width or height (elem.nodeType === 9) ? // is it a document // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element jQuery.css( elem, type ) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window); /** * @license AngularJS v0.9.19 * (c) 2010-2011 AngularJS http://angularjs.org * License: MIT */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); 'use strict'; //////////////////////////////////// if (typeof document.getAttribute == $undefined) document.getAttribute = function() {}; /** * @workInProgress * @ngdoc function * @name angular.lowercase * @function * * @description Converts string to lowercase * @param {string} string String to be lowercased. * @returns {string} Lowercased string. */ var lowercase = function (string){ return isString(string) ? string.toLowerCase() : string; }; /** * @workInProgress * @ngdoc function * @name angular.uppercase * @function * * @description Converts string to uppercase. * @param {string} string String to be uppercased. * @returns {string} Uppercased string. */ var uppercase = function (string){ return isString(string) ? string.toUpperCase() : string; }; var manualLowercase = function (s) { return isString(s) ? s.replace(/[A-Z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) | 32); }) : s; }; var manualUppercase = function (s) { return isString(s) ? s.replace(/[a-z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) & ~32); }) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods with // correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) { return String.fromCharCode(code); } var _undefined = undefined, _null = null, $$element = '$element', $$scope = '$scope', $$validate = '$validate', $angular = 'angular', $array = 'array', $boolean = 'boolean', $console = 'console', $date = 'date', $element = 'element', $function = 'function', $length = 'length', $name = 'name', $noop = 'noop', $null = 'null', $number = 'number', $object = 'object', $string = 'string', $value = 'value', $selected = 'selected', $undefined = 'undefined', NG_EXCEPTION = 'ng-exception', NG_VALIDATION_ERROR = 'ng-validation-error', NOOP = 'noop', PRIORITY_FIRST = -99999, PRIORITY_WATCH = -1000, PRIORITY_LAST = 99999, PRIORITY = {'FIRST': PRIORITY_FIRST, 'LAST': PRIORITY_LAST, 'WATCH':PRIORITY_WATCH}, Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, error = window[$console] ? bind(window[$console], window[$console]['error'] || noop) : noop, /** @name angular */ angular = window[$angular] || (window[$angular] = {}), /** @name angular.markup */ angularTextMarkup = extensionMap(angular, 'markup'), /** @name angular.attrMarkup */ angularAttrMarkup = extensionMap(angular, 'attrMarkup'), /** @name angular.directive */ angularDirective = extensionMap(angular, 'directive'), /** @name angular.widget */ angularWidget = extensionMap(angular, 'widget', lowercase), /** @name angular.validator */ angularValidator = extensionMap(angular, 'validator'), /** @name angular.fileter */ angularFilter = extensionMap(angular, 'filter'), /** @name angular.formatter */ angularFormatter = extensionMap(angular, 'formatter'), /** @name angular.service */ angularService = extensionMap(angular, 'service'), angularCallbacks = extensionMap(angular, 'callbacks'), nodeName_, rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/, uid = ['0', '0', '0'], DATE_ISOSTRING_LN = 24; /** * @workInProgress * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection. The collection can either * be an object or an array. The `iterator` function is invoked with `iterator(value, key)`, where * `value` is the value of an object property or an array element and `key` is the object property * key or array element index. Optionally, `context` can be specified for the iterator function. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {function()} iterator Iterator function. * @param {Object} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != $length && key != $name && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) iterator.call(context, obj[key], key); } } return obj; } function forEachSorted(obj, iterator, context) { var keys = []; for (var key in obj) keys.push(key); keys.sort(); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } /** * @description * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @workInProgress * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) to * `dst`. You can specify multiple `src` objects. * * @param {Object} dst The destination object. * @param {...Object} src The source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function inherit(parent, extra) { return extend(new (extend(function(){}, {prototype:parent}))(), extra); } /** * @workInProgress * @ngdoc function * @name angular.noop * @function * * @description * Empty function that performs no operation whatsoever. This function is useful when writing code * in the functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} /** * @workInProgress * @ngdoc function * @name angular.identity * @function * * @description * A function that does nothing except for returning its first argument. This function is useful * when writing code in the functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} function valueFn(value) {return function(){ return value; };} function extensionMap(angular, name, transform) { var extPoint; return angular[name] || (extPoint = angular[name] = function (name, fn, prop){ name = (transform || identity)(name); if (isDefined(fn)) { extPoint[name] = extend(fn, prop || {}); } return extPoint[name]; }); } /** * @workInProgress * @ngdoc function * @name angular.isUndefined * @function * * @description * Checks if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){ return typeof value == $undefined; } /** * @workInProgress * @ngdoc function * @name angular.isDefined * @function * * @description * Checks if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){ return typeof value != $undefined; } /** * @workInProgress * @ngdoc function * @name angular.isObject * @function * * @description * Checks if a reference is an `Object`. Unlike in JavaScript `null`s are not considered to be * objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){ return value!=null && typeof value == $object;} /** * @workInProgress * @ngdoc function * @name angular.isString * @function * * @description * Checks if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){ return typeof value == $string;} /** * @workInProgress * @ngdoc function * @name angular.isNumber * @function * * @description * Checks if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){ return typeof value == $number;} /** * @workInProgress * @ngdoc function * @name angular.isDate * @function * * @description * Checks if value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return value instanceof Date; } /** * @workInProgress * @ngdoc function * @name angular.isArray * @function * * @description * Checks if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return value instanceof Array; } /** * @workInProgress * @ngdoc function * @name angular.isFunction * @function * * @description * Checks if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){ return typeof value == $function;} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isBoolean(value) { return typeof value == $boolean;} function isTextNode(node) { return nodeName_(node) == '#text'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } /** * HTML class which is the only class which can be used in ng:bind to inline HTML for security reasons. * @constructor * @param html raw (unsafe) html * @param {string=} option if set to 'usafe' then get method will return raw (unsafe/unsanitized) html */ function HTML(html, option) { this.html = html; this.get = lowercase(option) == 'unsafe' ? valueFn(html) : function htmlSanitize() { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML' ) ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function isVisible(element) { var rect = element[0].getBoundingClientRect(), width = (rect.width || (rect.right||0 - rect.left||0)), height = (rect.height || (rect.bottom||0 - rect.top||0)); return width>0 && height>0; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @ngdoc function * @name angular.Object.size * @function * * @description * Determines the number of elements in an array, number of properties of an object or string * length. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {Object|Array|string} obj Object, array or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object or an array. * * @example * <doc:example> * <doc:source> * Number of items in array: {{ [1,2].$size() }}<br/> * Number of items in object: {{ {a:1, b:2, c:3}.$size() }}<br/> * </doc:source> * <doc:scenario> * it('should print correct sizes for an array and an object', function() { * expect(binding('[1,2].$size()')).toBe('2'); * expect(binding('{a:1, b:2, c:3}.$size()')).toBe('3'); * }); * </doc:scenario> * </doc:example> */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return true; } return false; } function indexOf(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.Object.copy * @function * * @description * Creates a deep copy of `source`. * * If `source` is an object or an array, all of its members will be copied into the `destination` * object. * * If `destination` is not provided and `source` is an object or an array, a copy is created & * returned, otherwise the `source` is returned. * * If `destination` is provided, all of its properties will be deleted. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {*} source The source to be used to make a copy. * Can be any type including primitives, `null` and `undefined`. * @param {(Object|Array)=} destination Optional destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination` if `destination` was specified. * * @example * <doc:example> * <doc:source> Salutation: <input type="text" name="master.salutation" value="Hello" /><br/> Name: <input type="text" name="master.name" value="world"/><br/> <button ng:click="form = master.$copy()">copy</button> <hr/> The master object is <span ng:hide="master.$equals(form)">NOT</span> equal to the form object. <pre>master={{master}}</pre> <pre>form={{form}}</pre> * </doc:source> * <doc:scenario> it('should print that initialy the form object is NOT equal to master', function() { expect(element('.doc-example-live input[name=master.salutation]').val()).toBe('Hello'); expect(element('.doc-example-live input[name=master.name]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); it('should make form and master equal when the copy button is clicked', function() { element('.doc-example-live button').click(); expect(element('.doc-example-live span').css('display')).toBe('none'); }); * </doc:scenario> * </doc:example> */ function copy(source, destination){ if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * @ngdoc function * @name angular.Object.equals * @function * * @description * Determines if two objects or value are equivalent. * * To be equivalent, they must pass `==` comparison or be of the same type and have all their * properties pass `==` comparison. During property comparision properties of `function` type and * properties with name starting with `$` are ignored. * * Supports values types, arrays and objects. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. * * @example * <doc:example> * <doc:source> Salutation: <input type="text" name="greeting.salutation" value="Hello" /><br/> Name: <input type="text" name="greeting.name" value="world"/><br/> <hr/> The <code>greeting</code> object is <span ng:hide="greeting.$equals({salutation:'Hello', name:'world'})">NOT</span> equal to <code>{salutation:'Hello', name:'world'}</code>. <pre>greeting={{greeting}}</pre> * </doc:source> * <doc:scenario> it('should print that initialy greeting is equal to the hardcoded value object', function() { expect(element('.doc-example-live input[name=greeting.salutation]').val()).toBe('Hello'); expect(element('.doc-example-live input[name=greeting.name]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('none'); }); it('should say that the objects are not equal when the form is modified', function() { input('greeting.name').enter('kitty'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); * </doc:scenario> * </doc:example> */ function equals(o1, o2) { if (o1 == o2) return true; if (o1 === null || o2 === null) return false; var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2 && t1 == 'object') { if (o1 instanceof Array) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else { keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) return false; keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } return false; } function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { node.innerText = html; } else { node.textContent = html; } } else { node.innerHTML = html; } } function isRenderableElement(element) { var name = element && element[0] && element[0].nodeName; return name && name.charAt(0) != '#' && !includes(['TR', 'COL', 'COLGROUP', 'TBODY', 'THEAD', 'TFOOT'], name); } function elementError(element, type, error) { var parent; while (!isRenderableElement(element)) { parent = element.parent(); if (parent.length) { element = element.parent(); } else { return; } } if (element[0]['$NG_ERROR'] !== error) { element[0]['$NG_ERROR'] = error; if (error) { element.addClass(type); element.attr(type, error.message || error); } else { element.removeClass(type); element.removeAttr(type); } } } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index, array2.length)); } /** * @workInProgress * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for `fn`). * Optional `args` can be supplied which are prebound to the function, also known as * [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? slice.call(arguments, 2, arguments.length) : []; if (typeof fn == $function && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0, arguments.length))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions and so they can not be bound (but they don't need to be) return fn; } } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } function merge(src, dst) { for ( var key in src) { var value = dst[key]; var type = typeof value; if (type == $undefined) { dst[key] = fromJson(toJson(src[key])); } else if (type == 'object' && value.constructor != array && key.substring(0, 1) != "$") { merge(src[key], value); } } } /** @name angular.compile */ function compile(element) { return new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget) .compile(element); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = unescape(key_value[0]); obj[key] = isDefined(key_value[1]) ? unescape(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(escape(key) + (value === true ? '' : '=' + escape(value))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:autobind * @element script * * @TODO ng:autobind is not a directive!! it should be documented as bootstrap parameter in a * separate bootstrap section. * @TODO rename to ng:autobind to ng:autoboot * * @description * * `ng:autobind` with no parameters tells angular to compile and manage the whole page. * * `ng:autobind="[root element ID]"` tells angular to compile and manage part of the docucment, * starting at "root element ID". * * For details on bootstrapping angular, see {@link guide/dev_guide.bootstrap Initializing Angular} * in the Angular Developer Guide. */ function angularInit(config, document){ var autobind = config.autobind; if (autobind) { var element = isString(autobind) ? document.getElementById(autobind) : document, scope = compile(element)(createScope({'$config':config})), $browser = scope.$service('$browser'); if (config.css) $browser.addCss(config.base_url + config.css); else if(msie<8) $browser.addJs(config.ie_compat, config.ie_compat_id); } } function angularJsConfig(document, config) { bindJQuery(); var scripts = document.getElementsByTagName("script"), match; config = extend({ ie_compat_id: 'ng-ie-compat' }, config); for(var j = 0; j < scripts.length; j++) { match = (scripts[j].src || "").match(rngScript); if (match) { config.base_url = match[1]; config.ie_compat = match[1] + 'angular-ie-compat' + (match[2] || '') + '.js'; extend(config, parseKeyValue(match[6])); eachAttribute(jqLite(scripts[j]), function(value, name){ if (/^ng:/.exec(name)) { name = name.substring(3).replace(/-/g, '_'); value = value || true; config[name] = value; } }); } } return config; } function bindJQuery(){ // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope }); } else { jqLite = jqLiteWrap; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { var error = new Error("Argument '" + (name||'?') + "' is " + (reason || "required")); throw error; } } function assertArgFn(arg, name) { assertArg(isFunction(arg, name, 'not a function')); } /** * @ngdoc property * @name angular.version * @description * Object which contains information about the current AngularJS version. The object has following * properties: * * - `full` – `{string}` – full version string, e.g. "0.9.18" * - `major` – `{number}` – major version number, e.g. 0 * - `minor` – `{number}` – minor version number, e.g. 9 * - `dot` – `{number}` – dot version number, e.g. 18 * - `codeName` – `{string}` – code name of the release, e.g. "jiggling-armfat" */ var version = { full: '0.9.19', // all of these placeholder strings will be replaced by rake's major: "NG_VERSION_MAJOR", // compile task minor: "NG_VERSION_MINOR", dot: "NG_VERSION_DOT", codeName: '"NG_VERSION_CODENAME"' }; 'use strict'; var array = [].constructor; /** * @workInProgress * @ngdoc function * @name angular.toJson * @function * * @description * Serializes the input into a JSON formated string. * * @param {Object|Array|Date|string|number} obj Input to jsonify. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { var buf = []; toJsonArray(buf, obj, pretty ? "\n " : null, []); return buf.join(''); } /** * @workInProgress * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a string in the JSON format. * * @param {string} json JSON string to deserialize. * @param {boolean} [useNative=false] Use native JSON parser if available * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json, useNative) { if (!isString(json)) return json; var obj; try { if (useNative && window.JSON && window.JSON.parse) { obj = JSON.parse(json); return transformDates(obj); } return parser(json, true).primary()(); } catch (e) { error("fromJson error: ", json, e); throw e; } // TODO make forEach optionally recursive and remove this function function transformDates(obj) { if (isString(obj) && obj.length === DATE_ISOSTRING_LN) { return angularString.toDate(obj); } else if (isArray(obj) || isObject(obj)) { forEach(obj, function(val, name) { obj[name] = transformDates(val); }); } return obj; } } angular.toJson = toJson; angular.fromJson = fromJson; function toJsonArray(buf, obj, pretty, stack) { if (isObject(obj)) { if (obj === window) { buf.push('WINDOW'); return; } if (obj === document) { buf.push('DOCUMENT'); return; } if (includes(stack, obj)) { buf.push('RECURSION'); return; } stack.push(obj); } if (obj === null) { buf.push($null); } else if (obj instanceof RegExp) { buf.push(angular.String.quoteUnicode(obj.toString())); } else if (isFunction(obj)) { return; } else if (isBoolean(obj)) { buf.push('' + obj); } else if (isNumber(obj)) { if (isNaN(obj)) { buf.push($null); } else { buf.push('' + obj); } } else if (isString(obj)) { return buf.push(angular.String.quoteUnicode(obj)); } else if (isObject(obj)) { if (isArray(obj)) { buf.push("["); var len = obj.length; var sep = false; for(var i=0; i<len; i++) { var item = obj[i]; if (sep) buf.push(","); if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) { buf.push($null); } else { toJsonArray(buf, item, pretty, stack); } sep = true; } buf.push("]"); } else if (isDate(obj)) { buf.push(angular.String.quoteUnicode(angular.Date.toString(obj))); } else { buf.push("{"); if (pretty) buf.push(pretty); var comma = false; var childPretty = pretty ? pretty + " " : false; var keys = []; for(var k in obj) { if (obj.hasOwnProperty(k) && obj[k] !== undefined) { keys.push(k); } } keys.sort(); for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) { var key = keys[keyIndex]; var value = obj[key]; if (typeof value != $function) { if (comma) { buf.push(","); if (pretty) buf.push(pretty); } buf.push(angular.String.quote(key)); buf.push(":"); toJsonArray(buf, value, childPretty, stack); comma = true; } } buf.push("}"); } } if (isObject(obj)) { stack.pop(); } } 'use strict'; /** * Template provides directions an how to bind to a given element. * It contains a list of init functions which need to be called to * bind to a new instance of elements. It also provides a list * of child paths which contain child templates */ function Template(priority) { this.paths = []; this.children = []; this.inits = []; this.priority = priority; this.newScope = false; } Template.prototype = { attach: function(element, scope) { var inits = {}; this.collectInits(element, inits, scope); forEachSorted(inits, function(queue){ forEach(queue, function(fn) {fn();}); }); }, collectInits: function(element, inits, scope) { var queue = inits[this.priority], childScope = scope; if (!queue) { inits[this.priority] = queue = []; } if (this.newScope) { childScope = createScope(scope); scope.$onEval(childScope.$eval); element.data($$scope, childScope); } forEach(this.inits, function(fn) { queue.push(function() { childScope.$tryEval(function(){ return childScope.$service.invoke(childScope, fn, [element]); }, element); }); }); var i, childNodes = element[0].childNodes, children = this.children, paths = this.paths, length = paths.length; for (i = 0; i < length; i++) { children[i].collectInits(jqLite(childNodes[paths[i]]), inits, childScope); } }, addInit:function(linkingFn) { if (linkingFn) { if (!linkingFn.$inject) linkingFn.$inject = []; this.inits.push(linkingFn); } }, addChild: function(index, template) { if (template) { this.paths.push(index); this.children.push(template); } }, empty: function() { return this.inits.length === 0 && this.paths.length === 0; } }; /////////////////////////////////// //Compiler ////////////////////////////////// /** * @workInProgress * @ngdoc function * @name angular.compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link angular.scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link angular.markup markup}, {@link angular.attrMarkup attrMarkup}, * {@link angular.widget widgets}, and {@link angular.directive directives}. For each match it * executes corresponding markup, attrMarkup, widget or directive template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link angular.widget.@ng:repeat repeater} many-times, in which case each call results in a view * that is a DOM clone of the original template. * <pre> // compile the entire window.document and give me the scope bound to this template. var rootScope = angular.compile(window.document)(); // compile a piece of html var rootScope2 = angular.compile('<div ng:click="clicked = true">click me</div>')(); // compile a piece of html and retain reference to both the dom and scope var template = angular.element('<div ng:click="clicked = true">click me</div>'), scope = angular.compile(template)(); // at this point template was transformed into a view </pre> * * * @param {string|DOMElement} element Element or HTML to compile into a template function. * @returns {function([scope][, cloneAttachFn])} a template function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link angular.scope Scope} to bind to. If none specified, then a new * root scope is created. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br/> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the template function returns the scope to which the element is bound to. It is either * the same scope as the one passed into the template function, or if none were provided it's the * newly create scope. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var view = angular.element('<p>{{total}}</p>'), * scope = angular.compile(view)(); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var original = angular.element('<p>{{total}}</p>'), * scope = someParentScope.$new(), * clone; * * angular.compile(original)(scope, function(clonedElement, scope) { * clone = clonedElement; * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * Compiler Methods For Widgets and Directives: * * The following methods are available for use when you write your own widgets, directives, * and markup. (Recall that the compile function's this is a reference to the compiler.) * * `compile(element)` - returns linker - * Invoke a new instance of the compiler to compile a DOM element and return a linker function. * You can apply the linker function to the original element or a clone of the original element. * The linker function returns a scope. * * * `comment(commentText)` - returns element - Create a comment element. * * * `element(elementName)` - returns element - Create an element by name. * * * `text(text)` - returns element - Create a text element. * * * `descend([set])` - returns descend state (true or false). Get or set the current descend * state. If true the compiler will descend to children elements. * * * `directives([set])` - returns directive state (true or false). Get or set the current * directives processing state. The compiler will process directives only when directives set to * true. * * For information on how the compiler works, see the * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide. */ function Compiler(markup, attrMarkup, directives, widgets){ this.markup = markup; this.attrMarkup = attrMarkup; this.directives = directives; this.widgets = widgets; } Compiler.prototype = { compile: function(templateElement) { templateElement = jqLite(templateElement); var index = 0, template, parent = templateElement.parent(); if (templateElement.length > 1) { // https://github.com/angular/angular.js/issues/338 throw Error("Cannot compile multiple element roots: " + jqLite('<div>').append(templateElement.clone()).html()); } if (parent && parent[0]) { parent = parent[0]; for(var i = 0; i < parent.childNodes.length; i++) { if (parent.childNodes[i] == templateElement[0]) { index = i; } } } template = this.templatize(templateElement, index, 0) || new Template(); return function(scope, cloneConnectFn){ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var element = cloneConnectFn ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!! : templateElement; scope = scope || createScope(); element.data($$scope, scope); scope.$element = element; (cloneConnectFn||noop)(element, scope); template.attach(element, scope); scope.$eval(); return scope; }; }, /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:eval-order * * @description * Normally the view is updated from top to bottom. This usually is * not a problem, but under some circumstances the values for data * is not available until after the full view is computed. If such * values are needed before they are computed the order of * evaluation can be changed using ng:eval-order * * @element ANY * @param {integer|string=} [priority=0] priority integer, or FIRST, LAST constant * * @example * try changing the invoice and see that the Total will lag in evaluation * @example <doc:example> <doc:source> <div>TOTAL: without ng:eval-order {{ items.$sum('total') | currency }}</div> <div ng:eval-order='LAST'>TOTAL: with ng:eval-order {{ items.$sum('total') | currency }}</div> <table ng:init="items=[{qty:1, cost:9.99, desc:'gadget'}]"> <tr> <td>QTY</td> <td>Description</td> <td>Cost</td> <td>Total</td> <td></td> </tr> <tr ng:repeat="item in items"> <td><input name="item.qty"/></td> <td><input name="item.desc"/></td> <td><input name="item.cost"/></td> <td>{{item.total = item.qty * item.cost | currency}}</td> <td><a href="" ng:click="items.$remove(item)">X</a></td> </tr> <tr> <td colspan="3"><a href="" ng:click="items.$add()">add</a></td> <td>{{ items.$sum('total') | currency }}</td> </tr> </table> </doc:source> <doc:scenario> it('should check ng:format', function(){ expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99'); expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$9.99'); input('item.qty').enter('2'); expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99'); expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$19.98'); }); </doc:scenario> </doc:example> */ templatize: function(element, elementIndex, priority){ var self = this, widget, fn, directiveFns = self.directives, descend = true, directives = true, elementName = nodeName_(element), elementNamespace = elementName.indexOf(':') > 0 ? lowercase(elementName).replace(':', '-') : '', template, selfApi = { compile: bind(self, self.compile), descend: function(value){ if(isDefined(value)) descend = value; return descend;}, directives: function(value){ if(isDefined(value)) directives = value; return directives;}, scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;} }; try { priority = element.attr('ng:eval-order') || priority || 0; } catch (e) { // for some reason IE throws error under some weird circumstances. so just assume nothing priority = priority || 0; } element.addClass(elementNamespace); if (isString(priority)) { priority = PRIORITY[uppercase(priority)] || parseInt(priority, 10); } template = new Template(priority); eachAttribute(element, function(value, name){ if (!widget) { if (widget = self.widgets('@' + name)) { element.addClass('ng-attr-widget'); widget = bind(selfApi, widget, value, element); } } }); if (!widget) { if (widget = self.widgets(elementName)) { if (elementNamespace) element.addClass('ng-widget'); widget = bind(selfApi, widget, element); } } if (widget) { descend = false; directives = false; var parent = element.parent(); template.addInit(widget.call(selfApi, element)); if (parent && parent[0]) { element = jqLite(parent[0].childNodes[elementIndex]); } } if (descend){ // process markup for text nodes only for(var i=0, child=element[0].childNodes; i<child.length; i++) { if (isTextNode(child[i])) { forEach(self.markup, function(markup){ if (i<child.length) { var textNode = jqLite(child[i]); markup.call(selfApi, textNode.text(), textNode, element); } }); } } } if (directives) { // Process attributes/directives eachAttribute(element, function(value, name){ forEach(self.attrMarkup, function(markup){ markup.call(selfApi, value, name, element); }); }); eachAttribute(element, function(value, name){ fn = directiveFns[name]; if (fn) { element.addClass('ng-directive'); template.addInit((directiveFns[name]).call(selfApi, value, element)); } }); } // Process non text child nodes if (descend) { eachNode(element, function(child, i){ template.addChild(i, self.templatize(child, i, priority)); }); } return template.empty() ? null : template; } }; function eachNode(element, fn){ var i, chldNodes = element[0].childNodes || [], chld; for (i = 0; i < chldNodes.length; i++) { if(!isTextNode(chld = chldNodes[i])) { fn(jqLite(chld), i); } } } function eachAttribute(element, fn){ var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {}; for (i = 0; i < attrs.length; i++) { attr = attrs[i]; name = attr.name; value = attr.value; if (msie && name == 'href') { value = decodeURIComponent(element[0].getAttribute(name, 2)); } attrValue[name] = value; } forEachSorted(attrValue, fn); } 'use strict'; function getter(instance, path, unboundFn) { if (!path) return instance; var element = path.split('.'); var key; var lastInstance = instance; var len = element.length; for ( var i = 0; i < len; i++) { key = element[i]; if (!key.match(/^[\$\w][\$\w\d]*$/)) throw "Expression '" + path + "' is not a valid expression for accessing variables."; if (instance) { lastInstance = instance; instance = instance[key]; } if (isUndefined(instance) && key.charAt(0) == '$') { var type = angular['Global']['typeOf'](lastInstance); type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; var fn = type ? type[[key.substring(1)]] : undefined; if (fn) { instance = bind(lastInstance, fn, lastInstance); return instance; } } } if (!unboundFn && isFunction(instance)) { return bind(lastInstance, instance); } return instance; } function setter(instance, path, value){ var element = path.split('.'); for ( var i = 0; element.length > 1; i++) { var key = element.shift(); var newInstance = instance[key]; if (!newInstance) { newInstance = {}; instance[key] = newInstance; } instance = newInstance; } instance[element.shift()] = value; return value; } /////////////////////////////////// var scopeId = 0, getterFnCache = {}, compileCache = {}, JS_KEYWORDS = {}; forEach( ("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," + "delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," + "if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," + "protected,public,return,short,static,super,switch,synchronized,this,throw,throws," + "transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/), function(key){ JS_KEYWORDS[key] = true;} ); function getterFn(path){ var fn = getterFnCache[path]; if (fn) return fn; var code = 'var l, fn, t;\n'; forEach(path.split('.'), function(key) { key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key; code += 'if(!s) return s;\n' + 'l=s;\n' + 's=s' + key + ';\n' + 'if(typeof s=="function" && !(s instanceof RegExp)) s = function(){ return l'+key+'.apply(l, arguments); };\n'; if (key.charAt(1) == '$') { // special code for super-imposed functions var name = key.substr(2); code += 'if(!s) {\n' + ' t = angular.Global.typeOf(l);\n' + ' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' + ' if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n' + '}\n'; } }); code += 'return s;'; fn = Function('s', code); fn["toString"] = function(){ return code; }; return getterFnCache[path] = fn; } /////////////////////////////////// function expressionCompile(exp){ if (typeof exp === $function) return exp; var fn = compileCache[exp]; if (!fn) { var p = parser(exp); var fnSelf = p.statements(); fn = compileCache[exp] = extend( function(){ return fnSelf(this);}, {fnSelf: fnSelf}); } return fn; } function errorHandlerFor(element, error) { elementError(element, NG_EXCEPTION, isDefined(error) ? formatError(error) : error); } /** * @workInProgress * @ngdoc overview * @name angular.scope * * @description * Scope is a JavaScript object and the execution context for expressions. You can think about * scopes as JavaScript objects that have extra APIs for registering watchers. A scope is the * context in which model (from the model-view-controller design pattern) exists. * * Angular scope objects provide the following methods: * * * {@link angular.scope.$become $become()} - * * {@link angular.scope.$bind $bind()} - * * {@link angular.scope.$eval $eval()} - * * {@link angular.scope.$get $get()} - * * {@link angular.scope.$new $new()} - * * {@link angular.scope.$onEval $onEval()} - * * {@link angular.scope.$service $service()} - * * {@link angular.scope.$set $set()} - * * {@link angular.scope.$tryEval $tryEval()} - * * {@link angular.scope.$watch $watch()} - * * For more information about how angular scope objects work, see {@link guide/dev_guide.scopes * Angular Scope Objects} in the angular Developer Guide. */ function createScope(parent, providers, instanceCache) { function Parent(){} parent = Parent.prototype = (parent || {}); var instance = new Parent(); var evalLists = {sorted:[]}; var $log, $exceptionHandler; extend(instance, { 'this': instance, $id: (scopeId++), $parent: parent, /** * @workInProgress * @ngdoc function * @name angular.scope.$bind * @function * * @description * Binds a function `fn` to the current scope. See: {@link angular.bind}. <pre> var scope = angular.scope(); var fn = scope.$bind(function(){ return this; }); expect(fn()).toEqual(scope); </pre> * * @param {function()} fn Function to be bound. */ $bind: bind(instance, bind, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$get * @function * * @description * Returns the value for `property_chain` on the current scope. Unlike in JavaScript, if there * are any `undefined` intermediary properties, `undefined` is returned instead of throwing an * exception. * <pre> var scope = angular.scope(); expect(scope.$get('person.name')).toEqual(undefined); scope.person = {}; expect(scope.$get('person.name')).toEqual(undefined); scope.person.name = 'misko'; expect(scope.$get('person.name')).toEqual('misko'); </pre> * * @param {string} property_chain String representing name of a scope property. Optionally * properties can be chained with `.` (dot), e.g. `'person.name.first'` * @returns {*} Value for the (nested) property. */ $get: bind(instance, getter, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$set * @function * * @description * Assigns a value to a property of the current scope specified via `property_chain`. Unlike in * JavaScript, if there are any `undefined` intermediary properties, empty objects are created * and assigned to them instead of throwing an exception. * <pre> var scope = angular.scope(); expect(scope.person).toEqual(undefined); scope.$set('person.name', 'misko'); expect(scope.person).toEqual({name:'misko'}); expect(scope.person.name).toEqual('misko'); </pre> * * @param {string} property_chain String representing name of a scope property. Optionally * properties can be chained with `.` (dot), e.g. `'person.name.first'` * @param {*} value Value to assign to the scope property. */ $set: bind(instance, setter, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$eval * @function * * @description * Without the `exp` parameter triggers an eval cycle for this scope and its child scopes. * * With the `exp` parameter, compiles the expression to a function and calls it with `this` set * to the current scope and returns the result. In other words, evaluates `exp` as angular * expression in the context of the current scope. * * # Example <pre> var scope = angular.scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(){ return this.a + this.b; })).toEqual(3); scope.$onEval('sum = a+b'); expect(scope.sum).toEqual(undefined); scope.$eval(); expect(scope.sum).toEqual(3); </pre> * * @param {(string|function())=} exp An angular expression to be compiled to a function or a js * function. * * @returns {*} The result of calling compiled `exp` with `this` set to the current scope. */ $eval: function(exp) { var type = typeof exp; var i, iSize; var j, jSize; var queue; var fn; if (type == $undefined) { for ( i = 0, iSize = evalLists.sorted.length; i < iSize; i++) { for ( queue = evalLists.sorted[i], jSize = queue.length, j= 0; j < jSize; j++) { instance.$tryEval(queue[j].fn, queue[j].handler); } } } else if (type === $function) { return exp.call(instance); } else if (type === 'string') { return expressionCompile(exp).call(instance); } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$tryEval * @function * * @description * Evaluates the expression in the context of the current scope just like * {@link angular.scope.$eval} with expression parameter, but also wraps it in a try/catch * block. * * If an exception is thrown then `exceptionHandler` is used to handle the exception. * * # Example <pre> var scope = angular.scope(); scope.error = function(){ throw 'myerror'; }; scope.$exceptionHandler = function(e) {this.lastException = e; }; expect(scope.$eval('error()')); expect(scope.lastException).toEqual('myerror'); this.lastException = null; expect(scope.$eval('error()'), function(e) {this.lastException = e; }); expect(scope.lastException).toEqual('myerror'); var body = angular.element(window.document.body); expect(scope.$eval('error()'), body); expect(body.attr('ng-exception')).toEqual('"myerror"'); expect(body.hasClass('ng-exception')).toEqual(true); </pre> * * @param {string|function()} expression Angular expression to evaluate. * @param {(function()|DOMElement)=} exceptionHandler Function to be called or DOMElement to be * decorated. * @returns {*} The result of `expression` evaluation. */ $tryEval: function (expression, exceptionHandler) { var type = typeof expression; try { if (type == $function) { return expression.call(instance); } else if (type == 'string'){ return expressionCompile(expression).call(instance); } } catch (e) { if ($log) $log.error(e); if (isFunction(exceptionHandler)) { exceptionHandler(e); } else if (exceptionHandler) { errorHandlerFor(exceptionHandler, e); } else if (isFunction($exceptionHandler)) { $exceptionHandler(e); } } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$watch * @function * * @description * Registers `listener` as a callback to be executed every time the `watchExp` changes. Be aware * that the callback gets, by default, called upon registration, this can be prevented via the * `initRun` parameter. * * # Example <pre> var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', 'counter = counter + 1'); expect(scope.counter).toEqual(1); scope.$eval(); expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$eval(); expect(scope.counter).toEqual(2); </pre> * * @param {function()|string} watchExp Expression that should be evaluated and checked for * change during each eval cycle. Can be an angular string expression or a function. * @param {function()|string} listener Function (or angular string expression) that gets called * every time the value of the `watchExp` changes. The function will be called with two * parameters, `newValue` and `oldValue`. * @param {(function()|DOMElement)=} [exceptionHanlder=angular.service.$exceptionHandler] Handler * that gets called when `watchExp` or `listener` throws an exception. If a DOMElement is * specified as a handler, the element gets decorated by angular with the information about the * exception. * @param {boolean=} [initRun=true] Flag that prevents the first execution of the listener upon * registration. * */ $watch: function(watchExp, listener, exceptionHandler, initRun) { var watch = expressionCompile(watchExp), last = watch.call(instance); listener = expressionCompile(listener); function watcher(firstRun){ var value = watch.call(instance), // we have to save the value because listener can call ourselves => inf loop lastValue = last; if (firstRun || lastValue !== value) { last = value; instance.$tryEval(function(){ return listener.call(instance, value, lastValue); }, exceptionHandler); } } instance.$onEval(PRIORITY_WATCH, watcher); if (isUndefined(initRun)) initRun = true; if (initRun) watcher(true); }, /** * @workInProgress * @ngdoc function * @name angular.scope.$onEval * @function * * @description * Evaluates the `expr` expression in the context of the current scope during each * {@link angular.scope.$eval eval cycle}. * * # Example <pre> var scope = angular.scope(); scope.counter = 0; scope.$onEval('counter = counter + 1'); expect(scope.counter).toEqual(0); scope.$eval(); expect(scope.counter).toEqual(1); </pre> * * @param {number} [priority=0] Execution priority. Lower priority numbers get executed first. * @param {string|function()} expr Angular expression or function to be executed. * @param {(function()|DOMElement)=} [exceptionHandler=angular.service.$exceptionHandler] Handler * function to call or DOM element to decorate when an exception occurs. * */ $onEval: function(priority, expr, exceptionHandler){ if (!isNumber(priority)) { exceptionHandler = expr; expr = priority; priority = 0; } var evalList = evalLists[priority]; if (!evalList) { evalList = evalLists[priority] = []; evalList.priority = priority; evalLists.sorted.push(evalList); evalLists.sorted.sort(function(a,b){return a.priority-b.priority;}); } evalList.push({ fn: expressionCompile(expr), handler: exceptionHandler }); }, /** * @workInProgress * @ngdoc function * @name angular.scope.$become * @function * @deprecated This method will be removed before 1.0 * * @description * Modifies the scope to act like an instance of the given class by: * * - copying the class's prototype methods * - applying the class's initialization function to the scope instance (without using the new * operator) * * That makes the scope be a `this` for the given class's methods — effectively an instance of * the given class with additional (scope) stuff. A scope can later `$become` another class. * * `$become` gets used to make the current scope act like an instance of a controller class. * This allows for use of a controller class in two ways. * * - as an ordinary JavaScript class for standalone testing, instantiated using the new * operator, with no attached view. * - as a controller for an angular model stored in a scope, "instantiated" by * `scope.$become(ControllerClass)`. * * Either way, the controller's methods refer to the model variables like `this.name`. When * stored in a scope, the model supports data binding. When bound to a view, {{name}} in the * HTML template refers to the same variable. */ $become: function(Class) { if (isFunction(Class)) { instance.constructor = Class; forEach(Class.prototype, function(fn, name){ instance[name] = bind(instance, fn); }); instance.$service.invoke(instance, Class, slice.call(arguments, 1, arguments.length)); //TODO: backwards compatibility hack, remove when we don't depend on init methods if (isFunction(Class.prototype.init)) { instance.init(); } } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$new * @function * * @description * Creates a new {@link angular.scope scope}, that: * * - is a child of the current scope * - will {@link angular.scope.$become $become} of type specified via `constructor` * * @param {function()} constructor Constructor function of the type the new scope should assume. * @returns {Object} The newly created child scope. * */ $new: function(constructor) { var child = createScope(instance); child.$become.apply(instance, concat([constructor], arguments, 1)); instance.$onEval(child.$eval); return child; } }); if (!parent.$root) { instance.$root = instance; instance.$parent = instance; /** * @workInProgress * @ngdoc function * @name angular.scope.$service * @function * * @description * Provides access to angular's dependency injector and * {@link angular.service registered services}. In general the use of this api is discouraged, * except for tests and components that currently don't support dependency injection (widgets, * filters, etc). * * @param {string} serviceId String ID of the service to return. * @returns {*} Value, object or function returned by the service factory function if any. */ (instance.$service = createInjector(instance, providers, instanceCache)).eager(); } $log = instance.$service('$log'); $exceptionHandler = instance.$service('$exceptionHandler'); return instance; } 'use strict'; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/dev_guide.di dependency injection}). * * Angular creates an injector automatically for the root scope and it is available as the * {@link angular.scope.$service $service} property. Creation of the injector automatically creates * all of the `$eager` {@link angular.service services}. * * @param {Object=} [factoryScope={}] `this` for the service factory function. * @param {Object.<string, function()>=} [factories=angular.service] Map of service factory * functions. * @param {Object.<string, function()>=} [instanceCache={}] Place where instances of services are * saved for reuse. Can also be used to override services specified by `serviceFactory` * (useful in tests). * @returns {function()} Injector function: * * * `injector(serviceName)`: * * `serviceName` - `{string=}` - name of the service to retrieve. * * The injector function also has these properties: * * * an `invoke` property which can be used to invoke methods with dependency-injected arguments. * `injector.invoke(self, fn, curryArgs)` * * `self` - "`this`" to be used when invoking the function. * * `fn` - the function to be invoked. The function may have the `$inject` property which * lists the set of arguments which should be auto injected * (see {@link guide/dev_guide.di dependency injection}). * * `curryArgs(array)` - optional array of arguments to pass to function invocation after the * injection arguments (also known as curry arguments or currying). * * an `eager` property which is used to initialize the eager services. * `injector.eager()` */ function createInjector(factoryScope, factories, instanceCache) { factories = factories || angularService; instanceCache = instanceCache || {}; factoryScope = factoryScope || {}; injector.invoke = invoke; injector.eager = function(){ forEach(factories, function(factory, name){ if (factory.$eager) injector(name); if (factory.$creation) throw new Error("Failed to register service '" + name + "': $creation property is unsupported. Use $eager:true or see release notes."); }); }; return injector; function injector(value){ if (!(value in instanceCache)) { var factory = factories[value]; if (!factory) throw Error("Unknown provider for '"+value+"'."); instanceCache[value] = invoke(factoryScope, factory); } return instanceCache[value]; } function invoke(self, fn, args){ args = args || []; var injectNames = injectionArgs(fn); var i = injectNames.length; while(i--) { args.unshift(injector(injectNames[i])); } return fn.apply(self, args); } } /** * THIS IS NOT PUBLIC DOC YET! * * @name angular.annotate * @function * * @description * Annotate the function with injection arguments. This is equivalent to setting the `$inject` * property as described in {@link guide.di dependency injection}. * * <pre> * var MyController = angular.annotate('$location', function($location){ ... }); * </pre> * * is the same as * * <pre> * var MyController = function($location){ ... }; * MyController.$inject = ['$location']; * </pre> * * @param {String|Array} serviceName... zero or more service names to inject into the * `annotatedFunction`. * @param {function} annotatedFunction function to annotate with `$inject` * functions. * @returns {function} `annotatedFunction` */ function annotate(services, fn) { if (services instanceof Array) { fn.$inject = services; return fn; } else { var i = 0, length = arguments.length - 1, // last one is the destination function $inject = arguments[length].$inject = []; for (; i < length; i++) { $inject.push(arguments[i]); } return arguments[length]; // return the last one } } function angularServiceInject(name, fn, inject, eager) { angularService(name, fn, {$inject:inject, $eager:eager}); } /** * @returns the $inject property of function. If not found the * the $inject is computed by looking at the toString of function and * extracting all arguments which and assuming that they are the * injection names. */ var FN_ARGS = /^function\s*[^\(]*\(([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(.+?)\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function injectionArgs(fn) { assertArgFn(fn); if (!fn.$inject) { var args = fn.$inject = []; var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, name){ args.push(name); }); }); } return fn.$inject; } 'use strict'; var OPERATORS = { 'null':function(self){return null;}, 'true':function(self){return true;}, 'false':function(self){return false;}, $undefined:noop, '+':function(self, a,b){return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, a,b){return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, a,b){return a*b;}, '/':function(self, a,b){return a/b;}, '%':function(self, a,b){return a%b;}, '^':function(self, a,b){return a^b;}, '=':noop, '==':function(self, a,b){return a==b;}, '!=':function(self, a,b){return a!=b;}, '<':function(self, a,b){return a<b;}, '>':function(self, a,b){return a>b;}, '<=':function(self, a,b){return a<=b;}, '>=':function(self, a,b){return a>=b;}, '&&':function(self, a,b){return a&&b;}, '||':function(self, a,b){return a||b;}, '&':function(self, a,b){return a&b;}, // '|':function(self, a,b){return a|b;}, '|':function(self, a,b){return b(self, a);}, '!':function(self, a){return !a;} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, parseStringsForObjects){ var dateParseLength = parseStringsForObjects ? DATE_ISOSTRING_LN : -1, tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function(){return number;}}); } function readIdent() { var ident = ""; var start = index; var fn; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { ident += ch; } else { break; } index++; } fn = OPERATORS[ident]; tokens.push({ index:start, text:ident, json: fn, fn:fn||extend(getterFn(ident), { assign:function(self, value){ return setter(self, ident, value); } }) }); } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({index:start, text:rawString, string:string, json:true, fn:function(){ return (string.length == dateParseLength) ? angular['String']['toDate'](string) : string; }}); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json){ var ZERO = valueFn(0), tokens = lex(text, json), assignment = _assignment, assignable = logicalOR, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain, functionIdent = _functionIdent, pipeFunction = _pipeFunction; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = assignable = filterChain = functionIdent = pipeFunction = function (){ throwError("is not valid json", {text:text, index:0}); }; } //TODO: Shouldn't all of the public methods have assertAllConsumed? //TODO: I think these should be public as part of the parser api instead of scope.$eval(). return { assignable: assertConsumed(assignable), primary: assertConsumed(primary), statements: assertConsumed(statements), validator: assertConsumed(validator), formatter: assertConsumed(formatter), filter: assertConsumed(filter) }; function assertConsumed(fn) { return function(){ var value = fn(); if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } return value; }; } /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self) { return fn(self, right(self)); }; } function binaryFn(left, fn, right) { return function(self) { return fn(self, left(self), right(self)); }; } function hasTokens () { return tokens.length > 0; } function statements(){ var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function (self){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self); } return value; }; } } } function _filterChain(){ var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter(){ return pipeFunction(angularFilter); } function validator(){ return pipeFunction(angularValidator); } function formatter(){ var token = expect(); var formatter = angularFormatter[token.text]; var argFns = []; if (!formatter) throwError('is not a valid formatter.', token); while(true) { if ((token = expect(':'))) { argFns.push(expression()); } else { return valueFn({ format:invokeFn(formatter.format), parse:invokeFn(formatter.parse) }); } } function invokeFn(fn){ return function(self, input){ var args = [input]; for ( var i = 0; i < argFns.length; i++) { args.push(argFns[i](self)); } return fn.apply(self, args); }; } } function _pipeFunction(fnScope){ var fn = functionIdent(fnScope); var argsFn = []; var token; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } return fn.apply(self, args); }; return function(){ return fnInvoke; }; } } } function expression(){ return assignment(); } function _assignment(){ var left = logicalOR(); var right; var token; if (token = expect('=')) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self){ return left.assign(self, right(self)); }; } else { return left; } } function logicalOR(){ var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND(){ var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality(){ var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational(){ var left = additive(); var token; if (token = expect('<', '>', '<=', '>=')) { left = binaryFn(left, token.fn, relational()); } return left; } function additive(){ var left = multiplicative(); var token; while(token = expect('+','-')) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative(){ var left = unary(); var token; while(token = expect('*','/','%')) { left = binaryFn(left, token.fn, unary()); } return left; } function unary(){ var token; if (expect('+')) { return primary(); } else if (token = expect('-')) { return binaryFn(ZERO, token.fn, unary()); } else if (token = expect('!')) { return unaryFn(token.fn, unary()); } else { return primary(); } } function _functionIdent(fnScope) { var token = expect(); var element = token.text.split('.'); var instance = fnScope; var key; for ( var i = 0; i < element.length; i++) { key = element[i]; if (instance) instance = instance[key]; } if (typeof instance != $function) { throwError("should be a function", token); } return instance; } function primary() { var primary; if (expect('(')) { var expression = filterChain(); consume(')'); primary = expression; } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next; while (next = expect('(', '[', '.')) { if (next.text === '(') { primary = functionCall(primary); } else if (next.text === '[') { primary = objectIndex(primary); } else if (next.text === '.') { primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field); return extend(function (self){ return getter(object(self)); }, { assign:function(self, value){ return setter(object(self), field, value); } }); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function (self){ var o = obj(self); var i = indexFn(self); return (o) ? o[i] : undefined; }, { assign:function(self, value){ return obj(self)[indexFn(self)] = value; } }); } function _functionCall(fn) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function (self){ var args = []; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } var fnPtr = fn(self) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(self, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function (self){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function (self){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self); object[keyValue.key] = value; } return object; }; } function watchDecl () { var anchorName = expect().text; consume(":"); var expressionFn; if (peekToken().text == '{') { consume("{"); expressionFn = statements(); consume("}"); } else { expressionFn = expression(); } return function(self) { return {name:anchorName, fn:expressionFn}; }; } } 'use strict'; function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && template.match(new RegExp(":" + param + "\\W"))) { urlParams[param] = true; } }); } Route.prototype = { url: function(params) { var self = this, url = this.template, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || ""); url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1"); }); url = url.replace(/\/?#$/, ''); var query = []; forEachSorted(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(xhr) { this.xhr = xhr; } ResourceFactory.DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; ResourceFactory.prototype = { route: function(url, paramDefaults, actions){ var self = this; var route = new Route(url); actions = extend({}, ResourceFactory.DEFAULT_ACTIONS, actions); function extractParams(data){ var ids = {}; forEach(paramDefaults || {}, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name){ var isPostOrPut = action.method == 'POST' || action.method == 'PUT'; Resource[name] = function (a1, a2, a3, a4) { var params = {}; var data; var success = noop; var error = null; switch(arguments.length) { case 4: error = a4; success = a3; //fallthrough case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; //fallthrough } else { params = a1; data = a2; success = a3; break; } case 1: if (isFunction(a1)) success = a1; else if (isPostOrPut) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); self.xhr( action.method, route.url(extend({}, action.params || {}, extractParams(data), params)), data, function(status, response, responseHeaders) { if (response) { if (action.isArray) { value.length = 0; forEach(response, function(item) { value.push(new Resource(item)); }); } else { copy(response, value); } } (success||noop)(value, responseHeaders); }, error || action.verifyCache, action.verifyCache); return value; }; Resource.bind = function(additionalParamDefaults){ return self.route(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; Resource.prototype['$' + name] = function(a1, a2, a3) { var params = extractParams(this), success = noop, error; switch(arguments.length) { case 3: params = a1; success = a2; error = a3; break; case 2: case 1: if (isFunction(a1)) { success = a1; error = a2; } else { params = a1; success = a2 || noop; } case 0: break; default: throw "Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } var data = isPostOrPut ? this : undefined; Resource[name].call(this, params, data, success, error); }; }); return Resource; } }; 'use strict'; ////////////////////////////// // Browser ////////////////////////////// var XHR = window.XMLHttpRequest || function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc service * @name angular.service.$browser * @requires $log * * @description * Constructor for the object exposed as $browser service. * * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link angular.mock.service.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} body jQuery wrapped document.body. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. */ function Browser(window, document, body, XHR, $log) { var self = this, rawDocument = document[0], location = window.location, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}, lastLocationUrl; self.isMock = false; ////////////////////////////////////////////////////////////// // XHR API ////////////////////////////////////////////////////////////// var idCounter = 0; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; /** * Executes the `fn` function (supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, slice.call(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @workInProgress * @ngdoc method * @name angular.service.$browser#xhr * @methodOf angular.service.$browser * * @param {string} method Requested method (get|post|put|delete|head|json) * @param {string} url Requested url * @param {?string} post Post data to send (null if nothing to post) * @param {function(number, string, function([string]))} callback Function that will be called on * response. The third argument is a function that can be called to return a specified response * header or an Object containing all headers (when called with no arguments). * @param {object=} header additional HTTP headers to send with XHR. * Standard headers are: * <ul> * <li><tt>Content-Type</tt>: <tt>application/x-www-form-urlencoded</tt></li> * <li><tt>Accept</tt>: <tt>application/json, text/plain, &#42;/&#42;</tt></li> * <li><tt>X-Requested-With</tt>: <tt>XMLHttpRequest</tt></li> * </ul> * * @description * Send ajax request */ self.xhr = function(method, url, post, callback, headers) { var parsedHeaders; outstandingRequestCount ++; if (lowercase(method) == 'json') { var callbackId = ("angular_" + Math.random() + '_' + (idCounter++)).replace(/\d\./, ''); window[callbackId] = function(data) { window[callbackId].data = data; }; var script = self.addJs(url.replace('JSON_CALLBACK', callbackId), null, function() { if (window[callbackId].data) { completeOutstandingRequest(callback, 200, window[callbackId].data); } else { completeOutstandingRequest(callback); } delete window[callbackId]; body[0].removeChild(script); }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // normalize IE bug (http://bugs.jquery.com/ticket/1450) var status = xhr.status == 1223 ? 204 : xhr.status || 200; completeOutstandingRequest(callback, status, xhr.responseText, function(header) { header = lowercase(header); if (header) { return parsedHeaders ? parsedHeaders[header] || null : xhr.getResponseHeader(header); } else { // Return an object containing each response header parsedHeaders = {}; forEach(xhr.getAllResponseHeaders().split('\n'), function(line) { var i = line.indexOf(':'), key = lowercase(trim(line.substr(0, i))), value = trim(line.substr(i + 1)); if (parsedHeaders[key]) { // Combine repeated headers // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 parsedHeaders[key] += ', ' + value; } else { parsedHeaders[key] = value; } }); return parsedHeaders; } }); } }; xhr.send(post || ''); } }; /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addPollFn * @methodOf angular.service.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); }; ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// /** * @workInProgress * @ngdoc method * @name angular.service.$browser#setUrl * @methodOf angular.service.$browser * * @param {string} url New url * * @description * Sets browser's url */ self.setUrl = function(url) { var existingURL = lastLocationUrl; if (!existingURL.match(/#/)) existingURL += '#'; if (!url.match(/#/)) url += '#'; if (existingURL != url) { location.href = url; } }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#getUrl * @methodOf angular.service.$browser * * @description * Get current browser's url * * @returns {string} Browser's url */ self.getUrl = function() { return lastLocationUrl = location.href; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#onHashChange * @methodOf angular.service.$browser * * @description * Detects if browser support onhashchange events and register a listener otherwise registers * $browser poller. The `listener` will then get called when the hash changes. * * The listener gets called with either HashChangeEvent object or simple object that also contains * `oldURL` and `newURL` properties. * * Note: this api is intended for use only by the $location service. Please use the * {@link angular.service.$location $location service} to monitor hash changes in angular apps. * * @param {function(event)} listener Listener function to be called when url hash changes. * @return {function()} Returns the registered listener fn - handy if the fn is anonymous. */ self.onHashChange = function(listener) { // IE8 comp mode returns true, but doesn't support hashchange event var dm = window.document.documentMode; if ('onhashchange' in window && (isUndefined(dm) || dm >= 8)) { jqLite(window).bind('hashchange', listener); } else { var lastBrowserUrl = self.getUrl(); self.addPollFn(function() { if (lastBrowserUrl != self.getUrl()) { listener(); lastBrowserUrl = self.getUrl(); } }); } return listener; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#cookies * @methodOf angular.service.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function (name, value) { var cookieLength, cookieArray, cookie, i, keyValue, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { rawDocument.cookie = escape(name) + '=' + escape(value); cookieLength = name.length + value.length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#defer * @methodOf angular.service.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * THIS DOC IS NOT VISIBLE because ngdocs can't process docs for foo#method.method * * @name angular.service.$browser#defer.cancel * @methodOf angular.service.$browser.defer * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. * * @description * Cancels a defered task identified with `deferId`. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// var hoverListener = noop; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#hover * @methodOf angular.service.$browser * * @description * Set hover listener. * * @param {function(Object, boolean)} listener Function that will be called when a hover event * occurs. */ self.hover = function(listener) { hoverListener = listener; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#bind * @methodOf angular.service.$browser * * @description * Register hover function to real browser */ self.bind = function() { document.bind("mouseover", function(event){ hoverListener(jqLite(msie ? event.srcElement : event.target), true); return true; }); document.bind("mouseleave mouseout click dblclick keypress keyup", function(event){ hoverListener(jqLite(event.target), false); return true; }); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addCss * @methodOf angular.service.$browser * * @param {string} url Url to css file * @description * Adds a stylesheet tag to the head. */ self.addCss = function(url) { var link = jqLite(rawDocument.createElement('link')); link.attr('rel', 'stylesheet'); link.attr('type', 'text/css'); link.attr('href', url); body.append(link); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addJs * @methodOf angular.service.$browser * * @param {string} url Url to js file * @param {string=} domId Optional id for the script tag * * @description * Adds a script tag to the head. */ self.addJs = function(url, domId, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document // // We need addJs to be able to add angular-ie-compat.js which is very special and must remain // part of the DOM so that the embedded images can reference it. jQuery's append implementation // (v1.4.2) fubars it. var script = rawDocument.createElement('script'); script.type = 'text/javascript'; script.src = url; if (domId) script.id = domId; if (msie) { script.onreadystatechange = function() { /loaded|complete/.test(script.readyState) && done && done(); }; } else { if (done) script.onload = script.onerror = done; } body[0].appendChild(script); return script; }; } 'use strict'; /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) // Empty Elements - HTML 4.01 var emptyElements = makeMap("area,br,col,hr,img"); // Block Elements - HTML 4.01 var blockElements = makeMap("address,blockquote,center,dd,del,dir,div,dl,dt,"+ "hr,ins,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul"); // Inline Elements - HTML 4.01 var inlineElements = makeMap("a,abbr,acronym,b,bdo,big,br,cite,code,del,dfn,em,font,i,img,"+ "ins,kbd,label,map,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var"); // Elements that you can, intentionally, leave open // (and which close themselves) var closeSelfElements = makeMap("colgroup,dd,dt,li,p,td,tfoot,th,thead,tr"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = extend({}, emptyElements, blockElements, inlineElements, closeSelfElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,href,longdesc,src,usemap"); var validAttrs = extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function(){ return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( closeSelfElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = emptyElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) { var value = doubleQuotedValue || singleQoutedValue || unqoutedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { hiddenPre.innerHTML=value.replace(/</g,"&lt;"); return hiddenPre.innerText || hiddenPre.textContent || ''; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] == true) { out('<'); out(tag); forEach(attrs, function(value, key){ var lkey=lowercase(key); if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = lowercase(tag); if (!ignore && validElements[tag] == true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } 'use strict'; ////////////////////////////////// //JQLite ////////////////////////////////// /** * @workInProgress * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as [jQuery](http://jquery.com) element. * `angular.element` is either an alias for [jQuery](http://api.jquery.com/jQuery/) function if * jQuery is loaded or a function that wraps the element or string in angular's jQuery lite * implementation. * * Real jQuery always takes precedence (as long as it was loaded before `DOMContentEvent`) * * Angular's jQuery lite implementation is a tiny API-compatible subset of jQuery which allows * angular to manipulate DOM. The jQuery lite implements only a subset of jQuery api, with the * focus on the most commonly needed functionality and minimal footprint. For this reason only a * limited number of jQuery methods, arguments and invocation styles are supported. * * Note: All element references in angular are always wrapped with jQuery (lite) and are never * raw DOM references. * * ## Angular's jQuery lite implements these functions: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [hasClass()](http://api.jquery.com/hasClass/) * - [parent()](http://api.jquery.com/parent/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [trigger()](http://api.jquery.com/trigger/) * - [eq()](http://api.jquery.com/eq/) * * ## Additionally these methods extend the jQuery and are available in both jQuery and jQuery lite * version: * *- `scope()` - retrieves the current angular scope of the element. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = {}, jqName = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return (jqId++); } function getStyle(element) { var current = {}, style = element[0].style, value, name, i; if (typeof style.length == 'number') { for(i = 0; i < style.length; i++) { name = style[i]; current[name] = style[name]; } } else { for (name in style) { value = style[name]; if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false') current[name] = value; } } return current; } ///////////////////////////////////////////// function jqLiteWrap(element) { if (isString(element) && element.charAt(0) != '<') { throw new Error('selectors not implemented'); } return new JQLite(element); } function JQLite(element) { if (element instanceof JQLite) { return element; } else if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteRemoveData(element) { var cacheId = element[jqName], cache = jqCache[cacheId]; if (cache) { forEach(cache.bind || {}, function(fn, type){ removeEventListenerFn(element, type, fn); }); delete jqCache[cacheId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteData(element, key, value) { var cacheId = element[jqName], cache = jqCache[cacheId || -1]; if (isDefined(value)) { if (!cache) { element[jqName] = cacheId = jqNextId(); cache = jqCache[cacheId] = {}; } cache[key] = value; } else { return cache ? cache[key] : null; } } function JQLiteHasClass(element, selector, _) { // the argument '_' is important, since it makes the function have 3 arguments, which // is needed for delegate function to realize the this is a getter. var className = " " + selector + " "; return ((" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1); } function JQLiteRemoveClass(element, selector) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + selector + " ", "") ); } function JQLiteAddClass(element, selector ) { if (!JQLiteHasClass(element, selector)) { element.className = trim(element.className + ' ' + selector); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. jqLiteWrap(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var SPECIAL_ATTR = makeMap("multiple,selected,checked,disabled,readonly"); forEach({ data: JQLiteData, scope: function(element) { var scope; while (element && !(scope = jqLite(element).data($$scope))) { element = element.parentNode; } return scope; }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { if (isDefined(value)) { element.style[name] = value; } else { return element.style[name]; } }, attr: function(element, name, value){ if (SPECIAL_ATTR[name]) { if (isDefined(value)) { element[name] = !!value; } else { return element[name]; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, text: extend((msie < 9) ? function(element, value) { // NodeType == 3 is text node if (element.nodeType == 3) { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } else { if (isUndefined(value)) return element.innerText; element.innerText = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; if ((fn.length == 2 ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { for (key in arg1) { fn(this[i], key, arg1[key]); } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function(element, type, fn){ var bind = JQLiteData(element, 'bind'); if (!bind) JQLiteData(element, 'bind', bind = {}); forEach(type.split(' '), function(type){ var eventHandler = bind[type]; if (!eventHandler) { bind[type] = eventHandler = function(event) { if (!event.preventDefault) { event.preventDefault = function(){ event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } forEach(eventHandler.fns, function(fn){ fn.call(element, event); }); }; eventHandler.fns = []; addEventListenerFn(element, type, eventHandler); } eventHandler.fns.push(fn); }); }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); 'use strict'; var angularGlobal = { 'typeOf':function(obj){ if (obj === null) return $null; var type = typeof obj; if (type == $object) { if (obj instanceof Array) return $array; if (isDate(obj)) return $date; if (obj.nodeType == 1) return $element; } return type; } }; /** * @ngdoc overview * @name angular.Object * @function * * @description * A namespace for utility functions used to work with JavaScript objects. These functions are * exposed in two ways: * * __* Angular expressions:__ Functions are bound to all objects and augment the Object type. The * names of these methods are prefixed with the '$' character in order to minimize naming collisions. * To call a method, invoke the function without the first argument, e.g, `myObject.$foo(param2)`. * * __* JavaScript code:__ Functions don't augment the Object type and must be invoked as functions of * `angular.Object` as `angular.Object.foo(myObject, param2)`. * * * {@link angular.Object.copy angular.Object.copy()} - Creates a deep copy of the source parameter * * {@link angular.Object.equals angular.Object.equals()} - Determines if two objects or values are * equivalent * * {@link angular.Object.size angular.Object.size()} - Determines the number of elements in * strings, arrays, and objects. */ var angularCollection = { 'copy': copy, 'size': size, 'equals': equals }; var angularObject = { 'extend': extend }; /** * @ngdoc overview * @name angular.Array * * @description * A namespace for utility functions for the manipulation of JavaScript Array objects. * * These functions are exposed in two ways: * * * __Angular expressions:__ Functions are bound to the Array objects and augment the Array type as * array methods. The names of these methods are prefixed with $ character to minimize naming * collisions. To call a method, invoke myArrayObject.$foo(params). * * Because Array type is a subtype of the Object type, all angular.Object functions augment * theArray type in angular expressions as well. * * * __JavaScript code:__ Functions don't augment the Array type and must be invoked as functions of * `angular.Array` as `angular.Array.foo(myArrayObject, params)`. * * The following APIs are built-in to the angular Array object: * * * {@link angular.Array.add angular.Array.add()} - Optionally adds a new element to an array. * * {@link angular.Array.count angular.Array.count()} - Determines the number of elements in an * array. * * {@link angular.Array.filter angular.Array.filter()} - Returns a subset of items as a new array. * * {@link angular.Array.indexOf angular.Array.indexOf()} - Determines the index of an array value. * * {@link angular.Array.limitTo angular.Array.limitTo()} - Creates a new array off the front or * back of an existing array. * * {@link angular.Array.orderBy angular.Array.orderBy()} - Orders array elements * * {@link angular.Array.remove angular.Array.remove()} - Removes array elements * * {@link angular.Array.sum angular.Array.sum()} - Sums the number elements in an array */ var angularArray = { /** * @ngdoc function * @name angular.Array.indexOf * @function * * @description * Determines the index of `value` in `array`. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Array to search. * @param {*} value Value to search for. * @returns {number} The position of the element in `array`. The position is 0-based. `-1` is returned if the value can't be found. * * @example <doc:example> <doc:source> <div ng:init="books = ['Moby Dick', 'Great Gatsby', 'Romeo and Juliet']"></div> <input name='bookName' value='Romeo and Juliet'> <br> Index of '{{bookName}}' in the list {{books}} is <em>{{books.$indexOf(bookName)}}</em>. </doc:source> <doc:scenario> it('should correctly calculate the initial index', function() { expect(binding('books.$indexOf(bookName)')).toBe('2'); }); it('should recalculate', function() { input('bookName').enter('foo'); expect(binding('books.$indexOf(bookName)')).toBe('-1'); input('bookName').enter('Moby Dick'); expect(binding('books.$indexOf(bookName)')).toBe('0'); }); </doc:scenario> </doc:example> */ 'indexOf': indexOf, /** * @ngdoc function * @name angular.Array.sum * @function * * @description * This function calculates the sum of all numbers in `array`. If the `expressions` is supplied, * it is evaluated once for each element in `array` and then the sum of these values is returned. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The source array. * @param {(string|function())=} expression Angular expression or a function to be evaluated for each * element in `array`. The array element becomes the `this` during the evaluation. * @returns {number} Sum of items in the array. * * @example <doc:example> <doc:source> <table ng:init="invoice= {items:[{qty:10, description:'gadget', cost:9.95}]}"> <tr><th>Qty</th><th>Description</th><th>Cost</th><th>Total</th><th></th></tr> <tr ng:repeat="item in invoice.items"> <td><input name="item.qty" value="1" size="4" ng:required ng:validate="integer"></td> <td><input name="item.description"></td> <td><input name="item.cost" value="0.00" ng:required ng:validate="number" size="6"></td> <td>{{item.qty * item.cost | currency}}</td> <td>[<a href ng:click="invoice.items.$remove(item)">X</a>]</td> </tr> <tr> <td><a href ng:click="invoice.items.$add()">add item</a></td> <td></td> <td>Total:</td> <td>{{invoice.items.$sum('qty*cost') | currency}}</td> </tr> </table> </doc:source> <doc:scenario> //TODO: these specs are lame because I had to work around issues #164 and #167 it('should initialize and calculate the totals', function() { expect(repeater('.doc-example-live table tr', 'item in invoice.items').count()).toBe(3); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(1)). toEqual(['$99.50']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); }); it('should add an entry and recalculate', function() { element('.doc-example-live a:contains("add item")').click(); using('.doc-example-live tr:nth-child(3)').input('item.qty').enter('20'); using('.doc-example-live tr:nth-child(3)').input('item.cost').enter('100'); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(2)). toEqual(['$2,000.00']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$2,099.50'); }); </doc:scenario> </doc:example> */ 'sum':function(array, expression) { var fn = angular['Function']['compile'](expression); var sum = 0; for (var i = 0; i < array.length; i++) { var value = 1 * fn(array[i]); if (!isNaN(value)){ sum += value; } } return sum; }, /** * @ngdoc function * @name angular.Array.remove * @function * * @description * Modifies `array` by removing an element from it. The element will be looked up using the * {@link angular.Array.indexOf indexOf} function on the `array` and only the first instance of * the element will be removed. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Array from which an element should be removed. * @param {*} value Element to be removed. * @returns {*} The removed element. * * @example <doc:example> <doc:source> <ul ng:init="tasks=['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']"> <li ng:repeat="task in tasks"> {{task}} [<a href="" ng:click="tasks.$remove(task)">X</a>] </li> </ul> <hr/> tasks = {{tasks}} </doc:source> <doc:scenario> it('should initialize the task list with for tasks', function() { expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(4); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']); }); it('should initialize the task list with for tasks', function() { element('.doc-example-live ul li a:contains("X"):first').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(3); element('.doc-example-live ul li a:contains("X"):last').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(2); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Read Documentation', 'Check out demos']); }); </doc:scenario> </doc:example> */ 'remove':function(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; }, /** * @ngdoc function * @name angular.Array.filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng:init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input name="searchText"/> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(searchText)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input name="search.$"/> <br> Name only <input name="search.name"/><br> Phone only <input name="search.phone"/><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(search)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ 'filter':function(array, expression) { var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function(){ var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function(){ var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case $function: predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }, /** * @workInProgress * @ngdoc function * @name angular.Array.add * @function * * @description * `add` is a function similar to JavaScript's `Array#push` method, in that it appends a new * element to an array. The difference is that the value being added is optional and defaults to * an empty object. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array expand. * @param {*=} [value={}] The value to be added. * @returns {Array} The expanded array. * * @TODO simplify the example. * * @example * This example shows how an initially empty array can be filled with objects created from user * input via the `$add` method. <doc:example> <doc:source> [<a href="" ng:click="people.$add()">add empty</a>] [<a href="" ng:click="people.$add({name:'John', sex:'male'})">add 'John'</a>] [<a href="" ng:click="people.$add({name:'Mary', sex:'female'})">add 'Mary'</a>] <ul ng:init="people=[]"> <li ng:repeat="person in people"> <input name="person.name"> <select name="person.sex"> <option value="">--chose one--</option> <option>male</option> <option>female</option> </select> [<a href="" ng:click="people.$remove(person)">X</a>] </li> </ul> <pre>people = {{people}}</pre> </doc:source> <doc:scenario> beforeEach(function() { expect(binding('people')).toBe('people = []'); }); it('should create an empty record when "add empty" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); expect(binding('people')).toBe('people = [{\n "name":"",\n "sex":null}]'); }); it('should create a "John" record when "add \'John\'" is clicked', function() { element('.doc-example-live a:contains("add \'John\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"John",\n "sex":"male"}]'); }); it('should create a "Mary" record when "add \'Mary\'" is clicked', function() { element('.doc-example-live a:contains("add \'Mary\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"Mary",\n "sex":"female"}]'); }); it('should delete a record when "X" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); element('.doc-example-live li a:contains("X"):first').click(); expect(binding('people')).toBe('people = []'); }); </doc:scenario> </doc:example> */ 'add':function(array, value) { array.push(isUndefined(value)? {} : value); return array; }, /** * @ngdoc function * @name angular.Array.count * @function * * @description * Determines the number of elements in an array. Optionally it will count only those elements * for which the `condition` evaluates to `true`. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array to count elements in. * @param {(function()|string)=} condition A function to be evaluated or angular expression to be * compiled and evaluated. The element that is currently being iterated over, is exposed to * the `condition` as `this`. * @returns {number} Number of elements in the array (for which the condition evaluates to true). * * @example <doc:example> <doc:source> <pre ng:init="items = [{name:'knife', points:1}, {name:'fork', points:3}, {name:'spoon', points:1}]"></pre> <ul> <li ng:repeat="item in items"> {{item.name}}: points= <input type="text" name="item.points"/> <!-- id="item{{$index}} --> </li> </ul> <p>Number of items which have one point: <em>{{ items.$count('points==1') }}</em></p> <p>Number of items which have more than one point: <em>{{items.$count('points&gt;1')}}</em></p> </doc:source> <doc:scenario> it('should calculate counts', function() { expect(binding('items.$count(\'points==1\')')).toEqual(2); expect(binding('items.$count(\'points>1\')')).toEqual(1); }); it('should recalculate when updated', function() { using('.doc-example-live li:first-child').input('item.points').enter('23'); expect(binding('items.$count(\'points==1\')')).toEqual(1); expect(binding('items.$count(\'points>1\')')).toEqual(2); }); </doc:scenario> </doc:example> */ 'count':function(array, condition) { if (!condition) return array.length; var fn = angular['Function']['compile'](condition), count = 0; forEach(array, function(value){ if (fn(value)) { count ++; } }); return count; }, /** * @ngdoc function * @name angular.Array.orderBy * @function * * @description * Orders `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator * - `string`: angular expression which evaluates to an object to order by, such as 'name' to * sort by a property called 'name'. Optionally prefixed with `+` or `-` to control ascending * or descending sort order (e.g. +name or -name). * - `Array`: array of function or string predicates, such that a first predicate in the array * is used for sorting, but when the items are equivalent next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <div ng:init="friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]"></div> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng:click="predicate=''">unsorted</a> ] <table ng:init="predicate='-age'"> <tr> <th><a href="" ng:click="predicate = 'name'; reverse=false">Name</a> (<a href ng:click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng:click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng:click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng:repeat="friend in friends.$orderBy(predicate, reverse)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('Sorting predicate = -age; reverse = '); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ 'orderBy':function(array, sortPredicate, reverseOrder) { if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = expressionCompile(predicate).fnSelf; } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }, /** * @ngdoc function * @name angular.Array.limitTo * @function * * @description * Creates a new array containing only the first, or last `limit` number of elements of the * source `array`. * * Note: this function is used to augment the `Array` type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the number is positive, the * first `limit` items from the source array will be copied, if the number is negative, the * last `limit` items will be copied. * @returns {Array} A new sub-array of length `limit`. * * @example <doc:example> <doc:source> <div ng:init="numbers = [1,2,3,4,5,6,7,8,9]"> Limit [1,2,3,4,5,6,7,8,9] to: <input name="limit" value="3"/> <p>Output: {{ numbers.$limitTo(limit) | json }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[name=limit]').val()).toBe('3'); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[7,8,9]'); }); </doc:scenario> </doc:example> */ limitTo: function(array, limit) { limit = parseInt(limit, 10); var out = [], i, n; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } }; var R_ISO8061_STR = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/; var angularString = { 'quote':function(string) { return '"' + string.replace(/\\/g, '\\\\'). replace(/"/g, '\\"'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/\t/g, '\\t'). replace(/\v/g, '\\v') + '"'; }, 'quoteUnicode':function(string) { var str = angular['String']['quote'](string); var chars = []; for ( var i = 0; i < str.length; i++) { var ch = str.charCodeAt(i); if (ch < 128) { chars.push(str.charAt(i)); } else { var encode = "000" + ch.toString(16); chars.push("\\u" + encode.substring(encode.length - 4)); } } return chars.join(''); }, /** * Tries to convert input to date and if successful returns the date, otherwise returns the input. * @param {string} string * @return {(Date|string)} */ 'toDate':function(string){ var match; if (isString(string) && (match = string.match(R_ISO8061_STR))){ var date = new Date(0); date.setUTCFullYear(match[1], match[2] - 1, match[3]); date.setUTCHours(match[4]||0, match[5]||0, match[6]||0, match[7]||0); return date; } return string; } }; var angularDate = { 'toString':function(date){ if (!date) return date; var isoString = date.toISOString ? date.toISOString() : ''; return (isoString.length==24) ? isoString : padNumber(date.getUTCFullYear(), 4) + '-' + padNumber(date.getUTCMonth() + 1, 2) + '-' + padNumber(date.getUTCDate(), 2) + 'T' + padNumber(date.getUTCHours(), 2) + ':' + padNumber(date.getUTCMinutes(), 2) + ':' + padNumber(date.getUTCSeconds(), 2) + '.' + padNumber(date.getUTCMilliseconds(), 3) + 'Z'; } }; var angularFunction = { 'compile':function(expression) { if (isFunction(expression)){ return expression; } else if (expression){ return expressionCompile(expression).fnSelf; } else { return identity; } } }; /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either call $hashKey function on object or assign unique hashKey id. * * @param obj * @returns {String} hash string such that the same input will have the same hash string */ function hashKey(obj) { var objType = typeof obj; var key = obj; if (objType == 'object') { if (typeof (key = obj.$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$hashKey(); } else if (key === undefined) { key = obj.$hashKey = nextUid(); } }; return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(){} HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type * @returns old value if any */ put: function(key, value) { var _key = hashKey(key); var oldValue = this[_key]; this[_key] = value; return oldValue; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key * @returns value associated with key before it was removed */ remove: function(key) { var _key = hashKey(key); var value = this[_key]; delete this[_key]; return value; } }; function defineApi(dst, chain){ angular[dst] = angular[dst] || {}; forEach(chain, function(parent){ extend(angular[dst], parent); }); } defineApi('Global', [angularGlobal]); defineApi('Collection', [angularGlobal, angularCollection]); defineApi('Array', [angularGlobal, angularCollection, angularArray]); defineApi('Object', [angularGlobal, angularCollection, angularObject]); defineApi('String', [angularGlobal, angularString]); defineApi('Date', [angularGlobal, angularDate]); //IE bug angular.Date.toString = angularDate.toString; defineApi('Function', [angularGlobal, angularCollection, angularFunction]); 'use strict'; /** * @workInProgress * @ngdoc overview * @name angular.filter * @description * * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * Following is the list of built-in angular filters: * * * {@link angular.filter.currency currency} * * {@link angular.filter.date date} * * {@link angular.filter.html html} * * {@link angular.filter.json json} * * {@link angular.filter.linky linky} * * {@link angular.filter.lowercase lowercase} * * {@link angular.filter.number number} * * {@link angular.filter.uppercase uppercase} * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @workInProgress * @ngdoc filter * @name angular.filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * @css ng-format-negative * When the value is negative, this css class is applied to the binding making it (by default) red. * * @example <doc:example> <doc:source> <input type="text" name="amount" value="1234.56"/> <br/> default currency symbol ($): {{amount | currency}}<br/> custom currency identifier (USD$): {{amount | currency:"USD$"}} </doc:source> <doc:scenario> it('should init with 1234.56', function(){ expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function(){ input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); expect(element('.doc-example-live .ng-binding').attr('className')). toMatch(/ng-format-negative/); }); </doc:scenario> </doc:example> */ angularFilter.currency = function(amount, currencySymbol){ this.$element.toggleClass('ng-format-negative', amount < 0); if (isUndefined(currencySymbol)) currencySymbol = NUMBER_FORMATS.CURRENCY_SYM; return formatNumber(amount, 2, 1).replace(/\u00A4/g, currencySymbol); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> Enter number: <input name='val' value='1234.56789' /><br/> Default formatting: {{val | number}}<br/> No fractions: {{val | number:0}}<br/> Negative number: {{-val | number:4}} </doc:source> <doc:scenario> it('should format numbers', function(){ expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function(){ input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ // PATTERNS[0] is an array for Decimal Pattern, PATTERNS[1] is an array Currency Pattern // Following is the order in each pattern array: // 0: minInteger, // 1: minFraction, // 2: maxFraction, // 3: positivePrefix, // 4: positiveSuffix, // 5: negativePrefix, // 6: negativeSuffix, // 7: groupSize, // 8: lastGroupSize var NUMBER_FORMATS = { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [[1, 0, 3, '', '', '-', '', 3, 3],[1, 2, 2, '\u00A4', '', '(\u00A4', ')', 3, 3]], CURRENCY_SYM: '$' }; var DECIMAL_SEP = '.'; angularFilter.number = function(number, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; return formatNumber(number, fractionSize, 0); }; function formatNumber(number, fractionSize, type) { var isNegative = number < 0, type = type || 0, // 0 is decimal pattern, 1 is currency pattern pattern = NUMBER_FORMATS.PATTERNS[type]; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; if (numStr.indexOf('e') !== -1) { var formatedText = numStr; } else { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; //determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern[1], fractionLen), pattern[2]); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern[8], group = pattern[7]; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += NUMBER_FORMATS.GROUP_SEP; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += NUMBER_FORMATS.GROUP_SEP; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize) formatedText += NUMBER_FORMATS.DECIMAL_SEP + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern[5] : pattern[3]); parts.push(formatedText); parts.push(isNegative ? pattern[6] : pattern[4]); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date) { var value = date['get' + name](); if(name == 'Month') { value = MONTH[value]; } else { value = DAY[value]; } return shortForm ? value.substr(0,3) : value; }; } function timeZoneGetter(numFormat) { return function(date) { var timeZone; if (numFormat || !(timeZone = GET_TIME_ZONE.exec(date.toString()))) { var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } return timeZone[0]; }; } var DAY = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','); var MONTH = 'January,February,March,April,May,June,July,August,September,October,November,December'. split(','); var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: function(date){return date.getHours() < 12 ? 'am' : 'pm';}, z: timeZoneGetter(false), Z: timeZoneGetter(true) }; var DEFAULT_DATETIME_FORMATS = { long: 'MMMM d, y h:mm:ss a z', medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', longTime: 'h:mm:ss a z', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }; var GET_TIME_ZONE = /[A-Z]{3}(?![+\-])/; var DATE_FORMATS_SPLIT = /([^yMdHhmsazZE]*)(E+|y+|M+|d+|H+|h+|m+|s+|a|Z|z)(.*)/; var OPERA_TOSTRING_PATTERN = /^[\d].*Z$/; var NUMBER_STRING = /^\d+$/; /** * @workInProgress * @ngdoc filter * @name angular.filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `'z'`: short form of current timezone name (e.g. PDT) * * `format` string can also be the following default formats for `en_US` locale (support for other * locales will be added in the future versions): * * * `'long'`: equivalent to `'MMMM d, y h:mm:ss a z'` for en_US locale * (e.g. September 3, 2010 12:05:08 pm PDT) * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'longTime'`: equivalent to `'h:mm:ss a z'` for en_US locale (e.g. 12:05:08 pm PDT) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ). * @param {string=} format Formatting rules (see Description). If not specified, * Date#toLocaleDateString is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng:non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/> </doc:source> <doc:scenario> it('should format date', function(){ expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (am|pm)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(am|pm)/); }); </doc:scenario> </doc:example> */ angularFilter.date = function(date, format) { format = DEFAULT_DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = parseInt(date, 10); } else { date = angularString.toDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } var text = date.toLocaleDateString(), fn; if (format && isString(format)) { text = ''; var parts = [], match; while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date) : value; }); } return text; }; /** * @workInProgress * @ngdoc filter * @name angular.filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * @css ng-monospace Always applied to the encapsulating element. * * @example: <doc:example> <doc:source> <input type="text" name="objTxt" value="{a:1, b:[]}" ng:eval="obj = $eval(objTxt)"/> <pre>{{ obj | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding('obj | json')).toBe('{\n "a":1,\n "b":[]}'); }); it('should update', function() { input('objTxt').enter('[1, 2, 3]'); expect(binding('obj | json')).toBe('[1,2,3]'); }); </doc:scenario> </doc:example> * */ angularFilter.json = function(object) { this.$element.addClass("ng-monospace"); return toJson(object, true); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.lowercase * @function * * @see angular.lowercase */ angularFilter.lowercase = lowercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.uppercase * @function * * @see angular.uppercase */ angularFilter.uppercase = uppercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.html * @function * * @description * Prevents the input from getting escaped by angular. By default the input is sanitized and * inserted into the DOM as is. * * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * If you hate your users, you may call the filter with optional 'unsafe' argument, which bypasses * the html sanitizer, but makes your application vulnerable to XSS and other attacks. Using this * option is strongly discouraged and should be used only if you absolutely trust the input being * filtered and you can't get the content through the sanitizer. * * @param {string} html Html input. * @param {string=} option If 'unsafe' then do not sanitize the HTML input. * @returns {string} Sanitized or raw html. * * @example <doc:example> <doc:source> Snippet: <textarea name="snippet" cols="60" rows="3"> &lt;p style="color:blue"&gt;an html &lt;em onmouseover="this.textContent='PWN3D!'"&gt;click here&lt;/em&gt; snippet&lt;/p&gt;</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng:bind="snippet | html"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | html"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng:bind="snippet | html:'unsafe'"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet | html:'unsafe'"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should sanitize the html snippet ', function(){ expect(using('#html-filter').binding('snippet | html')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should escape snippet without any filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function(){ input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet | html')).toBe('new <b>text</b>'); expect(using('#escaped-html').binding('snippet')).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).toBe('new <b>text</b>'); }); </doc:scenario> </doc:example> */ angularFilter.html = function(html, option){ return new HTML(html, option); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * @param {string} text Input text. * @returns {string} Html-linkified text. * * @example <doc:example> <doc:source> Snippet: <textarea name="snippet" cols="60" rows="3"> Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, another@somewhere.org, and one more: ftp://127.0.0.1/.</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng:bind="snippet | linky"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | linky"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should linkify the snippet with urls', function(){ expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:\n' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,\n' + '<a href="mailto:us@somewhere.org">us@somewhere.org</a>,\n' + '<a href="mailto:another@somewhere.org">another@somewhere.org</a>,\n' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:us@somewhere.org,\n" + "another@somewhere.org,\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function(){ input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); </doc:scenario> </doc:example> */ //TODO: externalize all regexps angularFilter.linky = function(text){ if (!text) return text; var URL = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/; var match; var raw = text; var html = []; var writer = htmlSanitizeWriter(html); var url; var i; while (match=raw.match(URL)) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2]==match[3]) url = 'mailto:' + url; i = match.index; writer.chars(raw.substr(0, i)); writer.start('a', {href:url}); writer.chars(match[0].replace(/^mailto:/, '')); writer.end('a'); raw = raw.substring(i + match[0].length); } writer.chars(raw); return new HTML(html.join('')); }; 'use strict'; /** * @workInProgress * @ngdoc overview * @name angular.formatter * @description * * Formatters are used for translating data formats between those used for display and those used * for storage. * * Following is the list of built-in angular formatters: * * * {@link angular.formatter.boolean boolean} - Formats user input in boolean format * * {@link angular.formatter.json json} - Formats user input in JSON format * * {@link angular.formatter.list list} - Formats user input string as an array * * {@link angular.formatter.number number} - Formats user input strings as a number * * {@link angular.formatter.trim trim} - Trims extras spaces from end of user input * * For more information about how angular formatters work, and how to create your own formatters, * see {@link guide/dev_guide.templates.formatters Understanding Angular Formatters} in the angular * Developer Guide. */ function formatter(format, parse) {return {'format':format, 'parse':parse || format};} function toString(obj) { return (isDefined(obj) && obj !== null) ? "" + obj : obj; } var NUMBER = /^\s*[-+]?\d*(\.\d*)?\s*$/; angularFormatter.noop = formatter(identity, identity); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.json * * @description * Formats the user input as JSON text. * * @returns {?string} A JSON string representation of the model. * * @example <doc:example> <doc:source> <div ng:init="data={name:'misko', project:'angular'}"> <input type="text" size='50' name="data" ng:format="json"/> <pre>data={{data}}</pre> </div> </doc:source> <doc:scenario> it('should format json', function(){ expect(binding('data')).toEqual('data={\n \"name\":\"misko\",\n \"project\":\"angular\"}'); input('data').enter('{}'); expect(binding('data')).toEqual('data={\n }'); }); </doc:scenario> </doc:example> */ angularFormatter.json = formatter(toJson, function(value){ return fromJson(value || 'null'); }); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.boolean * * @description * Use boolean formatter if you wish to store the data as boolean. * * @returns {boolean} Converts to `true` unless user enters (blank), `f`, `false`, `0`, `no`, `[]`. * * @example <doc:example> <doc:source> Enter truthy text: <input type="text" name="value" ng:format="boolean" value="no"/> <input type="checkbox" name="value"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format boolean', function(){ expect(binding('value')).toEqual('value=false'); input('value').enter('truthy'); expect(binding('value')).toEqual('value=true'); }); </doc:scenario> </doc:example> */ angularFormatter['boolean'] = formatter(toString, toBoolean); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.number * * @description * Use number formatter if you wish to convert the user entered string to a number. * * @returns {number} Number from the parsed string. * * @example <doc:example> <doc:source> Enter valid number: <input type="text" name="value" ng:format="number" value="1234"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format numbers', function(){ expect(binding('value')).toEqual('value=1234'); input('value').enter('5678'); expect(binding('value')).toEqual('value=5678'); }); </doc:scenario> </doc:example> */ angularFormatter.number = formatter(toString, function(obj){ if (obj == null || NUMBER.exec(obj)) { return obj===null || obj === '' ? null : 1*obj; } else { throw "Not a number"; } }); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.list * * @description * Use list formatter if you wish to convert the user entered string to an array. * * @returns {Array} Array parsed from the entered string. * * @example <doc:example> <doc:source> Enter a list of items: <input type="text" name="value" ng:format="list" value=" chair ,, table"/> <input type="text" name="value" ng:format="list"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format lists', function(){ expect(binding('value')).toEqual('value=["chair","table"]'); this.addFutureAction('change to XYZ', function($window, $document, done){ $document.elements('.doc-example-live :input:last').val(',,a,b,').trigger('change'); done(); }); expect(binding('value')).toEqual('value=["a","b"]'); }); </doc:scenario> </doc:example> */ angularFormatter.list = formatter( function(obj) { return obj ? obj.join(", ") : obj; }, function(value) { var list = []; forEach((value || '').split(','), function(item){ item = trim(item); if (item) list.push(item); }); return list; } ); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.trim * * @description * Use trim formatter if you wish to trim extra spaces in user text. * * @returns {String} Trim excess leading and trailing space. * * @example <doc:example> <doc:source> Enter text with leading/trailing spaces: <input type="text" name="value" ng:format="trim" value=" book "/> <input type="text" name="value" ng:format="trim"/> <pre>value={{value|json}}</pre> </doc:source> <doc:scenario> it('should format trim', function(){ expect(binding('value')).toEqual('value="book"'); this.addFutureAction('change to XYZ', function($window, $document, done){ $document.elements('.doc-example-live :input:last').val(' text ').trigger('change'); done(); }); expect(binding('value')).toEqual('value="text"'); }); </doc:scenario> </doc:example> */ angularFormatter.trim = formatter( function(obj) { return obj ? trim("" + obj) : ""; } ); 'use strict'; /** * @workInProgress * @ngdoc overview * @name angular.validator * @description * * Most of the built-in angular validators are used to check user input against defined types or * patterns. You can easily create your own custom validators as well. * * Following is the list of built-in angular validators: * * * {@link angular.validator.asynchronous asynchronous()} - Provides asynchronous validation via a * callback function. * * {@link angular.validator.date date()} - Checks user input against default date format: * "MM/DD/YYYY" * * {@link angular.validator.email email()} - Validates that user input is a well-formed email * address. * * {@link angular.validator.integer integer()} - Validates that user input is an integer * * {@link angular.validator.json json()} - Validates that user input is valid JSON * * {@link angular.validator.number number()} - Validates that user input is a number * * {@link angular.validator.phone phone()} - Validates that user input matches the pattern * "1(123)123-1234" * * {@link angular.validator.regexp regexp()} - Restricts valid input to a specified regular * expression pattern * * {@link angular.validator.url url()} - Validates that user input is a well-formed URL. * * For more information about how angular validators work, and how to create your own validators, * see {@link guide/dev_guide.templates.validators Understanding Angular Validators} in the angular * Developer Guide. */ extend(angularValidator, { 'noop': function() { return null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.regexp * @description * Use regexp validator to restrict the input to any Regular Expression. * * @param {string} value value to validate * @param {string|regexp} expression regular expression. * @param {string=} msg error message to display. * @css ng-validation-error * * @example <doc:example> <doc:source> <script> function Cntl(){ this.ssnRegExp = /^\d\d\d-\d\d-\d\d\d\d$/; } </script> Enter valid SSN: <div ng:controller="Cntl"> <input name="ssn" value="123-45-6789" ng:validate="regexp:ssnRegExp" > </div> </doc:source> <doc:scenario> it('should invalidate non ssn', function(){ var textBox = element('.doc-example-live :input'); expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); expect(textBox.val()).toEqual('123-45-6789'); input('ssn').enter('123-45-67890'); expect(textBox.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'regexp': function(value, regexp, msg) { if (!value.match(regexp)) { return msg || "Value does not match expected format " + regexp + "."; } else { return null; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.number * @description * Use number validator to restrict the input to numbers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example <doc:example> <doc:source> Enter number: <input name="n1" ng:validate="number" > <br> Enter number greater than 10: <input name="n2" ng:validate="number:10" > <br> Enter number between 100 and 200: <input name="n3" ng:validate="number:100:200" > <br> </doc:source> <doc:scenario> it('should invalidate number', function(){ var n1 = element('.doc-example-live :input[name=n1]'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('n1').enter('1.x'); expect(n1.attr('className')).toMatch(/ng-validation-error/); var n2 = element('.doc-example-live :input[name=n2]'); expect(n2.attr('className')).not().toMatch(/ng-validation-error/); input('n2').enter('9'); expect(n2.attr('className')).toMatch(/ng-validation-error/); var n3 = element('.doc-example-live :input[name=n3]'); expect(n3.attr('className')).not().toMatch(/ng-validation-error/); input('n3').enter('201'); expect(n3.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'number': function(value, min, max) { var num = 1 * value; if (num == value) { if (typeof min != $undefined && num < min) { return "Value can not be less than " + min + "."; } if (typeof min != $undefined && num > max) { return "Value can not be greater than " + max + "."; } return null; } else { return "Not a number"; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.integer * @description * Use number validator to restrict the input to integers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example <doc:example> <doc:source> Enter integer: <input name="n1" ng:validate="integer" > <br> Enter integer equal or greater than 10: <input name="n2" ng:validate="integer:10" > <br> Enter integer between 100 and 200 (inclusive): <input name="n3" ng:validate="integer:100:200" > <br> </doc:source> <doc:scenario> it('should invalidate integer', function(){ var n1 = element('.doc-example-live :input[name=n1]'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('n1').enter('1.1'); expect(n1.attr('className')).toMatch(/ng-validation-error/); var n2 = element('.doc-example-live :input[name=n2]'); expect(n2.attr('className')).not().toMatch(/ng-validation-error/); input('n2').enter('10.1'); expect(n2.attr('className')).toMatch(/ng-validation-error/); var n3 = element('.doc-example-live :input[name=n3]'); expect(n3.attr('className')).not().toMatch(/ng-validation-error/); input('n3').enter('100.1'); expect(n3.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ 'integer': function(value, min, max) { var numberError = angularValidator['number'](value, min, max); if (numberError) return numberError; if (!("" + value).match(/^\s*[\d+]*\s*$/) || value != Math.round(value)) { return "Not a whole number"; } return null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.date * @description * Use date validator to restrict the user input to a valid date * in format in format MM/DD/YYYY. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid date: <input name="text" value="1/1/2009" ng:validate="date" > </doc:source> <doc:scenario> it('should invalidate date', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('123/123/123'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'date': function(value) { var fields = /^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(value); var date = fields ? new Date(fields[3], fields[1]-1, fields[2]) : 0; return (date && date.getFullYear() == fields[3] && date.getMonth() == fields[1]-1 && date.getDate() == fields[2]) ? null : "Value is not a date. (Expecting format: 12/31/2009)."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.email * @description * Use email validator if you wist to restrict the user input to a valid email. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid email: <input name="text" ng:validate="email" value="me@example.com"> </doc:source> <doc:scenario> it('should invalidate email', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('a@b.c'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'email': function(value) { if (value.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)) { return null; } return "Email needs to be in username@host.com format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.phone * @description * Use phone validator to restrict the input phone numbers. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid phone number: <input name="text" value="1(234)567-8901" ng:validate="phone" > </doc:source> <doc:scenario> it('should invalidate phone', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('+12345678'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'phone': function(value) { if (value.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)) { return null; } if (value.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)) { return null; } return "Phone number needs to be in 1(987)654-3210 format in North America " + "or +999 (123) 45678 906 internationally."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.url * @description * Use phone validator to restrict the input URLs. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid URL: <input name="text" value="http://example.com/abc.html" size="40" ng:validate="url" > </doc:source> <doc:scenario> it('should invalidate url', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('abc://server/path'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'url': function(value) { if (value.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)) { return null; } return "URL needs to be in http://server[:port]/path format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.json * @description * Use json validator if you wish to restrict the user input to a valid JSON. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> <textarea name="json" cols="60" rows="5" ng:validate="json"> {name:'abc'} </textarea> </doc:source> <doc:scenario> it('should invalidate json', function(){ var n1 = element('.doc-example-live :input'); expect(n1.attr('className')).not().toMatch(/ng-validation-error/); input('json').enter('{name}'); expect(n1.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'json': function(value) { try { fromJson(value); return null; } catch (e) { return e.toString(); } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.asynchronous * @description * Use asynchronous validator if the validation can not be computed * immediately, but is provided through a callback. The widget * automatically shows a spinning indicator while the validity of * the widget is computed. This validator caches the result. * * @param {string} value value to validate * @param {function(inputToValidate,validationDone)} validate function to call to validate the state * of the input. * @param {function(data)=} [update=noop] function to call when state of the * validator changes * * @paramDescription * The `validate` function (specified by you) is called as * `validate(inputToValidate, validationDone)`: * * * `inputToValidate`: value of the input box. * * `validationDone`: `function(error, data){...}` * * `error`: error text to display if validation fails * * `data`: data object to pass to update function * * The `update` function is optionally specified by you and is * called by <angular/> on input change. Since the * asynchronous validator caches the results, the update * function can be called without a call to `validate` * function. The function is called as `update(data)`: * * * `data`: data object as passed from validate function * * @css ng-input-indicator-wait, ng-validation-error * * @example <doc:example> <doc:source> <script> function MyCntl(){ this.myValidator = function (inputToValidate, validationDone) { setTimeout(function(){ validationDone(inputToValidate.length % 2); }, 500); } } </script> This input is validated asynchronously: <div ng:controller="MyCntl"> <input name="text" ng:validate="asynchronous:myValidator"> </div> </doc:source> <doc:scenario> it('should change color in delayed way', function(){ var textBox = element('.doc-example-live :input'); expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); input('text').enter('X'); expect(textBox.attr('className')).toMatch(/ng-input-indicator-wait/); sleep(.6); expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); expect(textBox.attr('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ /* * cache is attached to the element * cache: { * inputs : { * 'user input': { * response: server response, * error: validation error * }, * current: 'current input' * } * } * */ 'asynchronous': function(input, asynchronousFn, updateFn) { if (!input) return; var scope = this; var element = scope.$element; var cache = element.data('$asyncValidator'); if (!cache) { element.data('$asyncValidator', cache = {inputs:{}}); } cache.current = input; var inputState = cache.inputs[input], $invalidWidgets = scope.$service('$invalidWidgets'); if (!inputState) { cache.inputs[input] = inputState = { inFlight: true }; $invalidWidgets.markInvalid(scope.$element); element.addClass('ng-input-indicator-wait'); asynchronousFn(input, function(error, data) { inputState.response = data; inputState.error = error; inputState.inFlight = false; if (cache.current == input) { element.removeClass('ng-input-indicator-wait'); $invalidWidgets.markValid(element); } element.data($$validate)(); scope.$service('$updateView')(); }); } else if (inputState.inFlight) { // request in flight, mark widget invalid, but don't show it to user $invalidWidgets.markInvalid(scope.$element); } else { (updateFn||noop)(inputState.response); } return inputState.error; } }); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ angularServiceInject('$cookieStore', function($store) { return { /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#get * @methodOf angular.service.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return fromJson($store[key]); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#put * @methodOf angular.service.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $store[key] = toJson(value); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#remove * @methodOf angular.service.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $store[key]; } }; }, ['$cookies']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example */ angularServiceInject('$cookies', function($browser) { var rootScope = this, cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) rootScope.$eval(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. this.$onEval(PRIORITY_LAST, push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push(){ var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!isString(value)) { if (isDefined(lastCookies[name])) { cookies[name] = lastCookies[name]; } else { delete cookies[name]; } } else if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }, ['$browser']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$defer * @requires $browser * @requires $exceptionHandler * @requires $updateView * * @description * Delegates to {@link angular.service.$browser $browser.defer}, but wraps the `fn` function * into a try/catch block and delegates any exceptions to * {@link angular.service.$exceptionHandler $exceptionHandler} service. * * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. */ angularServiceInject('$defer', function($browser, $exceptionHandler, $updateView) { return function(fn, delay) { $browser.defer(function() { try { fn(); } catch(e) { $exceptionHandler(e); } finally { $updateView(); } }, delay); }; }, ['$browser', '$exceptionHandler', '$updateView']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ angularServiceInject("$document", function(window){ return jqLite(window.document); }, ['$window']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overriden by * {@link angular.mock.service.$exceptionHandler mock $exceptionHandler} * * @example */ var $exceptionHandlerFactory; //reference to be used only in tests angularServiceInject('$exceptionHandler', $exceptionHandlerFactory = function($log){ return function(e) { $log.error(e); }; }, ['$log']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$hover * @requires $browser * @requires $document * * @description * * @example */ angularServiceInject("$hover", function(browser, document) { var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body); browser.hover(function(element, show){ if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) { if (!tooltip) { tooltip = { callout: jqLite('<div id="ng-callout"></div>'), arrow: jqLite('<div></div>'), title: jqLite('<div class="ng-title"></div>'), content: jqLite('<div class="ng-content"></div>') }; tooltip.callout.append(tooltip.arrow); tooltip.callout.append(tooltip.title); tooltip.callout.append(tooltip.content); body.append(tooltip.callout); } var docRect = body[0].getBoundingClientRect(), elementRect = element[0].getBoundingClientRect(), leftSpace = docRect.right - elementRect.right - arrowWidth; tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."); tooltip.content.text(error); if (leftSpace < width) { tooltip.arrow.addClass('ng-arrow-right'); tooltip.arrow.css({left: (width + 1)+'px'}); tooltip.callout.css({ position: 'fixed', left: (elementRect.left - arrowWidth - width - 4) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } else { tooltip.arrow.addClass('ng-arrow-left'); tooltip.callout.css({ position: 'fixed', left: (elementRect.right + arrowWidth) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } } else if (tooltip) { tooltip.callout.remove(); tooltip = null; } }); }, ['$browser', '$document'], true); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$invalidWidgets * * @description * Keeps references to all invalid widgets found during validation. * Can be queried to find whether there are any invalid widgets currently displayed. * * @example */ angularServiceInject("$invalidWidgets", function(){ var invalidWidgets = []; /** Remove an element from the array of invalid widgets */ invalidWidgets.markValid = function(element){ var index = indexOf(invalidWidgets, element); if (index != -1) invalidWidgets.splice(index, 1); }; /** Add an element to the array of invalid widgets */ invalidWidgets.markInvalid = function(element){ var index = indexOf(invalidWidgets, element); if (index === -1) invalidWidgets.push(element); }; /** Return count of all invalid widgets that are currently visible */ invalidWidgets.visible = function() { var count = 0; forEach(invalidWidgets, function(widget){ count = count + (isVisible(widget) ? 1 : 0); }); return count; }; /* At the end of each eval removes all invalid widgets that are not part of the current DOM. */ this.$onEval(PRIORITY_LAST, function() { for(var i = 0; i < invalidWidgets.length;) { var widget = invalidWidgets[i]; if (isOrphan(widget[0])) { invalidWidgets.splice(i, 1); if (widget.dealoc) widget.dealoc(); } else { i++; } } }); /** * Traverses DOM element's (widget's) parents and considers the element to be an orphant if one of * it's parents isn't the current window.document. */ function isOrphan(widget) { if (widget == window.document) return false; var parent = widget.parentNode; return !parent || isOrphan(parent); } return invalidWidgets; }); 'use strict'; var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = /^([^\?]*)?(\?([^\?]*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp':21}; /** * @workInProgress * @ngdoc service * @name angular.service.$location * @requires $browser * * @property {string} href The full URL of the current location. * @property {string} protocol The protocol part of the URL (e.g. http or https). * @property {string} host The host name, ip address or FQDN of the current location. * @property {number} port The port number of the current location (e.g. 80, 443, 8080). * @property {string} path The path of the current location (e.g. /myapp/inbox). * @property {Object.<string|boolean>} search Map of query parameters (e.g. {user:"foo", page:23}). * @property {string} hash The fragment part of the URL of the current location (e.g. #foo). * @property {string} hashPath Similar to `path`, but located in the `hash` fragment * (e.g. ../foo#/some/path => /some/path). * @property {Object.<string|boolean>} hashSearch Similar to `search` but located in `hash` * fragment (e.g. .../foo#/some/path?hashQuery=param => {hashQuery: "param"}). * * @description * Parses the browser location url and makes it available to your application. * Any changes to the url are reflected into `$location` service and changes to * `$location` are reflected in the browser location url. * * Notice that using browser's forward/back buttons changes the $location. * * @example <doc:example> <doc:source> <div ng:init="$location = $service('$location')"> <a id="ex-test" href="#myPath?name=misko">test hash</a>| <a id="ex-reset" href="#!/api/angular.service.$location">reset hash</a><br/> <input type='text' name="$location.hash" size="30"> <pre>$location = {{$location}}</pre> </div> </doc:source> <doc:scenario> it('should initialize the input field', function() { expect(using('.doc-example-live').input('$location.hash').val()). toBe('!/api/angular.service.$location'); }); it('should bind $location.hash to the input field', function() { using('.doc-example-live').input('$location.hash').enter('foo'); expect(browser().location().hash()).toBe('foo'); }); it('should set the hash to a test string with test link is presed', function() { using('.doc-example-live').element('#ex-test').click(); expect(using('.doc-example-live').input('$location.hash').val()). toBe('myPath?name=misko'); }); it('should reset $location when reset link is pressed', function() { using('.doc-example-live').input('$location.hash').enter('foo'); using('.doc-example-live').element('#ex-reset').click(); expect(using('.doc-example-live').input('$location.hash').val()). toBe('!/api/angular.service.$location'); }); </doc:scenario> </doc:example> */ angularServiceInject("$location", function($browser) { var scope = this, location = {update:update, updateHash: updateHash}, lastLocation = {}; $browser.onHashChange(function() { //register update($browser.getUrl()); copy(location, lastLocation); scope.$eval(); })(); //initialize this.$onEval(PRIORITY_FIRST, sync); this.$onEval(PRIORITY_LAST, updateBrowser); return location; // PUBLIC METHODS /** * @workInProgress * @ngdoc method * @name angular.service.$location#update * @methodOf angular.service.$location * * @description * Updates the location object. * * Does not immediately update the browser. Instead the browser is updated at the end of $eval() * cycle. * * <pre> $location.update('http://www.angularjs.org/path#hash?search=x'); $location.update({host: 'www.google.com', protocol: 'https'}); $location.update({hashPath: '/path', hashSearch: {a: 'b', x: true}}); </pre> * * @param {string|Object} href Full href as a string or object with properties */ function update(href) { if (isString(href)) { extend(location, parseHref(href)); } else { if (isDefined(href.hash)) { extend(href, isString(href.hash) ? parseHash(href.hash) : href.hash); } extend(location, href); if (isDefined(href.hashPath || href.hashSearch)) { location.hash = composeHash(location); } location.href = composeHref(location); } } /** * @workInProgress * @ngdoc method * @name angular.service.$location#updateHash * @methodOf angular.service.$location * * @description * Updates the hash fragment part of the url. * * @see update() * * <pre> scope.$location.updateHash('/hp') ==> update({hashPath: '/hp'}) scope.$location.updateHash({a: true, b: 'val'}) ==> update({hashSearch: {a: true, b: 'val'}}) scope.$location.updateHash('/hp', {a: true}) ==> update({hashPath: '/hp', hashSearch: {a: true}}) </pre> * * @param {string|Object} path A hashPath or hashSearch object * @param {Object=} search A hashSearch object */ function updateHash(path, search) { var hash = {}; if (isString(path)) { hash.hashPath = path; hash.hashSearch = search || {}; } else hash.hashSearch = path; hash.hash = composeHash(hash); update({hash: hash}); } // INNER METHODS /** * Synchronizes all location object properties. * * User is allowed to change properties, so after property change, * location object is not in consistent state. * * Properties are synced with the following precedence order: * * - `$location.href` * - `$location.hash` * - everything else * * Keep in mind that if the following code is executed: * * scope.$location.href = 'http://www.angularjs.org/path#a/b' * * immediately afterwards all other properties are still the old ones... * * This method checks the changes and update location to the consistent state */ function sync() { if (!equals(location, lastLocation)) { if (location.href != lastLocation.href) { update(location.href); return; } if (location.hash != lastLocation.hash) { var hash = parseHash(location.hash); updateHash(hash.hashPath, hash.hashSearch); } else { location.hash = composeHash(location); location.href = composeHref(location); } update(location.href); } } /** * If location has changed, update the browser * This method is called at the end of $eval() phase */ function updateBrowser() { sync(); if ($browser.getUrl() != location.href) { $browser.setUrl(location.href); copy(location, lastLocation); } } /** * Compose href string from a location object * * @param {Object} loc The location object with all properties * @return {string} Composed href */ function composeHref(loc) { var url = toKeyValue(loc.search); var port = (loc.port == DEFAULT_PORTS[loc.protocol] ? null : loc.port); return loc.protocol + '://' + loc.host + (port ? ':' + port : '') + loc.path + (url ? '?' + url : '') + (loc.hash ? '#' + loc.hash : ''); } /** * Compose hash string from location object * * @param {Object} loc Object with hashPath and hashSearch properties * @return {string} Hash string */ function composeHash(loc) { var hashSearch = toKeyValue(loc.hashSearch); //TODO: temporary fix for issue #158 return escape(loc.hashPath).replace(/%21/gi, '!').replace(/%3A/gi, ':').replace(/%24/gi, '$') + (hashSearch ? '?' + hashSearch : ''); } /** * Parse href string into location object * * @param {string} href * @return {Object} The location object */ function parseHref(href) { var loc = {}; var match = URL_MATCH.exec(href); if (match) { loc.href = href.replace(/#$/, ''); loc.protocol = match[1]; loc.host = match[3] || ''; loc.port = match[5] || DEFAULT_PORTS[loc.protocol] || null; loc.path = match[6] || ''; loc.search = parseKeyValue(match[8]); loc.hash = match[10] || ''; extend(loc, parseHash(loc.hash)); } return loc; } /** * Parse hash string into object * * @param {string} hash */ function parseHash(hash) { var h = {}; var match = HASH_MATCH.exec(hash); if (match) { h.hash = hash; h.hashPath = unescape(match[1] || ''); h.hashSearch = parseKeyValue(match[3]); } return h; } }, ['$browser']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <doc:example> <doc:source> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" name="message" value="Hello World!"/> <button ng:click="$log.log(message)">log</button> <button ng:click="$log.warn(message)">warn</button> <button ng:click="$log.info(message)">info</button> <button ng:click="$log.error(message)">error</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ var $logFactory; //reference to be used only in tests angularServiceInject("$log", $logFactory = function($window){ return { /** * @workInProgress * @ngdoc method * @name angular.service.$log#log * @methodOf angular.service.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#warn * @methodOf angular.service.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#info * @methodOf angular.service.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#error * @methodOf angular.service.$log * * @description * Write an error message */ error: consoleLog('error') }; function consoleLog(type) { var console = $window.console || {}; var logFn = console[type] || console.log || noop; if (logFn.apply) { return function(){ var args = []; forEach(arguments, function(arg){ args.push(formatError(arg)); }); return logFn.apply(console, args); }; } else { // we are IE, in which case there is nothing we can do return logFn; } } }, ['$window']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$resource * @requires $xhr.cache * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link angular.service.$xhr $xhr} service or * raw XMLHttpRequest. * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the following format: * * {action1: {method:?, params:?, isArray:?, verifyCache:?}, * action2: {method:?, params:?, isArray:?, verifyCache:?}, * ...} * * Where: * * - `action` – {string} – The name of action. This name becomes the name of the method on your * resource object. * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSON` (also known as JSONP). * - `params` – {object=} – Optional set of pre-bound parameters for this action. * - isArray – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * - verifyCache – {boolean=} – If true then whenever cache hit occurs, the object is returned and * an async request will be made to the server and the resources as well as the cache will be * updated when the response is received. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link angular.service.$xhr} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class `save`, `remove` and `delete` actions are available on it as * methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read, * update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function(){ user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` * - non-GET "class" actions: `Resource.action(postData, [parameters], [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(); // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$xhr` on the `url` template with the given `method` and `params`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function(){ user.abc = true; user.$save(); }); </pre> * * It's worth noting that the success callback for `get`, `query` and other method gets passed * in the response that came from the server, so one could rewrite the above example as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u, responseHeaders){ u.abc = true; u.$save(function(u, responseHeaders) { // Get an Object containing all response headers var allHeaders = responseHeaders(); // Get a specific response header u.newId = responseHeaders('Location'); }); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source jsfiddle="false"> <script> function BuzzController($resource) { this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSON', params:{visibility:'@self'}}, replies: {method:'JSON', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng:controller="BuzzController"> <input name="userId" value="googlebuzz"/> <button ng:click="fetch()">fetch</button> <hr/> <div ng:repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng:click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng:repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$resource', function($xhr){ var resource = new ResourceFactory($xhr); return bind(resource, resource.route); }, ['$xhr.cache']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$route * @requires $location * * @property {Object} current Reference to the current route definition. * @property {Array.<Object>} routes Array of all configured routes. * * @description * Watches `$location.hashPath` and tries to map the hash to an existing route * definition. It is used for deep-linking URLs to controllers and views (HTML partials). * * The `$route` service is typically used in conjunction with {@link angular.widget.ng:view ng:view} * widget. * * @example This example shows how changing the URL hash causes the <tt>$route</tt> to match a route against the URL, and the <tt>[[ng:include]]</tt> pulls in the partial. Try changing the URL in the input box to see changes. <doc:example> <doc:source jsfiddle="false"> <script> function MainCntl($route, $location) { this.$route = $route; this.$location = $location; $route.when('/Book/:bookId', {template: 'examples/book.html', controller: BookCntl}); $route.when('/Book/:bookId/ch/:chapterId', {template: 'examples/chapter.html', controller: ChapterCntl}); $route.onChange(function() { $route.current.scope.params = $route.current.params; }); } function BookCntl() { this.name = "BookCntl"; } function ChapterCntl() { this.name = "ChapterCntl"; } </script> <div ng:controller="MainCntl"> Choose: <a href="#/Book/Moby">Moby</a> | <a href="#/Book/Moby/ch/1">Moby: Ch1</a> | <a href="#/Book/Gatsby">Gatsby</a> | <a href="#/Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a><br/> $location.hashPath: <input type="text" name="$location.hashPath" size="80" /> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <hr /> <ng:view></ng:view> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$route', function(location, $updateView) { var routes = {}, onChange = [], matcher = switchRouteMatcher, parentScope = this, dirty = 0, lastHashPath, lastRouteParams, $route = { routes: routes, /** * @workInProgress * @ngdoc method * @name angular.service.$route#onChange * @methodOf angular.service.$route * * @param {function()} fn Function that will be called when `$route.current` changes. * @returns {function()} The registered function. * * @description * Register a handler function that will be called when route changes */ onChange: function(fn) { onChange.push(fn); return fn; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#parent * @methodOf angular.service.$route * * @param {Scope} [scope=rootScope] Scope to be used as parent for newly created * `$route.current.scope` scopes. * * @description * Sets a scope to be used as the parent scope for scopes created on route change. If not * set, defaults to the root scope. */ parent: function(scope) { if (scope) parentScope = scope; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#when * @methodOf angular.service.$route * * @param {string} path Route path (matched against `$location.hash`) * @param {Object} params Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{function()=}` – Controller fn that should be associated with newly * created scope. * - `template` – `{string=}` – path to an html template that should be used by * {@link angular.widget.ng:view ng:view} or * {@link angular.widget.ng:include ng:include} widgets. * - `redirectTo` – {(string|function())=} – value to update * {@link angular.service.$location $location} hash with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.hashPath` by applying the current route template. * - `{string}` - current `$location.hash` * - `{string}` - current `$location.hashPath` * - `{string}` - current `$location.hashSearch` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.hash`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when $location.hashSearch * changes. If this option is disabled, you should set up a $watch to be notified of * param (hashSearch) changes as follows: * * function MyCtrl($route) { * this.$watch(function() { * return $route.current.params.myHashSearchParam; * }, function(params) { * //do stuff with params * }); * } * * @returns {Object} route object * * @description * Adds a new route definition to the `$route` service. */ when:function (path, params) { if (isUndefined(path)) return routes; //TODO(im): remove - not needed! var route = routes[path]; if (!route) route = routes[path] = {reloadOnSearch: true}; if (params) extend(route, params); //TODO(im): what the heck? merge two route definitions? dirty++; return route; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#otherwise * @methodOf angular.service.$route * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. */ otherwise: function(params) { $route.when(null, params); }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#reload * @methodOf angular.service.$route * * @description * Causes `$route` service to reload (and recreate the `$route.current` scope) upon the next * eval even if {@link angular.service.$location $location} hasn't changed. */ reload: function() { dirty++; } }; function switchRouteMatcher(on, when, dstName) { var regex = '^' + when.replace(/[\.\\\(\)\^\$]/g, "\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param){ if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index){ dst[name] = match[index + 1]; }); if (dstName) this.$set(dstName, dst); } return match ? dst : null; } function updateRoute(){ var childScope, routeParams, pathParams, segmentMatch, key, redir; if ($route.current) { if (!$route.current.reloadOnSearch && (lastHashPath == location.hashPath)) { $route.current.params = extend({}, location.hashSearch, lastRouteParams); return; } } lastHashPath = location.hashPath; $route.current = null; forEach(routes, function(rParams, rPath) { if (!pathParams) { if (pathParams = matcher(location.hashPath, rPath)) { routeParams = rParams; } } }); // "otherwise" fallback routeParams = routeParams || routes[null]; if(routeParams) { if (routeParams.redirectTo) { if (isString(routeParams.redirectTo)) { // interpolate the redirectTo string redir = {hashPath: '', hashSearch: extend({}, location.hashSearch, pathParams)}; forEach(routeParams.redirectTo.split(':'), function(segment, i) { if (i==0) { redir.hashPath += segment; } else { segmentMatch = segment.match(/(\w+)(.*)/); key = segmentMatch[1]; redir.hashPath += pathParams[key] || location.hashSearch[key]; redir.hashPath += segmentMatch[2] || ''; delete redir.hashSearch[key]; } }); } else { // call custom redirectTo function redir = {hash: routeParams.redirectTo(pathParams, location.hash, location.hashPath, location.hashSearch)}; } location.update(redir); $updateView(); //TODO this is to work around the $location<=>$browser issues return; } childScope = createScope(parentScope); $route.current = extend({}, routeParams, { scope: childScope, params: extend({}, location.hashSearch, pathParams) }); lastRouteParams = pathParams; } //fire onChange callbacks forEach(onChange, parentScope.$tryEval); if (childScope) { childScope.$become($route.current.controller); } } this.$watch(function(){ return dirty + location.hash; }, updateRoute); return $route; }, ['$location', '$updateView']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$updateView * @requires $browser * * @description * Calling `$updateView` enqueues the eventual update of the view. (Update the DOM to reflect the * model). The update is eventual, since there are often multiple updates to the model which may * be deferred. The default update delayed is 25 ms. This means that the view lags the model by * that time. (25ms is small enough that it is perceived as instantaneous by the user). The delay * can be adjusted by setting the delay property of the service. * * <pre>angular.service('$updateView').delay = 10</pre> * * The delay is there so that multiple updates to the model which occur sufficiently close * together can be merged into a single update. * * You don't usually call '$updateView' directly since angular does it for you in most cases, * but there are some cases when you need to call it. * * - `$updateView()` called automatically by angular: * - Your Application Controllers: Your controller code is called by angular and hence * angular is aware that you may have changed the model. * - Your Services: Your service is usually called by your controller code, hence same rules * apply. * - May need to call `$updateView()` manually: * - Widgets / Directives: If you listen to any DOM events or events on any third party * libraries, then angular is not aware that you may have changed state state of the * model, and hence you need to call '$updateView()' manually. * - 'setTimeout'/'XHR': If you call 'setTimeout' (instead of {@link angular.service.$defer}) * or 'XHR' (instead of {@link angular.service.$xhr}) then you may be changing the model * without angular knowledge and you may need to call '$updateView()' directly. * * Note: if you wish to update the view immediately (without delay), you can do so by calling * {@link angular.scope.$eval} at any time from your code: * <pre>scope.$root.$eval()</pre> * * In unit-test mode the update is instantaneous and synchronous to simplify writing tests. * */ function serviceUpdateViewFactory($browser){ var rootScope = this; var scheduled; function update(){ scheduled = false; rootScope.$eval(); } return $browser.isMock ? update : function(){ if (!scheduled) { scheduled = true; $browser.defer(update, serviceUpdateViewFactory.delay); } }; } serviceUpdateViewFactory.delay = 25; angularServiceInject('$updateView', serviceUpdateViewFactory, ['$browser']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng:init="$window = $service('$window'); greeting='Hello World!'" type="text" name="greeting" /> <button ng:click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject("$window", bind(window, identity, window)); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.bulk * @requires $xhr * @requires $xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr.bulk', function($xhr, $error, $log){ var requests = [], scope = this; function bulkXHR(method, url, post, success, error) { if (isFunction(post)) { error = success; success = post; post = null; } var currentQueue; forEach(bulkXHR.urls, function(queue){ if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) { currentQueue = queue; } }); if (currentQueue) { if (!currentQueue.requests) currentQueue.requests = []; var request = { method: method, url: url, data: post, success: success}; if (error) request.error = error; currentQueue.requests.push(request); } else { $xhr(method, url, post, success, error); } } bulkXHR.urls = {}; bulkXHR.flush = function(success, error) { forEach(bulkXHR.urls, function(queue, url) { var currentRequests = queue.requests; if (currentRequests && currentRequests.length) { queue.requests = []; queue.callbacks = []; $xhr('POST', url, {requests: currentRequests}, function(code, response, responseHeaders) { forEach(response, function(response, i) { try { if (response.status == 200) { (currentRequests[i].success || noop) (response.status, response.response, responseHeaders); } else if (isFunction(currentRequests[i].error)) { currentRequests[i].error(response.status, response.response, responseHeaders); } else { $error(currentRequests[i], response); } } catch(e) { $log.error(e); } }); (success || noop)(); }, function(code, response, responseHeaders) { forEach(currentRequests, function(request, i) { try { if (isFunction(request.error)) { request.error(code, response, responseHeaders); } else { $error(request, response); } } catch(e) { $log.error(e); } }); (error || noop)(); }); scope.$eval(); } }); }; this.$onEval(PRIORITY_LAST, bulkXHR.flush); return bulkXHR; }, ['$xhr', '$xhr.error', '$log']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.cache * @function * * @requires $xhr.bulk * @requires $defer * @requires $xhr.error * @requires $log * * @description * Acts just like the {@link angular.service.$xhr $xhr} service but caches responses for `GET` * requests. All cache misses are delegated to the $xhr service. * * @property {function()} delegate Function to delegate all the cache misses to. Defaults to * the {@link angular.service.$xhr $xhr} service. * @property {object} data The hashmap where all cached entries are stored. * * @param {string} method HTTP method. * @param {string} url Destination URL. * @param {(string|Object)=} post Request body. * @param {function(number, (string|Object), Function)} success Response success callback. * @param {function(number, (string|Object), Function)} error Response error callback. * @param {boolean=} [verifyCache=false] If `true` then a result is immediately returned from cache * (if present) while a request is sent to the server for a fresh response that will update the * cached entry. The `success` function will be called when the response is received. * @param {boolean=} [sync=false] in case of cache hit execute `success` synchronously. */ angularServiceInject('$xhr.cache', function($xhr, $defer, $error, $log) { var inflight = {}, self = this; function cache(method, url, post, success, error, verifyCache, sync) { if (isFunction(post)) { if (!isFunction(success)) { verifyCache = success; sync = error; error = null; } else { sync = verifyCache; verifyCache = error; error = success; } success = post; post = null; } else if (!isFunction(error)) { sync = verifyCache; verifyCache = error; error = null; } if (method == 'GET') { var data, dataCached; if (dataCached = cache.data[url]) { if (sync) { success(200, copy(dataCached.value), copy(dataCached.headers)); } else { $defer(function() { success(200, copy(dataCached.value), copy(dataCached.headers)); }); } if (!verifyCache) return; } if (data = inflight[url]) { data.successes.push(success); data.errors.push(error); } else { inflight[url] = {successes: [success], errors: [error]}; cache.delegate(method, url, post, function(status, response, responseHeaders) { if (status == 200) cache.data[url] = {value: response, headers: responseHeaders}; var successes = inflight[url].successes; delete inflight[url]; forEach(successes, function(success) { try { (success||noop)(status, copy(response), responseHeaders); } catch(e) { $log.error(e); } }); }, function(status, response, responseHeaders) { var errors = inflight[url].errors, successes = inflight[url].successes; delete inflight[url]; forEach(errors, function(error, i) { try { if (isFunction(error)) { error(status, copy(response), copy(responseHeaders)); } else { $error( {method: method, url: url, data: post, success: successes[i]}, {status: status, body: response}); } } catch(e) { $log.error(e); } }); }); } } else { cache.data = {}; cache.delegate(method, url, post, success, error); } } cache.data = {}; cache.delegate = $xhr; return cache; }, ['$xhr.bulk', '$defer', '$xhr.error', '$log']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.error * @function * @requires $log * * @description * Error handler for {@link angular.service.$xhr $xhr service}. An application can replaces this * service with one specific for the application. The default implementation logs the error to * {@link angular.service.$log $log.error}. * * @param {Object} request Request object. * * The object has the following properties * * - `method` – `{string}` – The http request method. * - `url` – `{string}` – The request destination. * - `data` – `{(string|Object)=} – An optional request body. * - `success` – `{function()}` – The success callback function * * @param {Object} response Response object. * * The response object has the following properties: * * - status – {number} – Http status code. * - body – {string|Object} – Body of the response. * * @example <doc:example> <doc:source> fetch a non-existent file and log an error in the console: <button ng:click="$service('$xhr')('GET', '/DOESNT_EXIST')">fetch</button> </doc:source> </doc:example> */ angularServiceInject('$xhr.error', function($log){ return function(request, response){ $log.error('ERROR: XHR: ' + request.url, request, response); }; }, ['$log']); 'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$xhr * @function * @requires $browser $xhr delegates all XHR requests to the `$browser.xhr()`. A mock version * of the $browser exists which allows setting expectations on XHR requests * in your tests * @requires $xhr.error $xhr delegates all non `2xx` response code to this service. * @requires $log $xhr delegates all exceptions to `$log.error()`. * @requires $updateView After a server response the view needs to be updated for data-binding to * take effect. * * @description * Generates an XHR request. The $xhr service delegates all requests to * {@link angular.service.$browser $browser.xhr()} and adds error handling and security features. * While $xhr service provides nicer api than raw XmlHttpRequest, it is still considered a lower * level api in angular. For a higher level abstraction that utilizes `$xhr`, please check out the * {@link angular.service.$resource $resource} service. * * # Error handling * If no `error callback` is specified, XHR response with response code other then `2xx` will be * delegated to {@link angular.service.$xhr.error $xhr.error}. The `$xhr.error` can intercept the * request and process it in application specific way, or resume normal execution by calling the * request `success` method. * * # HTTP Headers * The $xhr service will automatically add certain http headers to all requests. These defaults can * be fully configured by accessing the `$xhr.defaults.headers` configuration object, which * currently contains this default configuration: * * - `$xhr.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, *\/*` * - `X-Requested-With: XMLHttpRequest` * - `$xhr.defaults.headers.post` (header defaults for HTTP POST requests): * - `Content-Type: application/x-www-form-urlencoded` * * To add or overwrite these defaults, simple add or remove a property from this configuration * object. To add headers for an HTTP method other than POST, simple create a new object with name * equal to the lowercased http method name, e.g. `$xhr.defaults.headers.get['My-Header']='value'`. * * * # Security Considerations * When designing web applications your design needs to consider security threats from * {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} and {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}. * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which an * unauthorized site can gain your user's private data. Angular provides following mechanism to * counter XSRF. When performing XHR requests, the $xhr service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the server * can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure that only * JavaScript running on your domain could have read the token. The token must be unique for each * user and must be verifiable by the server (to prevent the JavaScript making up its own tokens). * We recommend that the token is a digest of your site's authentication cookie with * {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * @param {string} method HTTP method to use. Valid values are: `GET`, `POST`, `PUT`, `DELETE`, and * `JSON`. `JSON` is a special case which causes a * [JSONP](http://en.wikipedia.org/wiki/JSON#JSONP) cross domain request using script tag * insertion. * @param {string} url Relative or absolute URL specifying the destination of the request. For * `JSON` requests, `url` should include `JSON_CALLBACK` string to be replaced with a name of an * angular generated callback function. * @param {(string|Object)=} post Request content as either a string or an object to be stringified * as JSON before sent to the server. * @param {function(number, (string|Object), Function)} success A function to be called when the response is * received. The success function will be called with: * * - {number} code [HTTP status code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) of * the response. This will currently always be 200, since all non-200 responses are routed to * {@link angular.service.$xhr.error} service (or custom error callback). * - {string|Object} response Response object as string or an Object if the response was in JSON * format. * - {function(string=)} responseHeaders A function that when called with a {string} header name, * returns the value of that header or null if it does not exist; when called without * arguments, returns an object containing every response header * @param {function(number, (string|Object))} error A function to be called if the response code is * not 2xx.. Accepts the same arguments as success, above. * * @example <doc:example> <doc:source jsfiddle="false"> <script> function FetchCntl($xhr) { var self = this; this.fetch = function() { self.code = null; self.response = null; $xhr(self.method, self.url, function(code, response) { self.code = code; self.response = response; }, function(code, response) { self.code = code; self.response = response || "Request failed"; }); }; this.updateModel = function(method, url) { self.method = method; self.url = url; }; } FetchCntl.$inject = ['$xhr']; </script> <div ng:controller="FetchCntl"> <select name="method"> <option>GET</option> <option>JSON</option> </select> <input type="text" name="url" value="index.html" size="80"/> <button ng:click="fetch()">fetch</button><br> <button ng:click="updateModel('GET', 'index.html')">Sample GET</button> <button ng:click="updateModel('JSON', 'https://www.googleapis.com/buzz/v1/activities/googlebuzz/@self?alt=json&callback=JSON_CALLBACK')">Sample JSONP (Buzz API)</button> <button ng:click="updateModel('JSON', 'https://www.invalid_JSONP_request.com&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>code={{code}}</pre> <pre>response={{response}}</pre> </div> </doc:source> <doc:scenario> it('should make xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code=200'); expect(binding('response')).toMatch(/angularjs.org/); }); it('should make JSONP request to the Buzz API', function() { element(':button:contains("Buzz API")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code=200'); expect(binding('response')).toMatch(/buzz-feed/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code='); expect(binding('response')).toBe('response=Request failed'); }); </doc:scenario> </doc:example> */ angularServiceInject('$xhr', function($browser, $error, $log, $updateView){ var xhrHeaderDefaults = { common: { "Accept": "application/json, text/plain, */*", "X-Requested-With": "XMLHttpRequest" }, post: {'Content-Type': 'application/x-www-form-urlencoded'}, get: {}, // all these empty properties are needed so that client apps can just do: head: {}, // $xhr.defaults.headers.head.foo="bar" without having to create head object put: {}, // it also means that if we add a header for these methods in the future, it 'delete': {}, // won't be easily silently lost due to an object assignment. patch: {} }; function xhr(method, url, post, success, error) { if (isFunction(post)) { error = success; success = post; post = null; } if (post && isObject(post)) { post = toJson(post); } $browser.xhr(method, url, post, function(code, response, responseHeaders){ try { if (isString(response)) { if (response.match(/^\)\]\}',\n/)) response=response.substr(6); if (/^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { response = fromJson(response, true); } } if (200 <= code && code < 300) { success(code, response, responseHeaders); } else if (isFunction(error)) { error(code, response, responseHeaders); } else { $error( {method: method, url: url, data: post, success: success}, {status: code, body: response}); } } catch (e) { $log.error(e); } finally { $updateView(); } }, extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, xhrHeaderDefaults.common, xhrHeaderDefaults[lowercase(method)])); }; xhr.defaults = {headers: xhrHeaderDefaults}; return xhr; }, ['$browser', '$xhr.error', '$log', '$updateView']); 'use strict'; /** * @workInProgress * @ngdoc overview * @name angular.directive * @description * * Custom attributes for DOM elements. Directives modify the behavior of the element they are * specified in, but are not intended to add elements to the DOM as are * {@link angular.widget widgets}. * * Following is the list of built-in angular directives: * * * {@link angular.directive.ng:bind ng:bind} - Creates a data-binding between HTML text value and * data model. * * {@link angular.directive.ng:bind-attr ng:bind-attr} - Creates a data-binding as in `ng:bind`, * but uses JSON key / value pairs. * * {@link angular.directive.ng:bind-template ng:bind-template} - Replaces text value of an element * with a specified template. * * {@link angular.directive.ng:change ng:change} - Executes an expression when the value of an * input widget changes. * * {@link angular.directive.ng:class ng:class} - Conditionally set CSS class on an element. * * {@link angular.directive.ng:class-even ng:class-even} - Like `ng:class`, but works in * conjunction with {@link angular.widget.@ng:repeat} to affect even rows in a collection. * * {@link angular.directive.ng:class-odd ng:class-odd} - Like `ng:class`, but works with {@link * angular.widget.@ng:repeat} to affect odd rows. * * {@link angular.directive.ng:click ng:click} - Executes custom behavior when element is clicked. * * {@link angular.directive.ng:controller ng:controller} - Creates a scope object linked to the * DOM element and assigns behavior to the scope. * * {@link angular.directive.ng:eval ng:eval} - Executes a binding but blocks output. * * {@link angular.directive.ng:eval-order ng:eval-order} - Change evaluation order when updating * the view. * * {@link angular.directive.ng:hide ng:hide} - Conditionally hides a portion of HTML. * * {@link angular.directive.ng:href ng:href} - Places an href in the angular namespace. * * {@link angular.directive.ng:init} - Initialization tasks run before a template is executed. * * {@link angular.directive.ng:show ng:show} - Conditionally displays a portion of HTML. * * {@link angular.directive.ng:src ng:src} - Places a `src` attribute into the angular namespace. * * {@link angular.directive.ng:style ng:style} - Conditionally set CSS styles on an element. * * {@link angular.directive.ng:submit} - Binds angular expressions to `onSubmit` events. * * For more information about how angular directives work, and how to create your own directives, * see {@link guide/dev_guide.compiler.directives Understanding Angular Directives} in the angular * Developer Guide. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:init * * @description * The `ng:init` attribute specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <div ng:init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function(){ expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ angularDirective("ng:init", function(expression){ return function(element){ this.$tryEval(expression, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:controller * * @description * The `ng:controller` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ng:controller` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link angular.service.$route}` * service. * * @element ANY * @param {expression} expression Name of a globally accessible constructor function or an * {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script type="text/javascript"> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; } SettingsController.prototype = { greet: function(){ alert(this.name); }, addContact: function(){ this.contacts.push({type:'email', value:'yourname@example.org'}); }, removeContact: function(contactToRemove) { angular.Array.remove(this.contacts, contactToRemove); }, clearContact: function(contact) { contact.type = 'phone'; contact.value = ''; } }; </script> <div ng:controller="SettingsController"> Name: <input type="text" name="name"/> [ <a href="" ng:click="greet()">greet</a> ]<br/> Contact: <ul> <li ng:repeat="contact in contacts"> <select name="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" name="contact.value"/> [ <a href="" ng:click="clearContact(contact)">clear</a> | <a href="" ng:click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng:click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function(){ expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li[ng\\:repeat-index="0"] input').val()).toBe('408 555 1212'); expect(element('.doc-example-live li[ng\\:repeat-index="1"] input').val()).toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li[ng\\:repeat-index="2"] input').val()).toBe('yourname@example.org'); }); </doc:scenario> </doc:example> */ angularDirective("ng:controller", function(expression){ this.scope(true); return function(element){ var controller = getter(window, expression, true) || getter(this, expression, true); if (!controller) throw "Can not find '"+expression+"' controller."; if (!isFunction(controller)) throw "Reference '"+expression+"' is not a class."; this.$become(controller); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:eval * * @description * The `ng:eval` allows you to execute a binding which has side effects * without displaying the result to the user. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example * Notice that `{{` `obj.multiplied = obj.a * obj.b` `}}` has a side effect of assigning * a value to `obj.multiplied` and displaying the result to the user. Sometimes, * however, it is desirable to execute a side effect without showing the value to * the user. In such a case `ng:eval` allows you to execute code without updating * the display. <doc:example> <doc:source> <input name="obj.a" value="6" > * <input name="obj.b" value="2"> = {{obj.multiplied = obj.a * obj.b}} <br> <span ng:eval="obj.divide = obj.a / obj.b"></span> <span ng:eval="obj.updateCount = 1 + (obj.updateCount||0)"> </span> <tt>obj.divide = {{obj.divide}}</tt><br> <tt>obj.updateCount = {{obj.updateCount}}</tt> </doc:source> <doc:scenario> it('should check eval', function(){ expect(binding('obj.divide')).toBe('3'); expect(binding('obj.updateCount')).toBe('2'); input('obj.a').enter('12'); expect(binding('obj.divide')).toBe('6'); expect(binding('obj.updateCount')).toBe('3'); }); </doc:scenario> </doc:example> */ angularDirective("ng:eval", function(expression){ return function(element){ this.$onEval(expression, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind * * @description * The `ng:bind` attribute asks angular to replace the text content of this * HTML element with the value of the given expression, and to keep the text * content up to date when the expression's value changes. Usually you would * just write `{{ expression }}` and let angular compile it into * `<span ng:bind="expression"></span>` at bootstrap time. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example * You can try it right here: enter text in the text box and watch the greeting change. <doc:example> <doc:source> Enter name: <input type="text" name="name" value="Whirled"> <br> Hello <span ng:bind="name" />! </doc:source> <doc:scenario> it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind", function(expression, element){ element.addClass('ng-binding'); return function(element) { var lastValue = noop, lastError = noop; this.$onEval(function() { var error, value, html, isHtml, isDomElement, oldElement = this.hasOwnProperty($$element) ? this.$element : undefined; this.$element = element; value = this.$tryEval(expression, function(e){ error = formatError(e); }); this.$element = oldElement; // If we are HTML then save the raw HTML data so that we don't // recompute sanitization since it is expensive. // TODO: turn this into a more generic way to compute this if (isHtml = (value instanceof HTML)) value = (html = value).html; if (lastValue === value && lastError == error) return; isDomElement = isElement(value); if (!isHtml && !isDomElement && isObject(value)) { value = toJson(value, true); } if (value != lastValue || error != lastError) { lastValue = value; lastError = error; elementError(element, NG_EXCEPTION, error); if (error) value = error; if (isHtml) { element.html(html.get()); } else if (isDomElement) { element.html(''); element.append(value); } else { element.text(value == undefined ? '' : value); } } }, element); }; }); var bindTemplateCache = {}; function compileBindTemplate(template){ var fn = bindTemplateCache[template]; if (!fn) { var bindings = []; forEach(parseBindings(template), function(text){ var exp = binding(text); bindings.push(exp ? function(element){ var error, value = this.$tryEval(exp, function(e){ error = toJson(e); }); elementError(element, NG_EXCEPTION, error); return error ? error : value; } : function() { return text; }); }); bindTemplateCache[template] = fn = function(element, prettyPrintJson){ var parts = [], self = this, oldElement = this.hasOwnProperty($$element) ? self.$element : undefined; self.$element = element; for ( var i = 0; i < bindings.length; i++) { var value = bindings[i].call(self, element); if (isElement(value)) value = ''; else if (isObject(value)) value = toJson(value, prettyPrintJson); parts.push(value); } self.$element = oldElement; return parts.join(''); }; } return fn; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind-template * * @description * The `ng:bind-template` attribute specifies that the element * text should be replaced with the template in ng:bind-template. * Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> Salutation: <input type="text" name="salutation" value="Hello"><br/> Name: <input type="text" name="name" value="World"><br/> <pre ng:bind-template="{{salutation}} {{name}}!"></pre> </doc:source> <doc:scenario> it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Hello World!'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Greetings user!'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-template", function(expression, element){ element.addClass('ng-binding'); var templateFn = compileBindTemplate(expression); return function(element) { var lastValue; this.$onEval(function() { var value = templateFn.call(this, element, true); if (value != lastValue) { element.text(value); lastValue = value; } }, element); }; }); var REMOVE_ATTRIBUTES = { 'disabled':'disabled', 'readonly':'readOnly', 'checked':'checked', 'selected':'selected', 'multiple':'multiple' }; /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind-attr * * @description * The `ng:bind-attr` attribute specifies that * {@link guide/dev_guide.templates.databinding databindings} should be created between element * attributes and given expressions. Unlike `ng:bind` the `ng:bind-attr` contains a JSON key value * pairs representing which attributes need to be mapped to which * {@link guide/dev_guide.expressions expressions}. * * You don't usually write the `ng:bind-attr` in the HTML since embedding * <tt ng:non-bindable>{{expression}}</tt> into the attribute directly as the attribute value is * preferred. The attributes get translated into `<span ng:bind-attr="{attr:expression}"/>` at * compile time. * * This HTML snippet is preferred way of working with `ng:bind-attr` * <pre> * <a href="http://www.google.com/search?q={{query}}">Google</a> * </pre> * * The above gets translated to bellow during bootstrap time. * <pre> * <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a> * </pre> * * @element ANY * @param {string} attribute_json a JSON key-value pairs representing * the attributes to replace. Each key matches the attribute * which needs to be replaced. Each value is a text template of * the attribute with embedded * <tt ng:non-bindable>{{expression}}</tt>s. Any number of * key-value pairs can be specified. * * @example * Try it here: enter text in text box and click Google. <doc:example> <doc:source> Google for: <input type="text" name="query" value="AngularJS"/> <a href="http://www.google.com/search?q={{query}}">Google</a> </doc:source> <doc:scenario> it('should check ng:bind-attr', function(){ expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=AngularJS'); using('.doc-example-live').input('query').enter('google'); expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=google'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-attr", function(expression){ return function(element){ var lastValue = {}; this.$onEval(function(){ var values = this.$eval(expression); for(var key in values) { var value = compileBindTemplate(values[key]).call(this, element), specialName = REMOVE_ATTRIBUTES[lowercase(key)]; if (lastValue[key] !== value) { lastValue[key] = value; if (specialName) { if (toBoolean(value)) { element.attr(specialName, specialName); element.attr('ng-' + specialName, value); } else { element.removeAttr(specialName); element.removeAttr('ng-' + specialName); } (element.data($$validate)||noop)(); } else { element.attr(key, value); } } } }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:click * * @description * The ng:click allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval upon click. * * @example <doc:example> <doc:source> <button ng:click="count = count + 1" ng:init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng:click', function(){ expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. * * TODO: maybe we should consider allowing users to control event propagation in the future. */ angularDirective("ng:click", function(expression, element){ return annotate('$updateView', function($updateView, element){ var self = this; element.bind('click', function(event){ self.$tryEval(expression, element); $updateView(); event.stopPropagation(); }); }); }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:submit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <form ng:submit="list.push(text);text='';" ng:init="list=[]"> Enter text and hit enter: <input type="text" name="text" value="hello"/> <input type="submit" id="submit" value="Submit" /> </form> <pre>list={{list}}</pre> </doc:source> <doc:scenario> it('should check ng:submit', function(){ expect(binding('list')).toBe('list=[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('list=["hello"]'); }); </doc:scenario> </doc:example> */ angularDirective("ng:submit", function(expression, element) { return annotate('$updateView', function($updateView, element) { var self = this; element.bind('submit', function(event) { self.$tryEval(expression, element); $updateView(); event.preventDefault(); }); }); }); function ngClass(selector) { return function(expression, element){ var existing = element[0].className + ' '; return function(element){ this.$onEval(function(){ var scope = this; if (selector(scope.$index)) { var ngClassVal = scope.$eval(element.attr('ng:class') || ''); if (isArray(ngClassVal)) ngClassVal = ngClassVal.join(' '); var value = scope.$eval(expression); if (isArray(value)) value = value.join(' '); if (ngClassVal && ngClassVal !== value) value = value + ' ' + ngClassVal; element[0].className = trim(existing + value); } }, element); }; }; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class * * @description * The `ng:class` allows you to set CSS class on HTML element * conditionally. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myVar='ng-input-indicator-wait'"> <input type="button" value="clear" ng:click="myVar=''"> <br> <span ng:class="myVar">Sample Text &nbsp;&nbsp;&nbsp;&nbsp;</span> </doc:source> <doc:scenario> it('should check ng:class', function(){ expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').attr('className')). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class", ngClass(function(){return true;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-odd * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. Must be * inside `ng:repeat`. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-odd", ngClass(function(i){return i % 2 === 0;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-even * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. Must be * inside `ng:repeat`. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-even", ngClass(function(i){return i % 2 === 1;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:show * * @description * The `ng:show` and `ng:hide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng:hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:show", function(expression, element){ return function(element){ this.$onEval(function(){ element.css('display', toBoolean(this.$eval(expression)) ? '' : 'none'); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:hide * * @description * The `ng:hide` and `ng:show` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:hide", function(expression, element){ return function(element){ this.$onEval(function(){ element.css('display', toBoolean(this.$eval(expression)) ? 'none' : ''); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:style * * @description * The ng:style allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myStyle={color:'red'}"> <input type="button" value="clear" ng:click="myStyle={}"> <br/> <span ng:style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </doc:source> <doc:scenario> it('should check ng:style', function(){ expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('red'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </doc:scenario> </doc:example> */ angularDirective("ng:style", function(expression, element){ return function(element){ var resetStyle = getStyle(element); this.$onEval(function(){ var style = this.$eval(expression) || {}, key, mergedStyle = {}; for(key in style) { if (resetStyle[key] === undefined) resetStyle[key] = ''; mergedStyle[key] = style[key]; } for(key in resetStyle) { mergedStyle[key] = mergedStyle[key] || resetStyle[key]; } element.css(mergedStyle); }, element); }; }); 'use strict'; /** * @workInProgress * @ngdoc overview * @name angular.markup * @description * * Angular markup transforms content of DOM elements or portions of this content into other text or * DOM elements for further compilation. * * Markup extensions do not themselves produce linking functions. Think of markup as a way to * produce shorthand for a {@link angular.widget widget} or a {@link angular.directive directive}. * * The most prominent example of a markup in angular is the built-in double curly markup * `{{expression}}`, which is shorthand for `<span ng:bind="expression"></span>`. * * Create custom markup like this: * * <pre> * angular.markup('newMarkup', function(text, textNode, parentElement){ * //tranformation code * }); * </pre> * * For more information about angular markup, see {@link guide/dev_guide.compiler.markup * Understanding Angular Markup} in the angular Developer Guide. */ /** * @workInProgress * @ngdoc overview * @name angular.attrMarkup * @description * * Attribute markup extends the angular compiler in a very similar way as {@link angular.markup} * except that it allows you to modify the state of the attribute text rather than the content of a * node. * * Create custom attribute markup like this: * * <pre> * angular.attrMarkup('newAttrMarkup', function(attrValue, attrName, element){ * //tranformation code * }); * </pre> * * For more information about angular attribute markup, see {@link guide/dev_guide.compiler.markup * Understanding Angular Markup} in the angular Developer Guide. */ function parseBindings(string) { var results = []; var lastIndex = 0; var index; while((index = string.indexOf('{{', lastIndex)) > -1) { if (lastIndex < index) results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; index = string.indexOf('}}', index); index = index < 0 ? string.length : index + 2; results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; } if (lastIndex != string.length) results.push(string.substr(lastIndex, string.length - lastIndex)); return results.length === 0 ? [ string ] : results; } function binding(string) { var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); return binding ? binding[1] : null; } function hasBindings(bindings) { return bindings.length > 1 || binding(bindings[0]) !== null; } angularTextMarkup('{{}}', function(text, textNode, parentElement) { var bindings = parseBindings(text), self = this; if (hasBindings(bindings)) { if (isLeafNode(parentElement[0])) { parentElement.attr('ng:bind-template', text); } else { var cursor = textNode, newElement; forEach(parseBindings(text), function(text){ var exp = binding(text); if (exp) { newElement = jqLite('<span>'); newElement.attr('ng:bind', exp); } else { newElement = jqLite(document.createTextNode(text)); } if (msie && text.charAt(0) == ' ') { newElement = jqLite('<span>&nbsp;</span>'); var nbsp = newElement.html(); newElement.text(text.substr(1)); newElement.html(nbsp + newElement.html()); } cursor.after(newElement); cursor = newElement; }); textNode.remove(); } } }); /** * This tries to normalize the behavior of value attribute across browsers. If value attribute is * not specified, then specify it to be that of the text. */ angularTextMarkup('option', function(text, textNode, parentElement){ if (lowercase(nodeName_(parentElement)) == 'option') { if (msie <= 7) { // In IE7 The issue is that there is no way to see if the value was specified hence // we have to resort to parsing HTML; htmlParser(parentElement[0].outerHTML, { start: function(tag, attrs) { if (isUndefined(attrs.value)) { parentElement.attr('value', text); } } }); } else if (parentElement[0].getAttribute('value') == null) { // jQuery does normalization on 'value' so we have to bypass it. parentElement.attr('value', text); } } }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:href * * @description * Using <angular/> markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ng:href` solves this problem by placing the `href` in the * `ng:` namespace. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng:href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input name="value" /><br /> <a id="link-1" href ng:click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng:click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng:href="#{{'123'}}" ng:click="value = 3">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng:click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng:click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng:href="#/{{value}}">link</a> (link, change hash) </doc:source> <doc:scenario> it('should execute ng:click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng:click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng:click and change url when ng:href specified', function() { element('#link-3').click(); expect(input('value').val()).toEqual('3'); expect(element('#link-3').attr('href')).toBe("#123"); expect(browser().location().hash()).toEqual('123'); }); it('should execute ng:click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(""); }); it('should execute ng:click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(undefined); }); it('should only change url when only ng:href', function() { input('value').enter('6'); element('#link-6').click(); expect(browser().location().hash()).toEqual('/6'); expect(element('#link-6').attr('href')).toBe("#/6"); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:src * * @description * Using <angular/> markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until <angular/> replaces the expression inside * `{{hash}}`. The `ng:src` attribute solves this problem by placing * the `src` attribute in the `ng:` namespace. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng:src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:disabled * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng:init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:disabled. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" name="checked"><br/> <button name="button" ng:disabled="{{checked}}">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').attr('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').attr('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:checked * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:checked. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" name="master"><br/> <input id="checkSlave" type="checkbox" ng:checked="{{master}}"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').attr('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').attr('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:multiple * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:multiple. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" name="checked"><br/> <select id="select" ng:multiple="{{checked}}"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').attr('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').attr('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:readonly * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:readonly. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" name="checked"><br/> <input type="text" ng:readonly="{{checked}}" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').attr('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').attr('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:selected * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:selected. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" name="checked"><br/> <select> <option>Hello!</option> <option id="greet" ng:selected="{{checked}}">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').attr('selected')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #greet').attr('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ var NG_BIND_ATTR = 'ng:bind-attr'; var SPECIAL_ATTRS = {}; forEach('src,href,checked,disabled,multiple,readonly,selected'.split(','), function(name) { SPECIAL_ATTRS['ng:' + name] = name; }); angularAttrMarkup('{{}}', function(value, name, element){ // don't process existing attribute markup if (angularDirective(name) || angularDirective("@" + name)) return; if (msie && name == 'src') value = decodeURI(value); var bindings = parseBindings(value), bindAttr; if (hasBindings(bindings)) { element.removeAttr(name); bindAttr = fromJson(element.attr(NG_BIND_ATTR) || "{}"); bindAttr[SPECIAL_ATTRS[name] || name] = value; element.attr(NG_BIND_ATTR, toJson(bindAttr)); } }); 'use strict'; /** * @workInProgress * @ngdoc overview * @name angular.widget * @description * * An angular widget can be either a custom attribute that modifies an existing DOM element or an * entirely new DOM element. * * During html compilation, widgets are processed after {@link angular.markup markup}, but before * {@link angular.directive directives}. * * Following is the list of built-in angular widgets: * * * {@link angular.widget.@ng:format ng:format} - Formats data for display to user and for storage. * * {@link angular.widget.@ng:non-bindable ng:non-bindable} - Blocks angular from processing an * HTML element. * * {@link angular.widget.@ng:repeat ng:repeat} - Creates and manages a collection of cloned HTML * elements. * * {@link angular.widget.@ng:required ng:required} - Verifies presence of user input. * * {@link angular.widget.@ng:validate ng:validate} - Validates content of user input. * * {@link angular.widget.HTML HTML input elements} - Standard HTML input elements data-bound by * angular. * * {@link angular.widget.ng:view ng:view} - Works with $route to "include" partial templates * * {@link angular.widget.ng:switch ng:switch} - Conditionally changes DOM structure * * {@link angular.widget.ng:include ng:include} - Includes an external HTML fragment * * For more information about angular widgets, see {@link guide/dev_guide.compiler.widgets * Understanding Angular Widgets} in the angular Developer Guide. */ /** * @workInProgress * @ngdoc widget * @name angular.widget.HTML * * @description * The most common widgets you will use will be in the form of the * standard HTML set. These widgets are bound using the `name` attribute * to an expression. In addition, they can have `ng:validate`, `ng:required`, * `ng:format`, `ng:change` attribute to further control their behavior. * * @usageContent * see example below for usage * * <input type="text|checkbox|..." ... /> * <textarea ... /> * <select ...> * <option>...</option> * </select> * * @example <doc:example> <doc:source> <table style="font-size:.9em;"> <tr> <th>Name</th> <th>Format</th> <th>HTML</th> <th>UI</th> <th ng:non-bindable>{{input#}}</th> </tr> <tr> <th>text</th> <td>String</td> <td><tt>&lt;input type="text" name="input1"&gt;</tt></td> <td><input type="text" name="input1" size="4"></td> <td><tt>{{input1|json}}</tt></td> </tr> <tr> <th>textarea</th> <td>String</td> <td><tt>&lt;textarea name="input2"&gt;&lt;/textarea&gt;</tt></td> <td><textarea name="input2" cols='6'></textarea></td> <td><tt>{{input2|json}}</tt></td> </tr> <tr> <th>radio</th> <td>String</td> <td><tt> &lt;input type="radio" name="input3" value="A"&gt;<br> &lt;input type="radio" name="input3" value="B"&gt; </tt></td> <td> <input type="radio" name="input3" value="A"> <input type="radio" name="input3" value="B"> </td> <td><tt>{{input3|json}}</tt></td> </tr> <tr> <th>checkbox</th> <td>Boolean</td> <td><tt>&lt;input type="checkbox" name="input4" value="checked"&gt;</tt></td> <td><input type="checkbox" name="input4" value="checked"></td> <td><tt>{{input4|json}}</tt></td> </tr> <tr> <th>pulldown</th> <td>String</td> <td><tt> &lt;select name="input5"&gt;<br> &nbsp;&nbsp;&lt;option value="c"&gt;C&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="d"&gt;D&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input5"> <option value="c">C</option> <option value="d">D</option> </select> </td> <td><tt>{{input5|json}}</tt></td> </tr> <tr> <th>multiselect</th> <td>Array</td> <td><tt> &lt;select name="input6" multiple size="4"&gt;<br> &nbsp;&nbsp;&lt;option value="e"&gt;E&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="f"&gt;F&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input6" multiple size="4"> <option value="e">E</option> <option value="f">F</option> </select> </td> <td><tt>{{input6|json}}</tt></td> </tr> </table> </doc:source> <doc:scenario> it('should exercise text', function(){ input('input1').enter('Carlos'); expect(binding('input1')).toEqual('"Carlos"'); }); it('should exercise textarea', function(){ input('input2').enter('Carlos'); expect(binding('input2')).toEqual('"Carlos"'); }); it('should exercise radio', function(){ expect(binding('input3')).toEqual('null'); input('input3').select('A'); expect(binding('input3')).toEqual('"A"'); input('input3').select('B'); expect(binding('input3')).toEqual('"B"'); }); it('should exercise checkbox', function(){ expect(binding('input4')).toEqual('false'); input('input4').check(); expect(binding('input4')).toEqual('true'); }); it('should exercise pulldown', function(){ expect(binding('input5')).toEqual('"c"'); select('input5').option('d'); expect(binding('input5')).toEqual('"d"'); }); it('should exercise multiselect', function(){ expect(binding('input6')).toEqual('[]'); select('input6').options('e'); expect(binding('input6')).toEqual('["e"]'); select('input6').options('e', 'f'); expect(binding('input6')).toEqual('["e","f"]'); }); </doc:scenario> </doc:example> */ function modelAccessor(scope, element) { var expr = element.attr('name'); var exprFn, assignFn; if (expr) { exprFn = parser(expr).assignable(); assignFn = exprFn.assign; if (!assignFn) throw new Error("Expression '" + expr + "' is not assignable."); return { get: function() { return exprFn(scope); }, set: function(value) { if (value !== undefined) { return scope.$tryEval(function(){ assignFn(scope, value); }, element); } } }; } } function modelFormattedAccessor(scope, element) { var accessor = modelAccessor(scope, element), formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName); if (accessor) { return { get: function() { return formatter.format(scope, accessor.get()); }, set: function(value) { return accessor.set(formatter.parse(scope, value)); } }; } } function compileValidator(expr) { return parser(expr).validator()(); } function compileFormatter(expr) { return parser(expr).formatter()(); } /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:validate * * @description * The `ng:validate` attribute widget validates the user input. If the input does not pass * validation, the `ng-validation-error` CSS class and the `ng:error` attribute are set on the input * element. Check out {@link angular.validator validators} to find out more. * * @param {string} validator The name of a built-in or custom {@link angular.validator validator} to * to be used. * * @element INPUT * @css ng-validation-error * * @example * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * <doc:example> <doc:source> I don't validate: <input type="text" name="value" value="NotANumber"><br/> I need an integer or nothing: <input type="text" name="value" ng:validate="integer"><br/> </doc:source> <doc:scenario> it('should check ng:validate', function(){ expect(element('.doc-example-live :input:last').attr('className')). toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input:last').attr('className')). not().toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:required * * @description * The `ng:required` attribute widget validates that the user input is present. It is a special case * of the {@link angular.widget.@ng:validate ng:validate} attribute widget. * * @element INPUT * @css ng-validation-error * * @example * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * <doc:example> <doc:source> I cannot be blank: <input type="text" name="value" ng:required><br/> </doc:source> <doc:scenario> it('should check ng:required', function(){ expect(element('.doc-example-live :input').attr('className')).toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input').attr('className')).not().toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:format * * @description * The `ng:format` attribute widget formats stored data to user-readable text and parses the text * back to the stored form. You might find this useful, for example, if you collect user input in a * text field but need to store the data in the model as a list. Check out * {@link angular.formatter formatters} to learn more. * * @param {string} formatter The name of the built-in or custom {@link angular.formatter formatter} * to be used. * * @element INPUT * * @example * This example shows how the user input is converted from a string and internally represented as an * array. * <doc:example> <doc:source> Enter a comma separated list of items: <input type="text" name="list" ng:format="list" value="table, chairs, plate"> <pre>list={{list}}</pre> </doc:source> <doc:scenario> it('should check ng:format', function(){ expect(binding('list')).toBe('list=["table","chairs","plate"]'); input('list').enter(',,, a ,,,'); expect(binding('list')).toBe('list=["a"]'); }); </doc:scenario> </doc:example> */ function valueAccessor(scope, element) { var validatorName = element.attr('ng:validate') || NOOP, validator = compileValidator(validatorName), requiredExpr = element.attr('ng:required'), formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName), format, parse, lastError, required, invalidWidgets = scope.$service('$invalidWidgets') || {markValid:noop, markInvalid:noop}; if (!validator) throw "Validator named '" + validatorName + "' not found."; format = formatter.format; parse = formatter.parse; if (requiredExpr) { scope.$watch(requiredExpr, function(newValue) { required = newValue; validate(); }); } else { required = requiredExpr === ''; } element.data($$validate, validate); return { get: function(){ if (lastError) elementError(element, NG_VALIDATION_ERROR, null); try { var value = parse(scope, element.val()); validate(); return value; } catch (e) { lastError = e; elementError(element, NG_VALIDATION_ERROR, e); } }, set: function(value) { var oldValue = element.val(), newValue = format(scope, value); if (oldValue != newValue) { element.val(newValue || ''); // needed for ie } validate(); } }; function validate() { var value = trim(element.val()); if (element[0].disabled || element[0].readOnly) { elementError(element, NG_VALIDATION_ERROR, null); invalidWidgets.markValid(element); } else { var error, validateScope = inherit(scope, {$element:element}); error = required && !value ? 'Required' : (value ? validator(validateScope, value) : null); elementError(element, NG_VALIDATION_ERROR, error); lastError = error; if (error) { invalidWidgets.markInvalid(element); } else { invalidWidgets.markValid(element); } } } } function checkedAccessor(scope, element) { var domElement = element[0], elementValue = domElement.value; return { get: function(){ return !!domElement.checked; }, set: function(value){ domElement.checked = toBoolean(value); } }; } function radioAccessor(scope, element) { var domElement = element[0]; return { get: function(){ return domElement.checked ? domElement.value : null; }, set: function(value){ domElement.checked = value == domElement.value; } }; } function optionsAccessor(scope, element) { var formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName); return { get: function(){ var values = []; forEach(element[0].options, function(option){ if (option.selected) values.push(formatter.parse(scope, option.value)); }); return values; }, set: function(values){ var keys = {}; forEach(values, function(value){ keys[formatter.format(scope, value)] = true; }); forEach(element[0].options, function(option){ option.selected = keys[option.value]; }); } }; } function noopAccessor() { return { get: noop, set: noop }; } /* * TODO: refactor * * The table below is not quite right. In some cases the formatter is on the model side * and in some cases it is on the view side. This is a historical artifact * * The concept of model/view accessor is useful for anyone who is trying to develop UI, and * so it should be exposed to others. There should be a form object which keeps track of the * accessors and also acts as their factory. It should expose it as an object and allow * the validator to publish errors to it, so that the the error messages can be bound to it. * */ var textWidget = inputWidget('keydown change', modelAccessor, valueAccessor, initWidgetValue(), true), INPUT_TYPE = { 'text': textWidget, 'textarea': textWidget, 'hidden': textWidget, 'password': textWidget, 'checkbox': inputWidget('click', modelFormattedAccessor, checkedAccessor, initWidgetValue(false)), 'radio': inputWidget('click', modelFormattedAccessor, radioAccessor, radioInit), 'select-one': inputWidget('change', modelAccessor, valueAccessor, initWidgetValue(null)), 'select-multiple': inputWidget('change', modelAccessor, optionsAccessor, initWidgetValue([])) // 'file': fileWidget??? }; function initWidgetValue(initValue) { return function (model, view) { var value = view.get(); if (!value && isDefined(initValue)) { value = copy(initValue); } if (isUndefined(model.get()) && isDefined(value)) { model.set(value); } }; } function radioInit(model, view, element) { var modelValue = model.get(), viewValue = view.get(), input = element[0]; input.checked = false; input.name = this.$id + '@' + input.name; if (isUndefined(modelValue)) { model.set(modelValue = null); } if (modelValue == null && viewValue !== null) { model.set(viewValue); } view.set(modelValue); } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:change * * @description * The directive executes an expression whenever the input widget changes. * * @element INPUT * @param {expression} expression to execute. * * @example * @example <doc:example> <doc:source> <div ng:init="checkboxCount=0; textCount=0"></div> <input type="text" name="text" ng:change="textCount = 1 + textCount"> changeCount {{textCount}}<br/> <input type="checkbox" name="checkbox" ng:change="checkboxCount = 1 + checkboxCount"> changeCount {{checkboxCount}}<br/> </doc:source> <doc:scenario> it('should check ng:change', function(){ expect(binding('textCount')).toBe('0'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('text').enter('abc'); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('checkbox').check(); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('1'); }); </doc:scenario> </doc:example> */ function inputWidget(events, modelAccessor, viewAccessor, initFn, textBox) { return annotate('$updateView', '$defer', function($updateView, $defer, element) { var scope = this, model = modelAccessor(scope, element), view = viewAccessor(scope, element), action = element.attr('ng:change') || '', lastValue; if (model) { initFn.call(scope, model, view, element); this.$eval(element.attr('ng:init')||''); element.bind(events, function(event){ function handler(){ var value = view.get(); if (!textBox || value != lastValue) { model.set(value); lastValue = model.get(); scope.$tryEval(action, element); $updateView(); } } event.type == 'keydown' ? $defer(handler) : handler(); }); scope.$watch(model.get, function(value){ if (lastValue !== value) { view.set(lastValue = value); } }); } }); } function inputWidgetSelector(element){ this.directives(true); this.descend(true); return INPUT_TYPE[lowercase(element[0].type)] || noop; } angularWidget('input', inputWidgetSelector); angularWidget('textarea', inputWidgetSelector); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:options * * @description * Dynamically generate a list of `<option>` elements for a `<select>` element using an array or * an object obtained by evaluating the `ng:options` expression. * * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `name` attribute * of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ng:options` provides iterator facility for `<option>` element which must be used instead * of {@link angular.widget.@ng:repeat ng:repeat}. `ng:repeat` is not suitable for use with * `<option>` element because of the following reasons: * * * value attribute of the option element that we need to bind to requires a string, but the * source of data for the iteration might be in a form of array containing objects instead of * strings * * {@link angular.widget.@ng:repeat ng:repeat} unrolls after the select binds causing * incorect rendering on most browsers. * * binding to a value not in list confuses most browsers. * * @element select * @param {comprehension_expression} comprehension in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl(){ this.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; this.color = this.colors[2]; // red } </script> <div ng:controller="MyCntrl"> <ul> <li ng:repeat="color in colors"> Name: <input name="color.name"> [<a href ng:click="colors.$remove(color)">X</a>] </li> <li> [<a href ng:click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select name="color" ng:options="c.name for c in colors"></select><br> Color (null allowed): <div class="nullable"> <select name="color" ng:options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </div><br/> Color grouped by shade: <select name="color" ng:options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng:click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng:style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng:options', function(){ expect(binding('color')).toMatch('red'); select('color').option('0'); expect(binding('color')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('color')).toMatch('null'); }); </doc:scenario> </doc:example> */ // 00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/; angularWidget('select', function(element){ this.descend(true); this.directives(true); var isMultiselect = element.attr('multiple'), expression = element.attr('ng:options'), onChange = expressionCompile(element.attr('ng:change') || "").fnSelf, match; if (!expression) { return inputWidgetSelector.call(this, element); } if (! (match = expression.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ng:options in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + expression + "'."); } var displayFn = expressionCompile(match[2] || match[1]).fnSelf, valueName = match[4] || match[6], keyName = match[5], groupByFn = expressionCompile(match[3] || '').fnSelf, valueFn = expressionCompile(match[2] ? match[1] : valueName).fnSelf, valuesFn = expressionCompile(match[7]).fnSelf, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate = jqLite(document.createElement('optgroup')), nullOption = false; // if false then user will not be able to select it return function(selectElement){ // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element var optionGroupsCache = [[{element: selectElement, label:''}]], scope = this, model = modelAccessor(scope, element); // find existing special options forEach(selectElement.children(), function(option){ if (option.value == '') // User is allowed to select the null. nullOption = {label:jqLite(option).text(), id:''}; }); selectElement.html(''); // clear contents selectElement.bind('change', function(){ var optionGroup, collection = valuesFn(scope) || [], key = selectElement.val(), tempScope = inherit(scope), value, optionElement, index, groupIndex, length, groupLength; try { if (isMultiselect) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { if (keyName) tempScope[keyName] = key; tempScope[valueName] = collection[optionElement.val()]; value.push(valueFn(tempScope)); } } } } else { if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { tempScope[valueName] = collection[key]; if (keyName) tempScope[keyName] = key; value = valueFn(tempScope); } } if (isDefined(value) && model.get() !== value) { onChange(scope); model.set(value); } scope.$tryEval(function(){ scope.$root.$eval(); }); } finally { tempScope = null; // TODO(misko): needs to be $destroy } }); scope.$onEval(function(){ var scope = this, optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, values = valuesFn(scope) || [], keys = values, key, groupLength, length, fragment, groupIndex, index, optionElement, optionScope = inherit(scope), modelValue = model.get(), selected, selectedSet = false, // nothing is selected yet isMulti = isMultiselect, lastElement, element; try { if (isMulti) { selectedSet = new HashMap(); if (modelValue && isNumber(length = modelValue.length)) { for (index = 0; index < length; index++) { selectedSet.put(modelValue[index], true); } } } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push(extend({selected:modelValue === null, id:'', label:''}, nullOption)); selectedSet = true; } // If we have a keyName then we are iterating over on object. Grab the keys and sort them. if(keyName) { keys = []; for (key in values) { if (values.hasOwnProperty(key)) keys.push(key); } keys.sort(); } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { optionScope[valueName] = values[keyName ? optionScope[keyName]=keys[index]:index]; optionGroupName = groupByFn(optionScope) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (isMulti) { selected = !!selectedSet.remove(valueFn(optionScope)); } else { selected = modelValue === valueFn(optionScope); selectedSet = selectedSet || selected; // see if at least one item is selected } optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: displayFn(optionScope) || '', // what will be seen by the user selected: selected // determine if we should be selected }); } optionGroupNames.sort(); if (!isMulti && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups optionGroupsCache.push( existingOptions = [ existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label } ] ); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the begining for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if (existingOption = existingOptions[index+1]) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (existingOption.selected !== option.selected) { lastElement.attr('selected', option.selected); } } else { // grow elements // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, checked: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } finally { optionScope = null; // TODO(misko): needs to be $destroy() } }); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:include * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ng:include won't work for file:// access). * * @param {string} src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {Scope=} [scope=new_child_scope] optional expression which evaluates to an * instance of angular.scope to set the HTML fragment to. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @example <doc:example> <doc:source jsfiddle="false"> <select name="url"> <option value="examples/ng-include/template1.html">template1.html</option> <option value="examples/ng-include/template2.html">template2.html</option> <option value="">(blank)</option> </select> url of the template: <tt><a href="{{url}}">{{url}}</a></tt> <hr/> <ng:include src="url"></ng:include> </doc:source> <doc:scenario> it('should load template1.html', function(){ expect(element('.doc-example-live ng\\:include').text()). toBe('Content of template1.html\n'); }); it('should load template2.html', function(){ select('url').option('examples/ng-include/template2.html'); expect(element('.doc-example-live ng\\:include').text()). toBe('Content of template2.html\n'); }); it('should change to blank', function(){ select('url').option(''); expect(element('.doc-example-live ng\\:include').text()).toEqual(''); }); </doc:scenario> </doc:example> */ angularWidget('ng:include', function(element){ var compiler = this, srcExp = element.attr("src"), scopeExp = element.attr("scope") || '', onloadExp = element[0].getAttribute('onload') || ''; //workaround for jquery bug #7537 if (element[0]['ng:compiled']) { this.descend(true); this.directives(true); } else { element[0]['ng:compiled'] = true; return extend(function(xhr, element){ var scope = this, childScope; var changeCounter = 0; var preventRecursion = false; function incrementChange(){ changeCounter++;} this.$watch(srcExp, incrementChange); this.$watch(scopeExp, incrementChange); // note that this propagates eval to the current childScope, where childScope is dynamically // bound (via $route.onChange callback) to the current scope created by $route scope.$onEval(function(){ if (childScope && !preventRecursion) { preventRecursion = true; try { childScope.$eval(); } finally { preventRecursion = false; } } }); this.$watch(function(){return changeCounter;}, function(){ var src = this.$eval(srcExp), useScope = this.$eval(scopeExp); if (src) { xhr('GET', src, null, function(code, response){ element.html(response); childScope = useScope || createScope(scope); compiler.compile(element)(childScope); scope.$eval(onloadExp); }, false, true); } else { childScope = null; element.html(''); } }); }, {$inject:['$xhr.cache']}); } }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:switch * * @description * Conditionally change the DOM structure. * * @usageContent * <any ng:switch-when="matchValue1">...</any> * <any ng:switch-when="matchValue2">...</any> * ... * <any ng:switch-default>...</any> * * @param {*} on expression to match against <tt>ng:switch-when</tt>. * @paramDescription * On child elments add: * * * `ng:switch-when`: the case statement to match against. If match then this * case will be displayed. * * `ng:switch-default`: the default case when no other casses match. * * @example <doc:example> <doc:source> <select name="switch"> <option>settings</option> <option>home</option> <option>other</option> </select> <tt>switch={{switch}}</tt> </hr> <ng:switch on="switch" > <div ng:switch-when="settings">Settings Div</div> <span ng:switch-when="home">Home Span</span> <span ng:switch-default>default</span> </ng:switch> </code> </doc:source> <doc:scenario> it('should start in settings', function(){ expect(element('.doc-example-live ng\\:switch').text()).toEqual('Settings Div'); }); it('should change to home', function(){ select('switch').option('home'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('Home Span'); }); it('should select deafault', function(){ select('switch').option('other'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('default'); }); </doc:scenario> </doc:example> */ //TODO(im): remove all the code related to using and inline equals var ngSwitch = angularWidget('ng:switch', function (element){ var compiler = this, watchExpr = element.attr("on"), usingExpr = (element.attr("using") || 'equals'), usingExprParams = usingExpr.split(":"), usingFn = ngSwitch[usingExprParams.shift()], changeExpr = element.attr('change') || '', cases = []; if (!usingFn) throw "Using expression '" + usingExpr + "' unknown."; if (!watchExpr) throw "Missing 'on' attribute."; eachNode(element, function(caseElement){ var when = caseElement.attr('ng:switch-when'); var switchCase = { change: changeExpr, element: caseElement, template: compiler.compile(caseElement) }; if (isString(when)) { switchCase.when = function(scope, value){ var args = [value, when]; forEach(usingExprParams, function(arg){ args.push(arg); }); return usingFn.apply(scope, args); }; cases.unshift(switchCase); } else if (isString(caseElement.attr('ng:switch-default'))) { switchCase.when = valueFn(true); cases.push(switchCase); } }); // this needs to be here for IE forEach(cases, function(_case){ _case.element.remove(); }); element.html(''); return function(element){ var scope = this, childScope; this.$watch(watchExpr, function(value){ var found = false; element.html(''); childScope = createScope(scope); forEach(cases, function(switchCase){ if (!found && switchCase.when(childScope, value)) { found = true; childScope.$tryEval(switchCase.change, element); switchCase.template(childScope, function(caseElement){ element.append(caseElement); }); } }); }); scope.$onEval(function(){ if (childScope) childScope.$eval(); }); }; }, { equals: function(on, when) { return ''+on == when; } }); /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with ng:click without * changing the location or causing page reloads, e.g.: * <a href="" ng:click="model.$save()">Save</a> */ angularWidget('a', function() { this.descend(true); this.directives(true); return function(element) { var hasNgHref = ((element.attr('ng:bind-attr') || '').indexOf('"href":') !== -1); // turn <a href ng:click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!hasNgHref && !element.attr('name') && !element.attr('href')) { element.attr('href', ''); } if (element.attr('href') === '' && !hasNgHref) { element.bind('click', function(event){ event.preventDefault(); }); } }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:repeat * * @description * The `ng:repeat` widget instantiates a template once per item from a collection. The collection is * enumerated with the `ng:repeat-index` attribute, starting from 0. Each template instance gets * its own scope, where the given loop variable is set to the current collection item, and `$index` * is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$position` – `{string}` – position of the repeated element in the iterator. One of: * * `'first'`, * * `'middle'` * * `'last'` * * Note: Although `ng:repeat` looks like a directive, it is actually an attribute widget. * * @element ANY * @param {string} repeat_expression The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ng:repeat` to display every person: <doc:example> <doc:source> <div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng:repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng:repeat', function(){ var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ angularWidget('@ng:repeat', function(expression, element){ element.removeAttr('ng:repeat'); element.replaceWith(jqLite('<!-- ng:repeat: ' + expression + ' -->')); var linker = this.compile(element); return function(iterStartElement){ var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ng:repeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + keyValue + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; var children = [], currentScope = this; this.$onEval(function(){ var index = 0, childCount = children.length, lastIterElement = iterStartElement, collection = this.$tryEval(rhs, iterStartElement), collectionLength = size(collection, true), fragment = (element[0].nodeName != 'OPTION') ? document.createDocumentFragment() : null, addFragment, childScope, key; for (key in collection) { if (collection.hasOwnProperty(key)) { if (index < childCount) { // reuse existing child childScope = children[index]; childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; lastIterElement = childScope.$element; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); childScope.$eval(); } else { // grow children childScope = createScope(currentScope); childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); children.push(childScope); linker(childScope, function(clone){ clone.attr('ng:repeat-index', index); if (fragment) { fragment.appendChild(clone[0]); addFragment = true; } else { //temporarily preserve old way for option element lastIterElement.after(clone); lastIterElement = clone; } }); } index ++; } } //attach new nodes buffered in doc fragment if (addFragment) { lastIterElement.after(jqLite(fragment)); } // shrink children while(children.length > index) { children.pop().$element.remove(); } }, iterStartElement); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:non-bindable * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML. * * Note: `ng:non-bindable` looks like a directive, but is actually an attribute widget. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ng:non-bindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng:non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng:non-bindable', function(){ expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ angularWidget("@ng:non-bindable", noop); /** * @ngdoc widget * @name angular.widget.ng:view * * @description * # Overview * `ng:view` is a widget that complements the {@link angular.service.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * This widget provides functionality similar to {@link angular.widget.ng:include ng:include} when * used like this: * * <ng:include src="$route.current.template" scope="$route.current.scope"></ng:include> * * * # Advantages * Compared to `ng:include`, `ng:view` offers these advantages: * * - shorter syntax * - more efficient execution * - doesn't require `$route` service to be available on the root scope * * * @example <doc:example> <doc:source jsfiddle="false"> <script> function MyCtrl($route) { $route.when('/overview', { controller: OverviewCtrl, template: 'guide/dev_guide.overview.html'}); $route.when('/bootstrap', { controller: BootstrapCtrl, template: 'guide/dev_guide.bootstrap.auto_bootstrap.html'}); }; MyCtrl.$inject = ['$route']; function BootstrapCtrl(){} function OverviewCtrl(){} </script> <div ng:controller="MyCtrl"> <a href="#/overview">overview</a> | <a href="#/bootstrap">bootstrap</a> | <a href="#/undefined">undefined</a> <br/> The view is included below: <hr/> <ng:view></ng:view> </div> </doc:source> <doc:scenario> it('should load templates', function(){ element('.doc-example-live a:contains(overview)').click(); expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Overview/); element('.doc-example-live a:contains(bootstrap)').click(); expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Initializing Angular: Automatic Initiialization/); }); </doc:scenario> </doc:example> */ angularWidget('ng:view', function(element) { var compiler = this; if (!element[0]['ng:compiled']) { element[0]['ng:compiled'] = true; return annotate('$xhr.cache', '$route', function($xhr, $route, element){ var parentScope = this, childScope; $route.onChange(function(){ var src; if ($route.current) { src = $route.current.template; childScope = $route.current.scope; } if (src) { //xhr's callback must be async, see commit history for more info $xhr('GET', src, function(code, response){ element.html(response); compiler.compile(element)(childScope); }); } else { element.html(''); } })(); //initialize the state forcefully, it's possible that we missed the initial //$route#onChange already // note that this propagates eval to the current childScope, where childScope is dynamically // bound (via $route.onChange callback) to the current scope created by $route parentScope.$onEval(function() { if (childScope) { childScope.$eval(); } }); }); } else { this.descend(true); this.directives(true); } }); 'use strict'; var browserSingleton; angularService('$browser', function($log){ if (!browserSingleton) { browserSingleton = new Browser(window, jqLite(window.document), jqLite(window.document.body), XHR, $log); browserSingleton.bind(); } return browserSingleton; }, {$inject:['$log']}); extend(angular, { // disabled for now until we agree on public name //'annotate': annotate, 'element': jqLite, 'compile': compile, 'scope': createScope, 'copy': copy, 'extend': extend, 'equals': equals, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isArray': isArray, 'version': version }); //try to bind to jquery now so that one can write angular.element().read() //but we will rebind on bootstrap again. bindJQuery(); 'use strict'; /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {Function} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {Function} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {Function} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function (config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {Function} iterator Callback function(value, continueFunction) * @param {Function} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number} maxStackLines Optional. max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} Optional event type. */ function browserTrigger(element, type) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[element.type] || 'click'; } if (lowercase(nodeName_(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } if (msie < 9) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } } else { var evnt = document.createEvent('MouseEvents'); evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element); element.dispatchEvent(evnt); } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown)/.test(type)) { return this.each(function(index, node) { browserTrigger(node, type); }); } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} name The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(name) { function contains(text, value) { return value instanceof RegExp ? value.test(text) : text && text.indexOf(value) >= 0; } var result = []; this.find('.ng-binding:visible').each(function() { var element = new _jQuery(this); if (!angular.isDefined(name) || contains(element.attr('ng:bind'), name) || contains(element.attr('ng:bind-template'), name)) { if (element.is('input, textarea')) { result.push(element.val()); } else { result.push(element.html()); } } }); return result; }; 'use strict'; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().attr('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {Function} loadFn function($window, $document) Called when frame loads. * @param {Function} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.remove(); this.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {Function} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } var $browser = $window.angular.service.$browser(); $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, _jQuery($window.document)); }); }; 'use strict'; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; 'use strict'; /** * A future action in a spec. * * @param {string} name of the future action * @param {Function} future callback(error, result) * @param {Function} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {Function} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {Function} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; 'use strict'; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec, step) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {Function} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; 'use strict'; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; 'use strict'; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { return scope.$new(angular.scenario.SpecRunner); }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.scope(this); $root.application = application; this.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = angular.scope(runner); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, specDone); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; 'use strict'; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {Function} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; 'use strict'; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().location().href() the full URL of the page * browser().location().hash() the full hash in the url * browser().location().path() the full path in the url * browser().location().hashSearch() the hashSearch Object from angular * browser().location().hashPath() the hashPath string from angular */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.location = function() { var api = {}; api.href = function() { return this.addFutureAction('browser url', function($window, $document, done) { done(null, $window.location.href); }); }; api.hash = function() { return this.addFutureAction('browser url hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; api.path = function() { return this.addFutureAction('browser url path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('browser url search', function($window, $document, done) { done(null, $window.angular.scope().$service('$location').search); }); }; api.hashSearch = function() { return this.addFutureAction('browser url hash search', function($window, $document, done) { done(null, $window.angular.scope().$service('$location').hashSearch); }); }; api.hashPath = function() { return this.addFutureAction('browser url hash path', function($window, $document, done) { done(null, $window.angular.scope().$service('$location').hashPath); }); }; return api; }; return function(time) { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings(name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; chain.enter = function(value) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements(':input[name="$1"]', this.name); input.val(value); input.trigger('keydown'); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements(':checkbox[name="$1"]', this.name); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements(':radio[name$="@$1"][value="$2"]', this.name, value); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements(':input[name="$1"]', this.name); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings(binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var values = []; var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings()); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[name="$1"]', this.name); select.val(value); select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][name="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); elements.trigger('click'); if (href && elements[0].nodeName.toUpperCase() === 'A') { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var futureName = "element '" + this.label + "' get " + methodName + " '" + name + "'"; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, name, value)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var futureName = "element '" + this.label + "' " + methodName; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, value)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); 'use strict'; /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); 'use strict'; /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">&lt;angular/&gt;</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec, step) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); }; /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {Function} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); }; }); 'use strict'; /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); 'use strict'; /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error'); stepContext.append(error); error.text(formatException(stepContext.error)); } }); }); } }); 'use strict'; /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); var $runner = new angular.scenario.Runner(window), config = angularJsConfig(document); if (config.autotest) { jqLiteWrap(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n.ng-format-negative {\n color: red;\n}\n\n.ng-exception {\n border: 2px solid #FF0000;\n font-family: "Courier New", Courier, monospace;\n font-size: smaller;\n white-space: pre;\n}\n\n.ng-validation-error {\n border: 2px solid #FF0000;\n}\n\n\n/*****************\n * TIP\n *****************/\n#ng-callout {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 13px;\n font-weight: normal;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n vertical-align: baseline;\n background: transparent;\n text-decoration: none;\n}\n\n#ng-callout .ng-arrow-left{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n left:-12px;\n height:23px;\n width:10px;\n top:-3px;\n}\n\n#ng-callout .ng-arrow-right{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n height:23px;\n width:11px;\n top:-2px;\n}\n\n#ng-callout {\n position: absolute;\n z-index:100;\n border: 2px solid #CCCCCC;\n background-color: #fff;\n}\n\n#ng-callout .ng-content{\n padding:10px 10px 10px 10px;\n color:#333333;\n}\n\n#ng-callout .ng-title{\n background-color: #CCCCCC;\n text-align: left;\n padding-left: 8px;\n padding-bottom: 5px;\n padding-top: 2px;\n font-weight:bold;\n}\n\n\n/*****************\n * indicators\n *****************/\n.ng-input-indicator-wait {\n background-image: url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");\n background-position: right;\n background-repeat: no-repeat;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
/*! * jQuery JavaScript Library v1.6.1 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu May 12 15:04:36 2011 -0400 */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!cj[a]){var b=f("<"+a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),c.body.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write("<!doctype><html><body></body></html>");b=cl.createElement(a),cl.body.appendChild(b),d=f.css(b,"display"),c.body.removeChild(ck)}cj[a]=d}return cj[a]}function cu(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function ct(){cq=b}function cs(){setTimeout(ct,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||bF.test(a)?d(a,e):b_(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(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===bU,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=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bQ),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 bD(a,b,c){var d=b==="width"?bx:by,e=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return e;f.each(d,function(){c||(e-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?e+=parseFloat(f.css(a,"margin"+this))||0:e-=parseFloat(f.css(a,"border"+this+"Width"))||0});return e}function bn(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bm(a){f.nodeName(a,"input")?bl(a):a.getElementsByTagName&&f.grep(a.getElementsByTagName("input"),bl)}function bl(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bk(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bj(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bi(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c=f.expando,d=f.data(a),e=f.data(b,d);if(d=d[c]){var g=d.events;e=e[c]=f.extend({},d);if(g){delete e.handle,e.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)f.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function bh(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function X(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(S.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 W(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function O(a,b){return(a&&a!=="*"?a+".":"")+b.replace(A,"`").replace(B,"&")}function N(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(y,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function L(a,c,d){var e=f.extend({},d[0]);e.type=a,e.originalEvent={},e.liveFired=b,f.event.handle.call(c,e),e.isDefaultPrevented()&&d[0].preventDefault()}function F(){return!0}function E(){return!1}function m(a,c,d){var e=c+"defer",g=c+"queue",h=c+"mark",i=f.data(a,e,b,!0);i&&(d==="queue"||!f.data(a,g,b,!0))&&(d==="mark"||!f.data(a,h,b,!0))&&setTimeout(function(){!f.data(a,g,b,!0)&&!f.data(a,h,b,!0)&&(f.removeData(a,e,!0),i.resolve())},0)}function l(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function k(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(j,"$1-$2").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNaN(d)?i.test(d)?f.parseJSON(d):d:parseFloat(d)}catch(g){}f.data(a,c,d)}else d=b}return d}var c=a.document,d=a.navigator,e=a.location,f=function(){function H(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(H,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=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=d.userAgent,x,y,z,A=Object.prototype.toString,B=Object.prototype.hasOwnProperty,C=Array.prototype.push,D=Array.prototype.slice,E=String.prototype.trim,F=Array.prototype.indexOf,G={};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=n.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.6.1",length:0,size:function(){return this.length},toArray:function(){return D.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)?C.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(),y.done(a);return this},eq:function(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(D.apply(this,arguments),"slice",D.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:C,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;y.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!y){y=e._Deferred();if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",z,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",z),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&H()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNaN:function(a){return a==null||!m.test(a)||isNaN(a)},type:function(a){return a==null?String(a):G[A.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;if(a.constructor&&!B.call(a,"constructor")&&!B.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a);return c===b||B.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw 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(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(b,c,d){a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),d=c.documentElement,(!d||!d.nodeName||d.nodeName==="parsererror")&&e.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},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:E?function(a){return a==null?"":E.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)?C.call(c,a):e.merge(c,a)}return c},inArray:function(a,b){if(F)return F.call(b,a);for(var c=0,d=b.length;c<d;c++)if(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=D.call(arguments,2),g=function(){return a.apply(c,f.concat(D.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.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){G["[object "+b+"]"]=b.toLowerCase()}),x=e.uaMatch(w),x.browser&&(e.browser[x.browser]=!0,e.browser.version=x.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?z=function(){c.removeEventListener("DOMContentLoaded",z,!1),e.ready()}:c.attachEvent&&(z=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",z),e.ready())});return e}(),g="done fail isResolved isRejected promise then always pipe".split(" "),h=[].slice;f.extend({_Deferred:function(){var a=[],b,c,d,e={done:function(){if(!d){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=f.type(i),j==="array"?e.done.apply(e,i):j==="function"&&a.push(i);k&&e.resolveWith(k[0],k[1])}return this},resolveWith:function(e,f){if(!d&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(e,f)}finally{b=[e,f],c=0}}return this},resolve:function(){e.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){d=1,a=[];return this}};return e},Deferred:function(a){var b=f._Deferred(),c=f._Deferred(),d;f.extend(b,{then:function(a,c){b.done(a).fail(c);return this},always:function(){return b.done.apply(b,arguments).fail.apply(this,arguments)},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,pipe:function(a,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[c,"reject"]},function(a,c){var e=c[0],g=c[1],h;f.isFunction(e)?b[a](function(){h=e.apply(this,arguments),h&&f.isFunction(h.promise)?h.promise().then(d.resolve,d.reject):d[g](h)}):b[a](d[g])})}).promise()},promise:function(a){if(a==null){if(d)return d;d=a={}}var c=g.length;while(c--)a[g[c]]=b[g[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?h.call(arguments,0):c,--e||g.resolveWith(g,h.call(b,0))}}var b=arguments,c=0,d=b.length,e=d,g=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred();if(d>1){for(;c<d;c++)b[c]&&f.isFunction(b[c].promise)?b[c].promise().then(i(c),g.reject):--e;e||g.resolveWith(g,b)}else g!==a&&g.resolveWith(g,d?[a]:[]);return g.promise()}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;a.setAttribute("className","t"),a.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};f=c.createElement("select"),g=f.appendChild(c.createElement("option")),h=a.getElementsByTagName("input")[0],j={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.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:h.value==="on",optSelected:g.selected,getSetAttribute:a.className!=="t",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},h.checked=!0,j.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,j.optDisabled=!g.disabled;try{delete a.test}catch(s){j.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function b(){j.noCloneEvent=!1,a.detachEvent("onclick",b)}),a.cloneNode(!0).fireEvent("onclick")),h=c.createElement("input"),h.value="t",h.setAttribute("type","radio"),j.radioValue=h.value==="t",h.setAttribute("checked","checked"),a.appendChild(h),k=c.createDocumentFragment(),k.appendChild(a.firstChild),j.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",l=c.createElement("body"),m={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"};for(q in m)l.style[q]=m[q];l.appendChild(a),b.insertBefore(l,b.firstChild),j.appendChecked=h.checked,j.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,j.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",j.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",n=a.getElementsByTagName("td"),r=n[0].offsetHeight===0,n[0].style.display="",n[1].style.display="none",j.reliableHiddenOffsets=r&&n[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(i=c.createElement("div"),i.style.width="0",i.style.marginRight="0",a.appendChild(i),j.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(i,null)||{marginRight:0}).marginRight,10)||0)===0),l.innerHTML="",b.removeChild(l);if(a.attachEvent)for(q in{submit:1,change:1,focusin:1})p="on"+q,r=p in a,r||(a.setAttribute(p,"return;"),r=typeof a[p]=="function"),j[q+"Bubbles"]=r;return j}(),f.boxModel=f.support.boxModel;var i=/^(?:\{.*\}|\[.*\])$/,j=/([a-z])([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&&!l(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g=f.expando,h=typeof c=="string",i,j=a.nodeType,k=j?f.cache:a,l=j?a[f.expando]:a[f.expando]&&f.expando;if((!l||e&&l&&!k[l][g])&&h&&d===b)return;l||(j?a[f.expando]=l=++f.uuid:l=f.expando),k[l]||(k[l]={},j||(k[l].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?k[l][g]=f.extend(k[l][g],c):k[l]=f.extend(k[l],c);i=k[l],e&&(i[g]||(i[g]={}),i=i[g]),d!==b&&(i[f.camelCase(c)]=d);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[f.camelCase(c)]:i}},removeData:function(b,c,d){if(!!f.acceptData(b)){var e=f.expando,g=b.nodeType,h=g?f.cache:b,i=g?b[f.expando]:f.expando;if(!h[i])return;if(c){var j=d?h[i][e]:h[i];if(j){delete j[c];if(!l(j))return}}if(d){delete h[i][e];if(!l(h[i]))return}var k=h[i][e];f.support.deleteExpando||h!=a?delete h[i]:h[i]=null,k?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=k):g&&(f.support.deleteExpando?delete b[f.expando]:b.removeAttribute?b.removeAttribute(f.expando):b[f.expando]=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=null;if(typeof a=="undefined"){if(this.length){d=f.data(this[0]);if(this[0].nodeType===1){var e=this[0].attributes,g;for(var h=0,i=e.length;h<i;h++)g=e[h].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),k(this[0],g,d[g]))}}return d}if(typeof a=="object")return this.each(function(){f.data(this,a)});var j=a.split(".");j[1]=j[1]?"."+j[1]:"";if(c===b){d=this.triggerHandler("getData"+j[1]+"!",[j[0]]),d===b&&this.length&&(d=f.data(this[0],a),d=k(this[0],a,d));return d===b&&j[1]?this.data(j[0]):d}return this.each(function(){var b=f(this),d=[j[0],c];b.triggerHandler("setData"+j[1]+"!",d),f.data(this,a,c),b.triggerHandler("changeData"+j[1]+"!",d)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,c){a&&(c=(c||"fx")+"mark",f.data(a,c,(f.data(a,c,b,!0)||0)+1,!0))},_unmark:function(a,c,d){a!==!0&&(d=c,c=a,a=!1);if(c){d=d||"fx";var e=d+"mark",g=a?0:(f.data(c,e,b,!0)||1)-1;g?f.data(c,e,g,!0):(f.removeData(c,e,!0),m(c,d,"mark"))}},queue:function(a,c,d){if(a){c=(c||"fx")+"queue";var e=f.data(a,c,b,!0);d&&(!e||f.isArray(d)?e=f.data(a,c,f.makeArray(d),!0):e.push(d));return e||[]}},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"),d.call(a,function(){f.dequeue(a,b)})),c.length||(f.removeData(a,b+"queue",!0),m(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return 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(){var c=this;setTimeout(function(){f.dequeue(c,b)},a)})},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._Deferred(),!0))h++,l.done(m);m();return d.promise()}});var n=/[\n\t\r]/g,o=/\s+/,p=/\r/g,q=/^(?:button|input)$/i,r=/^(?:button|input|object|select|textarea)$/i,s=/^a(?:rea)?$/i,t=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,u=/\:/,v,w;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.addClass(a.call(this,b,c.attr("class")||""))});if(a&&typeof a=="string"){var b=(a||"").split(o);for(var c=0,d=this.length;c<d;c++){var e=this[c];if(e.nodeType===1)if(!e.className)e.className=a;else{var g=" "+e.className+" ",h=e.className;for(var i=0,j=b.length;i<j;i++)g.indexOf(" "+b[i]+" ")<0&&(h+=" "+b[i]);e.className=f.trim(h)}}}return this},removeClass:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a=="string"||a===b){var c=(a||"").split(o);for(var d=0,e=this.length;d<e;d++){var g=this[d];if(g.nodeType===1&&g.className)if(a){var h=(" "+g.className+" ").replace(n," ");for(var 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){var d=f(this);d.toggleClass(a.call(this,c,d.attr("class"),b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(o);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+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(n," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e=this[0];if(!arguments.length){if(e){c=f.valHooks[e.nodeName.toLowerCase()]||f.valHooks[e.type];if(c&&"get"in c&&(d=c.get(e,"value"))!==b)return d;return(e.value||"").replace(p,"")}return b}var g=f.isFunction(a);return this.each(function(d){var e=f(this),h;if(this.nodeType===1){g?h=a.call(this,d,e.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.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),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=a.selectedIndex,d=[],e=a.options,g=a.type==="select-one";if(c<0)return null;for(var h=g?c:0,i=g?c+1:e.length;h<i;h++){var j=e[h];if(j.selected&&(f.support.optDisabled?!j.disabled:j.getAttribute("disabled")===null)&&(!j.parentNode.disabled||!f.nodeName(j.parentNode,"optgroup"))){b=f(j).val();if(g)return b;d.push(b)}}if(g&&!d.length&&e.length)return f(e[c]).val();return d},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},attrFix:{tabindex:"tabIndex"},attr:function(a,c,d,e){var g=a.nodeType;if(!a||g===3||g===8||g===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);var h,i,j=g!==1||!f.isXMLDoc(a);c=j&&f.attrFix[c]||c,i=f.attrHooks[c],i||(!t.test(c)||typeof d!="boolean"&&d!==b&&d.toLowerCase()!==c.toLowerCase()?v&&(f.nodeName(a,"form")||u.test(c))&&(i=v):i=w);if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(i&&"set"in i&&j&&(h=i.set(a,d,c))!==b)return h;a.setAttribute(c,""+d);return d}if(i&&"get"in i&&j)return i.get(a,c);h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.support.getSetAttribute?a.removeAttribute(b):(f.attr(a,b,""),a.removeAttributeNode(a.getAttributeNode(b))),t.test(b)&&(c=f.propFix[b]||b)in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(q.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}}},tabIndex:{get:function(a){var c=a.getAttributeNode("tabIndex");return c&&c.specified?parseInt(c.value,10):r.test(a.nodeName)||s.test(a.nodeName)&&a.href?0: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=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);c=i&&f.propFix[c]||c,h=f.propHooks[c];return d!==b?h&&"set"in h&&(g=h.set(a,d,c))!==b?g:a[c]=d:h&&"get"in h&&(g=h.get(a,c))!==b?g:a[c]},propHooks:{}}),w={get:function(a,c){return a[f.propFix[c]||c]?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]=b),a.setAttribute(c,c.toLowerCase()));return c}},f.attrHooks.value={get:function(a,b){if(v&&f.nodeName(a,"button"))return v.get(a,b);return a.value},set:function(a,b,c){if(v&&f.nodeName(a,"button"))return v.set(a,b,c);a.value=b}},f.support.getSetAttribute||(f.attrFix=f.propFix,v=f.attrHooks.name=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?d.nodeValue:b},set:function(a,b,c){var d=a.getAttributeNode(c);if(d){d.nodeValue=b;return b}}},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.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)}})),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 x=Object.prototype.hasOwnProperty,y=/\.(.*)$/,z=/^(?:textarea|input|select)$/i,A=/\./g,B=/ /g,C=/[^\w\s.|`]/g,D=function(a){return a.replace(C,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=E;else if(!d)return;var g,h;d.handler&&(g=d,d=g.handler),d.guid||(d.guid=f.guid++);var i=f._data(a);if(!i)return;var j=i.events,k=i.handle;j||(i.events=j={}),k||(i.handle=k=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.handle.apply(k.elem,arguments):b}),k.elem=a,c=c.split(" ");var l,m=0,n;while(l=c[m++]){h=g?f.extend({},g):{handler:d,data:e},l.indexOf(".")>-1?(n=l.split("."),l=n.shift(),h.namespace=n.slice(0).sort().join(".")):(n=[],h.namespace=""),h.type=l,h.guid||(h.guid=d.guid);var o=j[l],p=f.event.special[l]||{};if(!o){o=j[l]=[];if(!p.setup||p.setup.call(a,e,n,k)===!1)a.addEventListener?a.addEventListener(l,k,!1):a.attachEvent&&a.attachEvent("on"+l,k)}p.add&&(p.add.call(a,h),h.handler.guid||(h.handler.guid=d.guid)),o.push(h),f.event.global[l]=!0}a=null}},global:{},remove:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){d===!1&&(d=E);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=f.hasData(a)&&f._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(d=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)f.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+f.map(m.slice(0).sort(),D).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!d){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))f.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=f.event.special[h]||{};for(j=e||0;j<p.length;j++){q=p[j];if(d.guid===q.guid){if(l||n.test(q.namespace))e==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(e!=null)break}}if(p.length===0||e!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&f.removeEvent(a,h,s.handle),g=null,delete t[h]}if(f.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,f.isEmptyObject(s)&&f.removeData(a,b,!0)}}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){var h=c.type||c,i=[],j;h.indexOf("!")>=0&&(h=h.slice(0,-1),j=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if(!!e&&!f.event.customEvent[h]||!!f.event.global[h]){c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.exclusive=j,c.namespace=i.join("."),c.namespace_re=new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)");if(g||!e)c.preventDefault(),c.stopPropagation();if(!e){f.each(f.cache,function(){var a=f.expando,b=this[a];b&&b.events&&b.events[h]&&f.event.trigger(c,d,b.handle.elem )});return}if(e.nodeType===3||e.nodeType===8)return;c.result=b,c.target=e,d=d?f.makeArray(d):[],d.unshift(c);var k=e,l=h.indexOf(":")<0?"on"+h:"";do{var m=f._data(k,"handle");c.currentTarget=k,m&&m.apply(k,d),l&&f.acceptData(k)&&k[l]&&k[l].apply(k,d)===!1&&(c.result=!1,c.preventDefault()),k=k.parentNode||k.ownerDocument||k===c.target.ownerDocument&&a}while(k&&!c.isPropagationStopped());if(!c.isDefaultPrevented()){var n,o=f.event.special[h]||{};if((!o._default||o._default.call(e.ownerDocument,c)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)){try{l&&e[h]&&(n=e[l],n&&(e[l]=null),f.event.triggered=h,e[h]())}catch(p){}n&&(e[l]=n),f.event.triggered=b}}return c.result}},handle:function(c){c=f.event.fix(c||a.event);var d=((f._data(this,"events")||{})[c.type]||[]).slice(0),e=!c.exclusive&&!c.namespace,g=Array.prototype.slice.call(arguments,0);g[0]=c,c.currentTarget=this;for(var h=0,i=d.length;h<i;h++){var j=d[h];if(e||c.namespace_re.test(j.namespace)){c.handler=j.handler,c.data=j.data,c.handleObj=j;var k=j.handler.apply(this,g);k!==b&&(c.result=k,k===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[f.expando])return a;var d=a;a=f.Event(d);for(var e=this.props.length,g;e;)g=this.props[--e],a[g]=d[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=a.target.ownerDocument||c,i=h.documentElement,j=h.body;a.pageX=a.clientX+(i&&i.scrollLeft||j&&j.scrollLeft||0)-(i&&i.clientLeft||j&&j.clientLeft||0),a.pageY=a.clientY+(i&&i.scrollTop||j&&j.scrollTop||0)-(i&&i.clientTop||j&&j.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:f.proxy,special:{ready:{setup:f.bindReady,teardown:f.noop},live:{add:function(a){f.event.add(this,O(a.origType,a.selector),f.extend({},a,{handler:N,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,O(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},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.preventDefault)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()?F:E):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=F;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=F;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=F,this.stopPropagation()},isDefaultPrevented:E,isPropagationStopped:E,isImmediatePropagationStopped:E};var G=function(a){var b=a.relatedTarget;a.type=a.data;try{if(b&&b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&f.event.handle.apply(this,arguments)}catch(d){}},H=function(a){a.type=a.data,f.event.handle.apply(this,arguments)};f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={setup:function(c){f.event.add(this,b,c&&c.selector?H:G,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?H:G)}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(a,b){if(!f.nodeName(this,"form"))f.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&f(b).closest("form").length&&L("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&L("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var I,J=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?f.map(a.options,function(a){return a.selected}).join("-"):"":f.nodeName(a,"select")&&(c=a.selectedIndex);return c},K=function(c){var d=c.target,e,g;if(!!z.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=J(d),(c.type!=="focusout"||d.type!=="radio")&&f._data(d,"_change_data",g);if(e===b||g===e)return;if(e!=null||g)c.type="change",c.liveFired=b,f.event.trigger(c,arguments[1],d)}};f.event.special.change={filters:{focusout:K,beforedeactivate:K,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&K.call(this,a)},keydown:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(a.keyCode===13&&!f.nodeName(b,"textarea")||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&K.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",J(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in I)f.event.add(this,c+".specialChange",I[c]);return z.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return z.test(this.nodeName)}},I=f.event.special.change.filters,I.focus=I.beforeactivate}f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){function e(a){var c=f.event.fix(a);c.type=b,c.originalEvent={},f.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var d=0;f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.each(["bind","one"],function(a,c){f.fn[c]=function(a,d,e){var g;if(typeof a=="object"){for(var h in a)this[c](h,d,a[h],e);return this}if(arguments.length===2||d===!1)e=d,d=b;c==="one"?(g=function(a){f(this).unbind(a,g);return e.apply(this,arguments)},g.guid=e.guid||f.guid++):g=e;if(a==="unload"&&c!=="one")this.one(a,d,e);else for(var i=0,j=this.length;i<j;i++)f.event.add(this[i],a,g,d);return this}}),f.fn.extend({unbind:function(a,b){if(typeof a=="object"&&!a.preventDefault)for(var c in a)this.unbind(c,a[c]);else for(var d=0,e=this.length;d<e;d++)f.event.remove(this[d],a,b);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},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)}});var M={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};f.each(["live","die"],function(a,c){f.fn[c]=function(a,d,e,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:f(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,d,a[o],m);return this}if(c==="die"&&!a&&g&&g.charAt(0)==="."){n.unbind(g);return this}if(d===!1||f.isFunction(d))e=d||E,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=y.exec(h),k="",j&&(k=j[0],h=h.replace(y,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,M[h]?(a.push(M[h]+k),h=h+k):h=(M[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+O(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+O(h,m),e)}return this}}),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".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d=0,e=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,f,g){f=f||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return f;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(e.call(n)==="[object Array]")if(!u)f.push.apply(f,n);else if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&f.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&f.push(j[t]);else p(n,f);o&&(k(o,h,f,g),k.uniqueSort(f));return f};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(!f)g=o=!0;else if(f===!0)continue}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.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&&!j.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&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!j.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&&k.filter(b,a,!0)}},"":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("parentNode",b,f,a,e,c)},"~":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("previousSibling",b,f,a,e,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(i,"")+" ";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(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.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]&&k.error(a[0]);a[0]=d++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),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]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.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!!k(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=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([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}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||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=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":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=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=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(q){p=function(a,b){var c=0,d=b||[];if(e.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var f=a.length;c<f;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){if(a===b){g=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return s(a,b);if(!h)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 s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=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}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},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)&&(l.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:[]}},l.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&&(l.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")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[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}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.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 k(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;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};f.find=k,f.expr=k.selectors,f.expr[":"]=f.expr.filters,f.unique=k.uniqueSort,f.text=k.getText,f.isXMLDoc=k.isXML,f.contains=k.contains}();var P=/Until$/,Q=/^(?:parents|prevUntil|prevAll)/,R=/,/,S=/^.[^:#\[\.,]*$/,T=Array.prototype.slice,U=f.expr.match.POS,V={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(X(this,a,!1),"not",a)},filter:function(a){return this.pushStack(X(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?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,i,j={},k=1;if(g&&a.length){for(d=0,e=a.length;d<e;d++)i=a[d],j[i]||(j[i]=U.test(i)?f(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:f(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=U.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(l?l.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||typeof a=="string")return f.inArray(this[0],a?f(a):this.parent().children());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(W(c[0])||W(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),g=T.call(arguments);P.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!V[a]?f.unique(e):e,(this.length>1||R.test(d))&&Q.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.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 Y=/ jQuery\d+="(?:\d+|null)"/g,Z=/^\s+/,$=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,_=/<([\w:]+)/,ba=/<tbody/i,bb=/<|&#?\w+;/,bc=/<(?:script|object|embed|option|style)/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,"",""]};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){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},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){return this.each(function(){f(this).wrapAll(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(arguments[0]);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(arguments[0]).toArray());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){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Y,""):null;if(typeof a=="string"&&!bc.test(a)&&(f.support.leadingWhitespace||!Z.test(a))&&!bg[(_.exec(a)||["",""])[1].toLowerCase()]){a=a.replace($,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},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?bh(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bn)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!bc.test(a[0])&&(f.support.checkClone||!bd.test(a[0]))&&(g=!0,h=f.fragments[a[0]],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[a[0]]=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=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bj(a,d),e=bk(a),g=bk(d);for(h=0;e[h];++h)bj(e[h],g[h])}if(b){bi(a,d);if(c){e=bk(a),g=bk(d);for(h=0;e[h];++h)bi(e[h],g[h])}}return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument|| b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!bb.test(k))k=b.createTextNode(k);else{k=k.replace($,"<$1></$2>");var l=(_.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=ba.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&Z.test(k)&&o.insertBefore(b.createTextNode(Z.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bm(k[i]);else bm(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.expando,g=f.event.special,h=f.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&f.noData[j.nodeName.toLowerCase()])continue;c=j[f.expando];if(c){b=d[c]&&d[c][e];if(b&&b.events){for(var k in b.events)g[k]?f.event.remove(j,k):f.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[f.expando]:j.removeAttribute&&j.removeAttribute(f.expando),delete d[c]}}}});var bo=/alpha\([^)]*\)/i,bp=/opacity=([^)]*)/,bq=/-([a-z])/ig,br=/([A-Z]|^ms)/g,bs=/^-?\d+(?:px)?$/i,bt=/^-?\d/,bu=/^[+\-]=/,bv=/[^+\-\.\de]+/g,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB,bC=function(a,b){return b.toUpperCase()};f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0,widows:!0,orphans:!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;if(h==="number"&&isNaN(d)||d==null)return;h==="string"&&bu.test(d)&&(d=+d.replace(bv,"")+parseFloat(f.css(a,c))),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(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bq,bC)}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){a.offsetWidth!==0?e=bD(a,b,d):f.swap(a,bw,function(){e=bD(a,b,d)});if(e<=0){e=bz(a,b,b),e==="0px"&&bB&&(e=bB(a,b,b));if(e!=null)return e===""||e==="auto"?"0px":e}if(e<0||e==null){e=a.style[b];return e===""||e==="auto"?"0px":e}return typeof e=="string"?e:e+"px"}},set:function(a,b){if(!bs.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bp.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;c.zoom=1;var e=f.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.filter=bo.test(g)?g.replace(bo,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,c){var d,e,g;c=c.replace(br,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bs.test(d)&&bt.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bz=bA||bB,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.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bE=/%20/g,bF=/\[\]$/,bG=/\r?\n/g,bH=/#.*$/,bI=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bJ=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bK=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,bL=/^(?:GET|HEAD)$/,bM=/^\/\//,bN=/\?/,bO=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bP=/^(?:select|textarea)/i,bQ=/\s+/,bR=/([?&])_=[^&]*/,bS=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bT=f.fn.load,bU={},bV={},bW,bX;try{bW=e.href}catch(bY){bW=c.createElement("a"),bW.href="",bW=bW.href}bX=bS.exec(bW.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bT)return bT.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(bO,"")).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||bP.test(this.nodeName)||bJ.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(bG,"\r\n")}}):{name:b.name,value:c.replace(bG,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(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?f.extend(!0,a,f.ajaxSettings,b):(b=a,a=f.extend(!0,f.ajaxSettings,b));for(var c in{context:1,url:1})c in b?a[c]=b[c]:c in f.ajaxSettings&&(a[c]=f.ajaxSettings[c]);return a},ajaxSettings:{url:bW,isLocal:bK.test(bX[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},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}},ajaxPrefilter:bZ(bU),ajaxTransport:bZ(bV),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?4:0;var o,r,u,w=l?ca(d,v,l):b,x,y;if(a>=200&&a<300||a===304){if(d.ifModified){if(x=v.getResponseHeader("Last-Modified"))f.lastModified[k]=x;if(y=v.getResponseHeader("Etag"))f.etag[k]=y}if(a===304)c="notmodified",o=!0;else try{r=cb(d,w),c="success",o=!0}catch(z){c="parsererror",u=z}}else{u=c;if(!c||a)c="error",a<0&&(a=0)}v.status=a,v.statusText=c,o?h.resolveWith(e,[r,c,v]):h.rejectWith(e,[v,c,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.resolveWith(e,[v,c]),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._Deferred(),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=bI.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.done,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(bH,"").replace(bM,bX[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bQ),d.crossDomain==null&&(r=bS.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bX[1]&&r[2]==bX[2]&&(r[3]||(r[1]==="http:"?80:443))==(bX[3]||(bX[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bU,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bL.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bN.test(d.url)?"&":"?")+d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bR,"$1_="+x);d.url=y+(y===d.url?(bN.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]!=="*"?", */*; 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=b$(bV,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){status<2?w(-1,z):f.error(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(bE,"+")}}),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=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";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),m.text=h.responseText;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,cr=a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("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._data(d,"olddisplay",cv(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(cu("hide",3),a,b,c);for(var d=0,e=this.length;d<e;d++)if(this[d].style){var g=f.css(this[d],"display");g!=="none"&&!f._data(this[d],"olddisplay")&&f._data(this[d],"olddisplay",g)}for(d=0;d<e;d++)this[d].style&&(this[d].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(cu("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){var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return this[e.queue===!1?"each":"queue"](function(){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;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),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?(j=cv(this.nodeName),j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)):this.style.display="inline-block"))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)k=new f.fx(this,b,i),h=a[i],cm.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=cn.exec(h),m=k.cur(),l?(n=parseFloat(l[2]),o=l[3]||(f.cssNumber[i]?"":"px"),o!=="px"&&(f.style(this,i,(n||1)+o),m=(n||1)/k.cur()*m,f.style(this,i,m+o)),l[1]&&(n=(l[1]==="-="?-1:1)*n+m),k.custom(m,n,o)):k.custom(m,h,""));return!0})},stop:function(a,b){a&&this.queue([]),this.each(function(){var a=f.timers,c=a.length;b||f._unmark(!0,this);while(c--)a[c].elem===this&&(b&&a[c](!0),a.splice(c,1))}),b||this.dequeue();return this}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("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,d.old=d.complete,d.complete=function(a){d.queue!==!1?f.dequeue(this):a!==!1&&f._unmark(this),f.isFunction(d.old)&&d.old.call(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},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,b,c){function h(a){return d.step(a)}var d=this,e=f.fx,g;this.startTime=cq||cs(),this.start=a,this.end=b,this.unit=c||this.unit||(f.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,h.elem=this.elem,h()&&f.timers.push(h)&&!co&&(cr?(co=1,g=function(){co&&(cr(g),e.tick())},cr(g)):co=setInterval(e.tick,e.interval))},show:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=cq||cs(),c=!0,d=this.elem,e=this.options,g,h;if(a||b>=e.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),e.animatedProperties[this.prop]=!0;for(g in e.animatedProperties)e.animatedProperties[g]!==!0&&(c=!1);if(c){e.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){d.style["overflow"+b]=e.overflow[a]}),e.hide&&f(d).hide();if(e.hide||e.show)for(var i in e.animatedProperties)f.style(d,i,e.orig[i]);e.complete.call(d)}return!1}e.duration==Infinity?this.now=b:(h=b-this.startTime,this.state=h/e.duration,this.pos=f.easing[e.animatedProperties[this.prop]](this.state,h,0,1,e.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){for(var a=f.timers,b=0;b<a.length;++b)a[b]()||a.splice(b--,1);a.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.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);f.offset.initialize();var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.offset.doesNotAddBorder&&(!f.offset.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={initialize:function(){var a=c.body,b=c.createElement("div"),d,e,g,h,i=parseFloat(f.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";f.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),d=b.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,this.doesNotAddBorder=e.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,e.style.position="fixed",e.style.top="20px",this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),f.offset.initialize=f.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.offset.initialize(),f.offset.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(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){return this[0]?parseFloat(f.css(this[0],d,"padding")):null},f.fn["outer"+c]=function(a){return this[0]?parseFloat(f.css(this[0],d,a?"margin":"border")):null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c];return e.document.compatMode==="CSS1Compat"&&g||e.document.body["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var h=f.css(e,d),i=parseFloat(h);return f.isNaN(i)?h:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
;(function() { function mrFactory(mobx, React, ReactDOM) { if (!mobx) throw new Error("mobx-react requires the MobX package") if (!React) throw new Error("mobx-react requires React to be available") var isDevtoolsEnabled = false // WeakMap<Node, Object>; var componentByNodeRegistery = typeof WeakMap !== "undefined" ? new WeakMap() : undefined var renderReporter = new mobx.SimpleEventEmitter() function findDOMNode(component) { if (ReactDOM) return ReactDOM.findDOMNode(component) return null } function reportRendering(component) { var node = findDOMNode(component) if (node) componentByNodeRegistery.set(node, component) renderReporter.emit({ event: "render", renderTime: component.__$mobRenderEnd - component.__$mobRenderStart, totalTime: Date.now() - component.__$mobRenderStart, component: component, node: node }) } var reactiveMixin = { componentWillMount: function() { // Generate friendly name for debugging var name = [ this.displayName || this.name || (this.constructor && this.constructor.name) || "<component>", "#", this._reactInternalInstance && this._reactInternalInstance._rootNodeID, ".render()" ].join("") var baseRender = this.render.bind(this) var self = this var reaction = null var isRenderingPending = false function initialRender() { reaction = new mobx.Reaction(name, function() { if (!isRenderingPending) { isRenderingPending = true React.Component.prototype.forceUpdate.call(self) } }) reactiveRender.$mobx = reaction self.render = reactiveRender return reactiveRender() } function reactiveRender() { isRenderingPending = false var rendering reaction.track(function() { if (isDevtoolsEnabled) self.__$mobRenderStart = Date.now() rendering = mobx.extras.allowStateChanges(false, baseRender) if (isDevtoolsEnabled) self.__$mobRenderEnd = Date.now() }) return rendering } this.render = initialRender }, componentWillUnmount: function() { this.render.$mobx && this.render.$mobx.dispose() if (isDevtoolsEnabled) { var node = findDOMNode(this) if (node) { componentByNodeRegistery.delete(node) } renderReporter.emit({ event: "destroy", component: this, node: node }) } }, componentDidMount: function() { if (isDevtoolsEnabled) reportRendering(this) }, componentDidUpdate: function() { if (isDevtoolsEnabled) reportRendering(this) }, shouldComponentUpdate: function(nextProps, nextState) { // TODO: if context changed, return true.., see #18 // if props or state did change, but a render was scheduled already, no additional render needs to be scheduled if (this.render.$mobx && this.render.$mobx.isScheduled() === true) return false // update on any state changes (as is the default) if (this.state !== nextState) return true // update if props are shallowly not equal, inspired by PureRenderMixin var keys = Object.keys(this.props) var key if (keys.length !== Object.keys(nextProps).length) return true for (var i = keys.length - 1; i >= 0, (key = keys[i]); i--) { var newValue = nextProps[key] if (newValue !== this.props[key]) { return true } else if ( newValue && typeof newValue === "object" && !mobx.isObservable(newValue) ) { /** * If the newValue is still the same object, but that object is not observable, * fallback to the default React behavior: update, because the object *might* have changed. * If you need the non default behavior, just use the React pure render mixin, as that one * will work fine with mobx as well, instead of the default implementation of * observer. */ return true } } return false } } function patch(target, funcName) { var base = target[funcName] var mixinFunc = reactiveMixin[funcName] target[funcName] = function() { base && base.apply(this, arguments) mixinFunc.apply(this, arguments) } } function observer(componentClass) { // If it is function but doesn't seem to be a react class constructor, // wrap it to a react class automatically if ( typeof componentClass === "function" && !componentClass.prototype.render && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass) ) { return observer( React.createClass({ displayName: componentClass.displayName || componentClass.name, propTypes: componentClass.propTypes, contextTypes: componentClass.contextTypes, getDefaultProps: function() { return componentClass.defaultProps }, render: function() { return componentClass.call(this, this.props, this.context) } }) ) } if (!componentClass) throw new Error("Please pass a valid component to 'observer'") var target = componentClass.prototype || componentClass ;[ "componentWillMount", "componentWillUnmount", "componentDidMount", "componentDidUpdate" ].forEach(function(funcName) { patch(target, funcName) }) if (!target.shouldComponentUpdate) target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate componentClass.isMobXReactObserver = true return componentClass } function trackComponents() { if (typeof WeakMap === "undefined") throw new Error( "[mobx-react] tracking components is not supported in this browser." ) if (!isDevtoolsEnabled) isDevtoolsEnabled = true } return { observer: observer, reactiveComponent: function() { console.warn( "[mobx-react] `reactiveComponent` has been renamed to `observer` and will be removed in 1.1." ) return observer.apply(null, arguments) }, renderReporter: renderReporter, componentByNodeRegistery: componentByNodeRegistery, trackComponents: trackComponents } } // UMD if (typeof define === "function" && define.amd) { define("mobx-react", ["mobx", "react", "react-dom"], mrFactory) } else if (typeof exports === "object") { module.exports = mrFactory(require("mobx"), require("react"), require("react-dom")) } else { this.mobxReact = mrFactory(this["mobx"], this["React"], this["ReactDOM"]) } })()
'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var invariant = require('fbjs/lib/invariant'); var react = require('react'); var objectAssign$1 = require('object-assign'); var require$$0 = require('fbjs/lib/warning'); var emptyFunction = require('fbjs/lib/emptyFunction'); var propTypes = require('prop-types'); var emptyObject = require('fbjs/lib/emptyObject'); var hyphenateStyleName = require('fbjs/lib/hyphenateStyleName'); var memoizeStringOnly = require('fbjs/lib/memoizeStringOnly'); var checkPropTypes = require('prop-types/checkPropTypes'); var camelizeStyleName = require('fbjs/lib/camelizeStyleName'); /** * Copyright (c) 2013-present, 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 reactProdInvariant * */ function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : void 0; { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in true. * * autofocus is predefined, because adding it to the property whitelist * causes unintended side effects. * * @type {Object} */ getPossibleStandardName: { autofocus: 'autoFocus' }, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; var DOMProperty_1 = DOMProperty; /** * Copyright 2016-present, 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. * * Based on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @providesModule escapeTextContentForBrowser */ // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } var escapeTextContentForBrowser_1 = escapeTextContentForBrowser; /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser_1(value) + '"'; } var quoteAttributeValueForBrowser_1 = quoteAttributeValueForBrowser; { var warning$1 = require$$0; } // isAttributeNameSafe() is currently duplicated in DOMPropertyOperations. // TODO: Find a better place for this. var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty_1.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty_1.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; { warning$1(false, 'Invalid attribute name: `%s`', attributeName); } return false; } // shouldIgnoreValue() is currently duplicated in DOMPropertyOperations. // TODO: Find a better place for this. function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMMarkupOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty_1.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser_1(id); }, createMarkupForRoot: function () { return DOMProperty_1.ROOT_ATTRIBUTE_NAME + '=""'; }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty_1.properties.hasOwnProperty(name) ? DOMProperty_1.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser_1(value); } else if (DOMProperty_1.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser_1(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser_1(value); } }; var DOMMarkupOperations_1 = DOMMarkupOperations; var ReactControlledValuePropTypes = { checkPropTypes: null }; { var warning$2 = require$$0; var emptyFunction$1 = emptyFunction; var PropTypes = propTypes; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; ReactControlledValuePropTypes.checkPropTypes = emptyFunction$1; var hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true }; var propTypes$1 = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: PropTypes.func }; var loggedTypeFailures = {}; /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ ReactControlledValuePropTypes.checkPropTypes = function (tagName, props, getStack) { for (var propName in propTypes$1) { if (propTypes$1.hasOwnProperty(propName)) { var error = propTypes$1[propName](props, propName, tagName, 'prop', null, ReactPropTypesSecret); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; warning$2(false, 'Failed form propType: %s%s', error.message, getStack()); } } }; } var ReactControlledValuePropTypes_1 = ReactControlledValuePropTypes; /** * Copyright 2013-present, 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 omittedCloseTags */ // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }; var omittedCloseTags_1 = omittedCloseTags; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = objectAssign$1({ menuitem: true }, omittedCloseTags_1); var voidElementTags_1 = voidElementTags; { var warning$3 = require$$0; } var HTML = '__html'; function getDeclarationErrorAddendum(getCurrentOwnerName) { { var ownerName = getCurrentOwnerName(); if (ownerName) { // TODO: also report the stack. return '\n\nThis DOM node was rendered by `' + ownerName + '`.'; } } return ''; } function assertValidProps(tag, props, getCurrentOwnerName) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags_1[tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', tag, getDeclarationErrorAddendum(getCurrentOwnerName)) : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : void 0; } { warning$3(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); warning$3(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.'); warning$3(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); } !(props.style == null || typeof props.style === 'object') ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(getCurrentOwnerName)) : void 0; } var assertValidProps_1 = assertValidProps; /** * Copyright 2013-present, 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 CSSProperty */ /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber$1 = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, columns: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridRowEnd: true, gridRowSpan: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnSpan: true, gridColumnStart: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber$1).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber$1[prefixKey(prefix, prop)] = isUnitlessNumber$1[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber$1, shorthandPropertyExpansions: shorthandPropertyExpansions }; var CSSProperty_1 = CSSProperty; var isUnitlessNumber = CSSProperty_1.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, isCustomProperty) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) { return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers } return ('' + value).trim(); } var dangerousStyleValue_1 = dangerousStyleValue; /** * Copyright 2013-present, 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 getComponentName * */ function getComponentName$2(instanceOrFiber) { if (typeof instanceOrFiber.getName === 'function') { // Stack reconciler var instance = instanceOrFiber; return instance.getName(); } if (typeof instanceOrFiber.tag === 'number') { // Fiber reconciler var fiber = instanceOrFiber; var type = fiber.type; if (typeof type === 'string') { return type; } if (typeof type === 'function') { return type.displayName || type.name; } } return null; } var getComponentName_1 = getComponentName$2; var ReactInternals = react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var ReactGlobalSharedState = { ReactCurrentOwner: ReactInternals.ReactCurrentOwner }; { objectAssign$1(ReactGlobalSharedState, { ReactComponentTreeHook: ReactInternals.ReactComponentTreeHook, ReactDebugCurrentFrame: ReactInternals.ReactDebugCurrentFrame }); } var ReactGlobalSharedState_1 = ReactGlobalSharedState; /** * Copyright 2013-present, 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 ReactTypeOfWork * */ var ReactTypeOfWork = { IndeterminateComponent: 0, // Before we know whether it is functional or class FunctionalComponent: 1, ClassComponent: 2, HostRoot: 3, // Root of a host tree. Could be nested inside another node. HostPortal: 4, // A subtree. Could be an entry point to a different renderer. HostComponent: 5, HostText: 6, CoroutineComponent: 7, CoroutineHandlerPhase: 8, YieldComponent: 9, Fragment: 10 }; /** * Copyright 2016-present, 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 describeComponentFrame */ var describeComponentFrame$1 = function (name, source, ownerName) { return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); }; var IndeterminateComponent = ReactTypeOfWork.IndeterminateComponent; var FunctionalComponent = ReactTypeOfWork.FunctionalComponent; var ClassComponent = ReactTypeOfWork.ClassComponent; var HostComponent = ReactTypeOfWork.HostComponent; function describeFiber(fiber) { switch (fiber.tag) { case IndeterminateComponent: case FunctionalComponent: case ClassComponent: case HostComponent: var owner = fiber._debugOwner; var source = fiber._debugSource; var name = getComponentName_1(fiber); var ownerName = null; if (owner) { ownerName = getComponentName_1(owner); } return describeComponentFrame$1(name, source, ownerName); default: return ''; } } // This function can only be called with a work-in-progress fiber and // only during begin or complete phase. Do not call it under any other // circumstances. function getStackAddendumByWorkInProgressFiber$1(workInProgress) { var info = ''; var node = workInProgress; do { info += describeFiber(node); // Otherwise this return pointer might point to the wrong tree: node = node['return']; } while (node); return info; } var ReactFiberComponentTreeHook = { getStackAddendumByWorkInProgressFiber: getStackAddendumByWorkInProgressFiber$1 }; var ReactDebugCurrentFrame$1 = ReactGlobalSharedState_1.ReactDebugCurrentFrame; { var getComponentName$3 = getComponentName_1; var _require2$1 = ReactFiberComponentTreeHook, getStackAddendumByWorkInProgressFiber = _require2$1.getStackAddendumByWorkInProgressFiber; } function getCurrentFiberOwnerName$1() { { var fiber = ReactDebugCurrentFiber.current; if (fiber === null) { return null; } if (fiber._debugOwner != null) { return getComponentName$3(fiber._debugOwner); } } return null; } function getCurrentFiberStackAddendum() { { var fiber = ReactDebugCurrentFiber.current; if (fiber === null) { return null; } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. return getStackAddendumByWorkInProgressFiber(fiber); } return null; } function resetCurrentFiber() { ReactDebugCurrentFrame$1.getCurrentStack = null; ReactDebugCurrentFiber.current = null; ReactDebugCurrentFiber.phase = null; } function setCurrentFiber(fiber, phase) { ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackAddendum; ReactDebugCurrentFiber.current = fiber; ReactDebugCurrentFiber.phase = phase; } var ReactDebugCurrentFiber = { current: null, phase: null, resetCurrentFiber: resetCurrentFiber, setCurrentFiber: setCurrentFiber, getCurrentFiberOwnerName: getCurrentFiberOwnerName$1, getCurrentFiberStackAddendum: getCurrentFiberStackAddendum }; var ReactDebugCurrentFiber_1 = ReactDebugCurrentFiber; var warnValidStyle$1 = emptyFunction; { var camelizeStyleName$1 = camelizeStyleName; var getComponentName$1 = getComponentName_1; var warning$4 = require$$0; var _require$1 = ReactDebugCurrentFiber_1, getCurrentFiberOwnerName = _require$1.getCurrentFiberOwnerName; // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnedForInfinityValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; warning$4(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName$1(name), checkRenderMessage(owner)); }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; warning$4(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)); }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; warning$4(false, "Style property values shouldn't contain a semicolon.%s " + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')); }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; warning$4(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)); }; var warnStyleValueIsInfinity = function (name, value, owner) { if (warnedForInfinityValue) { return; } warnedForInfinityValue = true; warning$4(false, '`Infinity` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)); }; var checkRenderMessage = function (owner) { var ownerName; if (owner != null) { // Stack passes the owner manually all the way to CSSPropertyOperations. ownerName = getComponentName$1(owner); } else { // Fiber doesn't pass it but uses ReactDebugCurrentFiber to track it. // It is only enabled in development and tracks host components too. ownerName = getCurrentFiberOwnerName(); // TODO: also report the stack. } if (ownerName) { return '\n\nCheck the render method of `' + ownerName + '`.'; } return ''; }; warnValidStyle$1 = function (name, value, component) { var owner; if (component) { // TODO: this only works with Stack. Seems like we need to add unit tests? owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number') { if (isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } else if (!isFinite(value)) { warnStyleValueIsInfinity(name, value, owner); } } }; } var warnValidStyle_1 = warnValidStyle$1; var warnedProperties = {}; var rARIA = new RegExp('^(aria)-[' + DOMProperty_1.ATTRIBUTE_NAME_CHAR + ']*$'); { var warning$5 = require$$0; var _require$2 = ReactGlobalSharedState_1, ReactComponentTreeHook = _require$2.ReactComponentTreeHook, ReactDebugCurrentFrame$2 = _require$2.ReactDebugCurrentFrame; var getStackAddendumByID = ReactComponentTreeHook.getStackAddendumByID; } function getStackAddendum$1(debugID) { if (debugID != null) { // This can only happen on Stack return getStackAddendumByID(debugID); } else { // This can only happen on Fiber / Server var stack = ReactDebugCurrentFrame$2.getStackAddendum(); return stack != null ? stack : ''; } } function validateProperty(tagName, name, debugID) { if (warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (rARIA.test(name)) { var lowerCasedName = name.toLowerCase(); var standardName = DOMProperty_1.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty_1.getPossibleStandardName[lowerCasedName] : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (standardName == null) { warnedProperties[name] = true; return false; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== standardName) { warning$5(false, 'Unknown ARIA attribute %s. Did you mean %s?%s', name, standardName, getStackAddendum$1(debugID)); warnedProperties[name] = true; return true; } } return true; } function warnInvalidARIAProps(type, props, debugID) { var invalidProps = []; for (var key in props) { var isValid = validateProperty(type, key, debugID); if (!isValid) { invalidProps.push(key); } } var unknownPropString = invalidProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (invalidProps.length === 1) { warning$5(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, type, getStackAddendum$1(debugID)); } else if (invalidProps.length > 1) { warning$5(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, type, getStackAddendum$1(debugID)); } } function validateProperties(type, props, debugID /* Stack only */) { if (type.indexOf('-') >= 0 || props.is) { return; } warnInvalidARIAProps(type, props, debugID); } var ReactDOMInvalidARIAHook = { // Fiber validateProperties: validateProperties, // Stack onBeforeMountComponent: function (debugID, element) { if (true && element != null && typeof element.type === 'string') { validateProperties(element.type, element.props, debugID); } }, onBeforeUpdateComponent: function (debugID, element) { if (true && element != null && typeof element.type === 'string') { validateProperties(element.type, element.props, debugID); } } }; var ReactDOMInvalidARIAHook_1 = ReactDOMInvalidARIAHook; { var warning$6 = require$$0; var _require$3 = ReactGlobalSharedState_1, ReactComponentTreeHook$1 = _require$3.ReactComponentTreeHook, ReactDebugCurrentFrame$3 = _require$3.ReactDebugCurrentFrame; var getStackAddendumByID$1 = ReactComponentTreeHook$1.getStackAddendumByID; } var didWarnValueNull = false; function getStackAddendum$2(debugID) { if (debugID != null) { // This can only happen on Stack return getStackAddendumByID$1(debugID); } else { // This can only happen on Fiber / Server var stack = ReactDebugCurrentFrame$3.getStackAddendum(); return stack != null ? stack : ''; } } function validateProperties$1(type, props, debugID /* Stack only */) { if (type !== 'input' && type !== 'textarea' && type !== 'select') { return; } if (props != null && props.value === null && !didWarnValueNull) { warning$6(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', type, getStackAddendum$2(debugID)); didWarnValueNull = true; } } var ReactDOMNullInputValuePropHook = { // Fiber validateProperties: validateProperties$1, // Stack onBeforeMountComponent: function (debugID, element) { if (true && element != null && typeof element.type === 'string') { validateProperties$1(element.type, element.props, debugID); } }, onBeforeUpdateComponent: function (debugID, element) { if (true && element != null && typeof element.type === 'string') { validateProperties$1(element.type, element.props, debugID); } } }; var ReactDOMNullInputValuePropHook_1 = ReactDOMNullInputValuePropHook; /** * Injectable ordering of event plugins. */ var eventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, pluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, pluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in true. * @type {Object} */ possibleRegistrationNames: {}, // Trust the developer to only use possibleRegistrationNames in true /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (injectedEventPluginOrder) { !!eventPluginOrder ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : void 0; // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { !!namesToPlugins[pluginName] ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0; namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } } }; var EventPluginRegistry_1 = EventPluginRegistry; { var warning$7 = require$$0; var _require$4 = ReactGlobalSharedState_1, ReactComponentTreeHook$2 = _require$4.ReactComponentTreeHook, ReactDebugCurrentFrame$4 = _require$4.ReactDebugCurrentFrame; var getStackAddendumByID$2 = ReactComponentTreeHook$2.getStackAddendumByID; } function getStackAddendum$3(debugID) { if (debugID != null) { // This can only happen on Stack return getStackAddendumByID$2(debugID); } else { // This can only happen on Fiber / Server var stack = ReactDebugCurrentFrame$4.getStackAddendum(); return stack != null ? stack : ''; } } { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, defaultChecked: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true }; var warnedProperties$1 = {}; var EVENT_NAME_REGEX = /^on[A-Z]/; var validateProperty$1 = function (tagName, name, debugID) { if (DOMProperty_1.properties.hasOwnProperty(name) || DOMProperty_1.isCustomAttribute(name)) { return true; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties$1.hasOwnProperty(name) && warnedProperties$1[name]) { return true; } if (EventPluginRegistry_1.registrationNameModules.hasOwnProperty(name)) { return true; } if (EventPluginRegistry_1.plugins.length === 0 && EVENT_NAME_REGEX.test(name)) { // If no event plugins have been injected, we might be in a server environment. // Don't check events in this case. return true; } warnedProperties$1[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty_1.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty_1.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty_1.getPossibleStandardName[lowerCasedName] : null; var registrationName = EventPluginRegistry_1.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry_1.possibleRegistrationNames[lowerCasedName] : null; if (standardName != null) { warning$7(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, getStackAddendum$3(debugID)); return true; } else if (registrationName != null) { warning$7(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, getStackAddendum$3(debugID)); return true; } else { // We were unable to guess which prop the user intended. // It is likely that the user was just blindly spreading/forwarding props // Components should be careful to only render valid props/attributes. // Warning will be invoked in warnUnknownProperties to allow grouping. return false; } }; } var warnUnknownProperties = function (type, props, debugID) { var unknownProps = []; for (var key in props) { var isValid = validateProperty$1(type, key, debugID); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { warning$7(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, type, getStackAddendum$3(debugID)); } else if (unknownProps.length > 1) { warning$7(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, type, getStackAddendum$3(debugID)); } }; function validateProperties$2(type, props, debugID /* Stack only */) { if (type.indexOf('-') >= 0 || props.is) { return; } warnUnknownProperties(type, props, debugID); } var ReactDOMUnknownPropertyHook = { // Fiber validateProperties: validateProperties$2, // Stack onBeforeMountComponent: function (debugID, element) { if (true && element != null && typeof element.type === 'string') { validateProperties$2(element.type, element.props, debugID); } }, onBeforeUpdateComponent: function (debugID, element) { if (true && element != null && typeof element.type === 'string') { validateProperties$2(element.type, element.props, debugID); } } }; var ReactDOMUnknownPropertyHook_1 = ReactDOMUnknownPropertyHook; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var toArray = react.Children.toArray; { var warning = require$$0; var checkPropTypes$1 = checkPropTypes; var warnValidStyle = warnValidStyle_1; var _require = ReactDOMInvalidARIAHook_1, validateARIAProperties = _require.validateProperties; var _require2 = ReactDOMNullInputValuePropHook_1, validateInputPropertes = _require2.validateProperties; var _require3 = ReactDOMUnknownPropertyHook_1, validateUnknownPropertes = _require3.validateProperties; var validatePropertiesInDevelopment = function (type, props) { validateARIAProperties(type, props); validateInputPropertes(type, props); validateUnknownPropertes(type, props); }; var describeComponentFrame = describeComponentFrame$1; var describeStackFrame = function (element) { var source = element._source; var type = element.type; var name = getComponentName(type); var ownerName = null; return describeComponentFrame(name, source, ownerName); }; var _require4 = ReactGlobalSharedState_1, ReactDebugCurrentFrame = _require4.ReactDebugCurrentFrame; var currentDebugStack = null; var currentDebugElementStack = null; var setCurrentDebugStack = function (stack) { currentDebugElementStack = stack[stack.length - 1].debugElementStack; // We are about to enter a new composite stack, reset the array. currentDebugElementStack.length = 0; currentDebugStack = stack; ReactDebugCurrentFrame.getCurrentStack = getStackAddendum; }; var pushElementToDebugStack = function (element) { if (currentDebugElementStack !== null) { currentDebugElementStack.push(element); } }; var resetCurrentDebugStack = function () { currentDebugElementStack = null; currentDebugStack = null; ReactDebugCurrentFrame.getCurrentStack = null; }; var getStackAddendum = function () { if (currentDebugStack === null) { return null; } var stack = ''; var debugStack = currentDebugStack; for (var i = debugStack.length - 1; i >= 0; i--) { var debugElementStack = debugStack[i].debugElementStack; for (var ii = debugElementStack.length - 1; ii >= 0; ii--) { stack += describeStackFrame(debugElementStack[ii]); } } return stack; }; } var didWarnDefaultInputValue = false; var didWarnDefaultChecked = false; var didWarnDefaultSelectValue = false; var didWarnDefaultTextareaValue = false; var didWarnInvalidOptionChildren = false; var valuePropNames = ['value', 'defaultValue']; var newlineEatingTags = { listing: true, pre: true, textarea: true }; function getComponentName(type) { return typeof type === 'string' ? type : typeof type === 'function' ? type.displayName || type.name : null; } // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; function validateDangerousTag(tag) { if (!validatedTagCache.hasOwnProperty(tag)) { !VALID_TAG_REGEX.test(tag) ? invariant(false, 'Invalid tag: %s', tag) : void 0; validatedTagCache[tag] = true; } } var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); function createMarkupForStyles(styles, component) { var serialized = ''; var delimiter = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var isCustomProperty = styleName.indexOf('--') === 0; var styleValue = styles[styleName]; { if (!isCustomProperty) { warnValidStyle(styleName, styleValue, component); } } if (styleValue != null) { serialized += delimiter + processStyleName(styleName) + ':'; serialized += dangerousStyleValue_1(styleName, styleValue, isCustomProperty); delimiter = ';'; } } return serialized || null; } function warnNoop(publicInstance, callerName) { { var constructor = publicInstance.constructor; warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, constructor && getComponentName(constructor) || 'ReactClass'); } } function shouldConstruct(Component) { return Component.prototype && Component.prototype.isReactComponent; } function getNonChildrenInnerMarkup(props) { var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return innerHTML.__html; } } else { var content = props.children; if (typeof content === 'string' || typeof content === 'number') { return escapeTextContentForBrowser_1(content); } } return null; } function flattenOptionChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. react.Children.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { { if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; warning(false, 'Only strings and numbers are supported as <option> children.'); } } } }); return content; } function maskContext(type, context) { var contextTypes = type.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; } function checkContextTypes(typeSpecs, values, location) { { checkPropTypes$1(typeSpecs, values, location, 'Component', getStackAddendum); } } function processContext(type, context) { var maskedContext = maskContext(type, context); { if (type.contextTypes) { checkContextTypes(type.contextTypes, maskedContext, 'context'); } } return maskedContext; } var STYLE = 'style'; var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } function createOpenTagMarkup(tagVerbatim, tagLowercase, props, makeStaticMarkup, isRootElement, instForDebug) { var ret = '<' + tagVerbatim; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (propKey === STYLE) { propValue = createMarkupForStyles(propValue, instForDebug); } var markup = null; if (isCustomComponent(tagLowercase, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMMarkupOperations_1.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMMarkupOperations_1.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (makeStaticMarkup) { return ret; } if (isRootElement) { ret += ' ' + DOMMarkupOperations_1.createMarkupForRoot(); } return ret; } function validateRenderResult(child, type) { if (child === undefined) { invariant(false, '%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.', getComponentName(type) || 'Component'); } } function resolve(child, context) { while (react.isValidElement(child)) { { pushElementToDebugStack(child); } var Component = child.type; if (typeof Component !== 'function') { break; } var publicContext = processContext(Component, context); var inst; var queue = []; var replace = false; var updater = { isMounted: function (publicInstance) { return false; }, enqueueForceUpdate: function (publicInstance) { if (queue === null) { warnNoop(publicInstance, 'forceUpdate'); return null; } }, enqueueReplaceState: function (publicInstance, completeState) { replace = true; queue = [completeState]; }, enqueueSetState: function (publicInstance, partialState) { if (queue === null) { warnNoop(publicInstance, 'setState'); return null; } queue.push(partialState); } }; if (shouldConstruct(Component)) { inst = new Component(child.props, publicContext, updater); } else { inst = Component(child.props, publicContext, updater); if (inst == null || inst.render == null) { child = inst; validateRenderResult(child, Component); continue; } } inst.props = child.props; inst.context = publicContext; inst.updater = updater; var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } if (inst.componentWillMount) { inst.componentWillMount(); if (queue.length) { var oldQueue = queue; var oldReplace = replace; queue = null; replace = false; if (oldReplace && oldQueue.length === 1) { inst.state = oldQueue[0]; } else { var nextState = oldReplace ? oldQueue[0] : inst.state; var dontMutate = true; for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { var partial = oldQueue[i]; var partialState = typeof partial === 'function' ? partial.call(inst, nextState, child.props, publicContext) : partial; if (partialState) { if (dontMutate) { dontMutate = false; nextState = objectAssign$1({}, nextState, partialState); } else { objectAssign$1(nextState, partialState); } } } inst.state = nextState; } } else { queue = null; } } child = inst.render(); { if (child === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. child = null; } } validateRenderResult(child, Component); var childContext; if (typeof inst.getChildContext === 'function') { var childContextTypes = Component.childContextTypes; !(typeof childContextTypes === 'object') ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', getComponentName(Component) || 'Unknown') : void 0; childContext = inst.getChildContext(); for (var contextKey in childContext) { !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(Component) || 'Unknown', contextKey) : void 0; } } if (childContext) { context = objectAssign$1({}, context, childContext); } } return { child: child, context: context }; } var ReactDOMServerRenderer = function () { function ReactDOMServerRenderer(element, makeStaticMarkup) { _classCallCheck(this, ReactDOMServerRenderer); var children = react.isValidElement(element) ? [element] : toArray(element); var topFrame = { children: children, childIndex: 0, context: emptyObject, footer: '' }; { topFrame.debugElementStack = []; } this.stack = [topFrame]; this.exhausted = false; this.currentSelectValue = null; this.previousWasTextNode = false; this.makeStaticMarkup = makeStaticMarkup; } ReactDOMServerRenderer.prototype.read = function read(bytes) { if (this.exhausted) { return null; } var out = ''; while (out.length < bytes) { if (this.stack.length === 0) { this.exhausted = true; break; } var frame = this.stack[this.stack.length - 1]; if (frame.childIndex >= frame.children.length) { out += frame.footer; this.previousWasTextNode = false; this.stack.pop(); if (frame.tag === 'select') { this.currentSelectValue = null; } continue; } var child = frame.children[frame.childIndex++]; { setCurrentDebugStack(this.stack); } out += this.render(child, frame.context); { // TODO: Handle reentrant server render calls. This doesn't. resetCurrentDebugStack(); } } return out; }; ReactDOMServerRenderer.prototype.render = function render(child, context) { if (typeof child === 'string' || typeof child === 'number') { var text = '' + child; if (text === '') { return ''; } if (this.makeStaticMarkup) { return escapeTextContentForBrowser_1(text); } if (this.previousWasTextNode) { return '<!-- -->' + escapeTextContentForBrowser_1(text); } this.previousWasTextNode = true; return escapeTextContentForBrowser_1(text); } else { var _resolve = resolve(child, context); child = _resolve.child; context = _resolve.context; if (child === null || child === false) { return ''; } else { if (react.isValidElement(child)) { return this.renderDOM(child, context); } else { var children = toArray(child); var frame = { children: children, childIndex: 0, context: context, footer: '' }; { frame.debugElementStack = []; } this.stack.push(frame); return ''; } } } }; ReactDOMServerRenderer.prototype.renderDOM = function renderDOM(element, context) { var tag = element.type.toLowerCase(); { warning(tag === element.type, '<%s /> is using uppercase HTML. Always use lowercase HTML tags ' + 'in React.', element.type); } validateDangerousTag(tag); var props = element.props; if (tag === 'input') { { ReactControlledValuePropTypes_1.checkPropTypes('input', props, function () { return ''; }); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) { warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type); didWarnDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) { warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type); didWarnDefaultInputValue = true; } } props = objectAssign$1({ type: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: props.value != null ? props.value : props.defaultValue, checked: props.checked != null ? props.checked : props.defaultChecked }); } else if (tag === 'textarea') { { ReactControlledValuePropTypes_1.checkPropTypes('textarea', props, function () { return ''; }); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) { warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components'); didWarnDefaultTextareaValue = true; } } var initialValue = props.value; if (initialValue == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var textareaChildren = props.children; if (textareaChildren != null) { { warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.'); } !(defaultValue == null) ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : void 0; if (Array.isArray(textareaChildren)) { !(textareaChildren.length <= 1) ? invariant(false, '<textarea> can only have at most one child.') : void 0; textareaChildren = textareaChildren[0]; } defaultValue = '' + textareaChildren; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } props = objectAssign$1({}, props, { value: undefined, children: '' + initialValue }); } else if (tag === 'select') { { ReactControlledValuePropTypes_1.checkPropTypes('select', props, function () { return ''; }); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, ''); } else if (!props.multiple && isArray) { warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, ''); } } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) { warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components'); didWarnDefaultSelectValue = true; } } this.currentSelectValue = props.value != null ? props.value : props.defaultValue; props = objectAssign$1({}, props, { value: undefined }); } else if (tag === 'option') { var selected = null; var selectValue = this.currentSelectValue; var optionChildren = flattenOptionChildren(props.children); if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { value = optionChildren; } selected = false; if (Array.isArray(selectValue)) { // multiple for (var j = 0; j < selectValue.length; j++) { if ('' + selectValue[j] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } props = objectAssign$1({ selected: undefined, children: undefined }, props, { selected: selected, children: optionChildren }); } } { validatePropertiesInDevelopment(tag, props); } assertValidProps_1(tag, props); var out = createOpenTagMarkup(element.type, tag, props, this.makeStaticMarkup, this.stack.length === 1, null); var footer = ''; if (omittedCloseTags_1.hasOwnProperty(tag)) { out += '/>'; } else { out += '>'; footer = '</' + element.type + '>'; } var children; var innerMarkup = getNonChildrenInnerMarkup(props); if (innerMarkup != null) { children = []; if (newlineEatingTags[tag] && innerMarkup.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> out += '\n'; } out += innerMarkup; } else { children = toArray(props.children); } var frame = { tag: tag, children: children, childIndex: 0, context: context, footer: footer }; { frame.debugElementStack = []; } this.stack.push(frame); return out; }; return ReactDOMServerRenderer; }(); var ReactPartialRenderer = ReactDOMServerRenderer; /** * Copyright 2013-present, 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 ReactFeatureFlags * */ var ReactFeatureFlags = { disableNewFiberFeatures: false, enableAsyncSubtreeAPI: false }; var ReactFeatureFlags_1 = ReactFeatureFlags; /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://facebook.github.io/react/docs/react-dom-server.html#rendertostring */ function renderToString(element) { var disableNewFiberFeatures = ReactFeatureFlags_1.disableNewFiberFeatures; if (disableNewFiberFeatures) { !react.isValidElement(element) ? invariant(false, 'renderToString(): Invalid component element.') : void 0; } var renderer = new ReactPartialRenderer(element, false); var markup = renderer.read(Infinity); return markup; } /** * Similar to renderToString, except this doesn't create extra DOM attributes * such as data-react-id that React uses internally. * See https://facebook.github.io/react/docs/react-dom-server.html#rendertostaticmarkup */ function renderToStaticMarkup(element) { var disableNewFiberFeatures = ReactFeatureFlags_1.disableNewFiberFeatures; if (disableNewFiberFeatures) { !react.isValidElement(element) ? invariant(false, 'renderToStaticMarkup(): Invalid component element.') : void 0; } var renderer = new ReactPartialRenderer(element, true); var markup = renderer.read(Infinity); return markup; } var ReactDOMStringRenderer = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; /** * Copyright 2013-present, 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 ReactVersion */ var ReactVersion = '16.0.0-beta.4'; /** * Copyright 2013-present, 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 ARIADOMPropertyConfig */ var ARIADOMPropertyConfig = { Properties: { // Global States and Properties 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }, DOMAttributeNames: {}, DOMPropertyNames: {} }; var ARIADOMPropertyConfig_1 = ARIADOMPropertyConfig; var MUST_USE_PROPERTY = DOMProperty_1.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty_1.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty_1.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty_1.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty_1.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty_1.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, // specifies target context for links with `preload` type as: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, controlsList: 0, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, playsInline: HAS_BOOLEAN_VALUE, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, // support for projecting regular DOM Elements via V1 named slots ( shadow dom ) slot: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {}, DOMMutationMethods: { value: function (node, value) { if (value == null) { return node.removeAttribute('value'); } // Number inputs get special treatment due to some edge cases in // Chrome. Let everything else assign the value attribute as normal. // https://github.com/facebook/react/issues/7253#issuecomment-236074326 if (node.type !== 'number' || node.hasAttribute('value') === false) { node.setAttribute('value', '' + value); } else if (node.validity && !node.validity.badInput && node.ownerDocument.activeElement !== node) { // Don't assign an attribute if validation reports bad // input. Chrome will clear the value. Additionally, don't // operate on inputs that have focus, otherwise Chrome might // strip off trailing decimal places and cause the user's // cursor position to jump to the beginning of the input. // // In ReactDOMInput, we have an onBlur event that will trigger // this function again when focus is lost. node.setAttribute('value', '' + value); } } } }; var HTMLDOMPropertyConfig_1 = HTMLDOMPropertyConfig; /** * Copyright 2013-present, 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 SVGDOMPropertyConfig */ var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlns: 0, xmlnsXlink: 'xmlns:xlink', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); var SVGDOMPropertyConfig_1 = SVGDOMPropertyConfig; DOMProperty_1.injection.injectDOMPropertyConfig(ARIADOMPropertyConfig_1); DOMProperty_1.injection.injectDOMPropertyConfig(HTMLDOMPropertyConfig_1); DOMProperty_1.injection.injectDOMPropertyConfig(SVGDOMPropertyConfig_1); var ReactDOMServerBrowserEntry = { renderToString: ReactDOMStringRenderer.renderToString, renderToStaticMarkup: ReactDOMStringRenderer.renderToStaticMarkup, renderToStream: function () { invariant(false, 'ReactDOMServer.renderToStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToString() instead.'); }, renderToStaticStream: function () { invariant(false, 'ReactDOMServer.renderToStaticStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.'); }, version: ReactVersion }; module.exports = ReactDOMServerBrowserEntry; })(); }
(function() { "use strict"; var ember$data$lib$system$adapter$$get = Ember.get; var ember$data$lib$system$adapter$$errorProps = [ 'description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack' ]; /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. For Ember Data to correctly map errors to their corresponding properties on the model, Ember Data expects each error to be namespaced under a key that matches the property name. For example if you had a Post model that looked like this. ```js App.Post = DS.Model.extend({ title: DS.attr('string'), content: DS.attr('string') }); ``` To show an error from the server related to the `title` and `content` properties your adapter could return a promise that rejects with a `DS.InvalidError` object that looks like this: ```js App.PostAdapter = DS.RESTAdapter.extend({ updateRecord: function() { // Fictional adapter that always rejects return Ember.RSVP.reject(new DS.InvalidError({ title: ['Must be unique'], content: ['Must not be blank'], })); } }); ``` Your backend may use different property names for your records the store will attempt extract and normalize the errors using the serializer's `extractErrors` method before the errors get added to the the model. As a result, it is safe for the `InvalidError` to wrap the error payload unaltered. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); // 422 is used by this fictional server to signal a validation error if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText); return new DS.InvalidError(jsonErrors); } else { // The ajax request failed however it is not a result of this // record being in an invalid state so we do not return a // `InvalidError` object. return error; } } }); ``` @class InvalidError @namespace DS */ function ember$data$lib$system$adapter$$InvalidError(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=ember$data$lib$system$adapter$$errorProps.length; i<l; i++) { this[ember$data$lib$system$adapter$$errorProps[i]] = tmp[ember$data$lib$system$adapter$$errorProps[i]]; } } ember$data$lib$system$adapter$$InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter Create a new subclass of `DS.Adapter`, then assign it to the `ApplicationAdapter` property of the application. ```javascript var MyAdapter = DS.Adapter.extend({ // ...your code here }); App.ApplicationAdapter = MyAdapter; ``` Model-specific adapters can be created by assigning your adapter class to the `ModelName` + `Adapter` property of the application. ```javascript var MyPostAdapter = DS.Adapter.extend({ // ...Post-specific adapter code goes here }); App.PostAdapter = MyPostAdapter; ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `findQuery()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ var ember$data$lib$system$adapter$$Adapter = Ember.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority than a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```javascript var DjangoAdapter = DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: ```javascript App.ApplicationAdapter = DS.Adapter.extend({ find: function(store, type, id, snapshot) { var url = [type.typeKey, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ find: null, /** The `findAll()` method is called when you call `find` on the store without an ID (i.e. `store.find('post')`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: null, /** This method is called when you call `find` on the store with a query object as the second parameter (i.e. `store.find('person', { page: 1 })`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findQuery: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript generateIdForRecord: function(store, inputProperties) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @method generateIdForRecord @param {DS.Store} store @param {Object} inputProperties a hash of properties to set on the newly created record. @return {String|Number} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Model} record @param {Object} options @return {Object} serialized record */ serialize: function(record, options) { var snapshot = record._createSnapshot(); return ember$data$lib$system$adapter$$get(record, 'store').serializerFor(snapshot.typeKey).serialize(snapshot, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: null, /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ updateRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: null, /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ deleteRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: null, /** By default the store will try to coalesce all `fetchRecord` calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: true, /** Find multiple records at once if coalesceFindRequests is true @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids @param {Array} snapshots @return {Promise} promise */ /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. For example, if your api has nested URLs that depend on the parent, you will want to group records by their parent. The default implementation returns the records as a single group. @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function(store, snapshots) { return [snapshots]; } }); var ember$data$lib$system$adapter$$default = ember$data$lib$system$adapter$$Adapter; var ember$data$lib$adapters$fixture$adapter$$get = Ember.get; var ember$data$lib$adapters$fixture$adapter$$fmt = Ember.String.fmt; var ember$data$lib$adapters$fixture$adapter$$indexOf = Ember.EnumerableUtils.indexOf; var ember$data$lib$adapters$fixture$adapter$$counter = 0; var ember$data$lib$adapters$fixture$adapter$$default = ember$data$lib$system$adapter$$default.extend({ // by default, fixtures are already in normalized form serializer: null, // The fixture adapter does not support coalesceFindRequests coalesceFindRequests: false, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {Subclass of DS.Model} type @return {Array} */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture) { var fixtureIdType = typeof fixture.id; if (fixtureIdType !== "number" && fixtureIdType !== "string") { throw new Error(ember$data$lib$adapters$fixture$adapter$$fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixture @param {Object} query @param {Subclass of DS.Model} type @return {Promise|Array} */ queryFixtures: function(fixtures, query, type) { Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); }, /** @method updateFixtures @param {Subclass of DS.Model} type @param {Array} fixture */ updateFixtures: function(type, fixture) { if (!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {DS.Store} store @param {Subclass of DS.Model} type @param {DS.Snapshot} snapshot */ mockJSON: function(store, type, snapshot) { return store.serializerFor(snapshot.typeKey).serialize(snapshot, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String} id */ generateIdForRecord: function(store) { return "fixture-" + ember$data$lib$adapters$fixture$adapter$$counter++; }, /** @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ find: function(store, type, id, snapshot) { var fixtures = this.fixturesForType(type); var fixture; Ember.assert("Unable to find fixtures for model type "+type.toString() +". If you're defining your fixtures using `Model.FIXTURES = ...`, please change it to `Model.reopenClass({ FIXTURES: ... })`.", fixtures); if (fixtures) { fixture = Ember.A(fixtures).findBy('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function(store, type, ids, snapshots) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); if (fixtures) { fixtures = fixtures.filter(function(item) { return ember$data$lib$adapters$fixture$adapter$$indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type " + type.toString(), fixtures); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function(store, type, snapshot) { var fixture = this.mockJSON(store, type, snapshot); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function(store, type, snapshot) { var fixture = this.mockJSON(store, type, snapshot); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function(store, type, snapshot) { this.deleteLoadedFixture(type, snapshot); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param snapshot */ deleteLoadedFixture: function(type, snapshot) { var existingFixture = this.findExistingFixture(type, snapshot); if (existingFixture) { var index = ember$data$lib$adapters$fixture$adapter$$indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param snapshot */ findExistingFixture: function(type, snapshot) { var fixtures = this.fixturesForType(type); var id = snapshot.id; return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if (''+ember$data$lib$adapters$fixture$adapter$$get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { var value = Ember.copy(callback.call(context), true); if (ember$data$lib$adapters$fixture$adapter$$get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(value); }, ember$data$lib$adapters$fixture$adapter$$get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule('actions', null, function() { resolve(value); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); var ember$data$lib$system$map$$Map = Ember.Map; var ember$data$lib$system$map$$MapWithDefault = Ember.MapWithDefault; var ember$data$lib$system$map$$default = ember$data$lib$system$map$$Map; var ember$data$lib$adapters$build$url$mixin$$get = Ember.get; var ember$data$lib$adapters$build$url$mixin$$default = Ember.Mixin.create({ /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. When called by RESTAdapter.findMany() the `id` and `snapshot` parameters will be arrays of ids and snapshots. @method buildURL @param {String} type @param {String|Array} id single id or array of ids @param {DS.Snapshot|Array} snapshot single snapshot or array of snapshots @return {String} url */ buildURL: function(type, id, snapshot) { var url = []; var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host'); var prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } //We might get passed in an array of ids from findMany //in which case we don't want to modify the url, as the //ids will be passed in through a query param if (id && !Ember.isArray(id)) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, /** @method urlPrefix @private @param {String} path @param {String} parentUrl @return {String} urlPrefix */ urlPrefix: function(path, parentURL) { var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host'); var namespace = ember$data$lib$adapters$build$url$mixin$$get(this, 'namespace'); var url = []; if (path) { // Protocol relative url //jscs:disable disallowEmptyBlocks if (/^\/\//.test(path)) { // Do nothing, the full host is already included. This branch // avoids the absolute path logic and the relative path logic. // Absolute path } else if (path.charAt(0) === '/') { //jscs:enable disallowEmptyBlocks if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} type @return {String} path **/ pathForType: function(type) { var camelized = Ember.String.camelize(type); return Ember.String.pluralize(camelized); } }); var ember$data$lib$adapters$rest$adapter$$get = Ember.get; var ember$data$lib$adapters$rest$adapter$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$adapters$rest$adapter$$default = ember$data$lib$system$adapter$$Adapter.extend(ember$data$lib$adapters$build$url$mixin$$default, { defaultSerializer: '-rest', /** By default, the RESTAdapter will send the query params sorted alphabetically to the server. For example: ```js store.find('posts', {sort: 'price', category: 'pets'}); ``` will generate a requests like this `/posts?category=pets&sort=price`, even if the parameters were specified in a different order. That way the generated URL will be deterministic and that simplifies caching mechanisms in the backend. Setting `sortQueryParams` to a falsey value will respect the original order. In case you want to sort the query parameters with a different criteria, set `sortQueryParams` to your custom sort function. ```js export default DS.RESTAdapter.extend({ sortQueryParams: function(params) { var sortedKeys = Object.keys(params).sort().reverse(); var len = sortedKeys.length, newParams = {}; for (var i = 0; i < len; i++) { newParams[sortedKeys[i]] = params[sortedKeys[i]]; } return newParams; } }); ``` @method sortQueryParams @param {Object} obj @return {Object} */ sortQueryParams: function(obj) { var keys = Ember.keys(obj); var len = keys.length; if (len < 2) { return obj; } var newQueryParams = {}; var sortedKeys = keys.sort(); for (var i = 0; i < len; i++) { newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; } return newQueryParams; }, /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.find('comment', 1); store.find('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```javascript DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```javascript DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ find: function(store, type, id, snapshot) { return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ findQuery: function(store, type, query) { if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function(store, type, ids, snapshots) { return this.ajax(this.buildURL(type.typeKey, ids, snapshots), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. If the URL is host-relative (starting with a single slash), the request will use the host specified on the adapter (if any). @method findHasMany @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findHasMany: function(store, snapshot, url, relationship) { var host = ember$data$lib$adapters$rest$adapter$$get(this, 'host'); var id = snapshot.id; var type = snapshot.typeKey; if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') { url = host + url; } return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findBelongsTo: function(store, snapshot, url, relationship) { var id = snapshot.id; var type = snapshot.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function(store, type, snapshot) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(this.buildURL(type.typeKey, null, snapshot), "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function(store, type, snapshot) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, snapshot); var id = snapshot.id; return this.ajax(this.buildURL(type.typeKey, id, snapshot), "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function(store, type, snapshot) { var id = snapshot.id; return this.ajax(this.buildURL(type.typeKey, id, snapshot), "DELETE"); }, _stripIDFromURL: function(store, snapshot) { var url = this.buildURL(snapshot.typeKey, snapshot.id, snapshot); var expandedURL = url.split('/'); //Case when the url is of the format ...something/:id var lastSegment = expandedURL[expandedURL.length - 1]; var id = snapshot.id; if (lastSegment === id) { expandedURL[expandedURL.length - 1] = ""; } else if (ember$data$lib$adapters$rest$adapter$$endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers maxUrlLength: 2048, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, snapshots) { var groups = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function() { return []; } }); var adapter = this; var maxUrlLength = this.maxUrlLength; ember$data$lib$adapters$rest$adapter$$forEach.call(snapshots, function(snapshot) { var baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxUrlLength, paramNameLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; ember$data$lib$adapters$rest$adapter$$forEach.call(group, function(snapshot) { var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; if (baseUrl.length + idsSize + additionalLength >= maxUrlLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(snapshot); }); return splitGroups; } var groupsArray = []; groups.forEach(function(group, key) { var paramNameLength = '&ids%5B%5D='.length; var splitGroups = splitGroupToFitInUrl(group, maxUrlLength, paramNameLength); ember$data$lib$adapters$rest$adapter$$forEach.call(splitGroups, function(splitGroup) { groupsArray.push(splitGroup); }); }); return groupsArray; }, /** Takes an ajax response, and returns an error payload. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. When returning an `InvalidError` the store will attempt to normalize the error data returned from the server using the serializer's `extractErrors` method. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText); return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` Note: As a correctness optimization, the default implementation of the `ajaxError` method strips out the `then` method from jquery's ajax response (jqXHR). This is important because the jqXHR's `then` method fulfills the promise with itself resulting in a circular "thenable" chain which may cause problems for some promise libraries. @method ajaxError @param {Object} jqXHR @param {Object} responseText @param {Object} errorThrown @return {Object} jqXHR */ ajaxError: function(jqXHR, responseText, errorThrown) { var isObject = jqXHR !== null && typeof jqXHR === 'object'; if (isObject) { jqXHR.then = null; if (!jqXHR.errorThrown) { if (typeof errorThrown === 'string') { jqXHR.errorThrown = new Error(errorThrown); } else { jqXHR.errorThrown = errorThrown; } } } return jqXHR; }, /** Takes an ajax response, and returns the json payload. By default this hook just returns the jsonPayload passed to it. You might want to override it in two cases: 1. Your API might return useful results in the request headers. If you need to access these, you can override this hook to copy them from jqXHR to the payload object so they can be processed in you serializer. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a DS.InvalidError from this hook and it will automatically reject the promise and put your record into the invalid state. @method ajaxSuccess @param {Object} jqXHR @param {Object} jsonPayload @return {Object} jsonPayload */ ajaxSuccess: function(jqXHR, jsonPayload) { return jsonPayload; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Promise} promise */ ajax: function(url, type, options) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function(json, textStatus, jqXHR) { json = adapter.ajaxSuccess(jqXHR, json); if (json instanceof ember$data$lib$system$adapter$$InvalidError) { Ember.run(null, reject, json); } else { Ember.run(null, resolve, json); } }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR, jqXHR.responseText, errorThrown)); }; Ember.$.ajax(hash); }, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions: function(url, type, options) { var hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = ember$data$lib$adapters$rest$adapter$$get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { ember$data$lib$adapters$rest$adapter$$forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; } }); //From http://stackoverflow.com/questions/280634/endswith-in-javascript function ember$data$lib$adapters$rest$adapter$$endsWith(string, suffix) { if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } var ember$lib$main$$default = self.Ember; var ember$inflector$lib$lib$system$inflector$$capitalize = ember$lib$main$$default.String.capitalize; var ember$inflector$lib$lib$system$inflector$$BLANK_REGEX = /^\s*$/; var ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX = /(\w+[_-])([a-z\d]+$)/; var ember$inflector$lib$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX = /(\w+)([A-Z][a-z\d]*$)/; var ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; function ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function ember$inflector$lib$lib$system$inflector$$loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; //pluralizing rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregular[pair[1].toLowerCase()] = pair[1]; //singularizing rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; rules.irregularInverse[pair[0].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow'); //=> 'kine' inflector.singularize('kine'); //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice'); // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice'); // => 'advice' inflector.pluralize('formula'); // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula'); // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function ember$inflector$lib$lib$system$inflector$$Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || ember$inflector$lib$lib$system$inflector$$makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || ember$inflector$lib$lib$system$inflector$$makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: ember$inflector$lib$lib$system$inflector$$makeDictionary(), irregularInverse: ember$inflector$lib$lib$system$inflector$$makeDictionary(), uncountable: ember$inflector$lib$lib$system$inflector$$makeDictionary() }; ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, ruleSet.uncountable); ember$inflector$lib$lib$system$inflector$$loadIrregular(rules, ruleSet.irregularPairs); this.enableCache(); } if (!Object.create && !Object.create(null).hasOwnProperty) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } function ember$inflector$lib$lib$system$inflector$$makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } ember$inflector$lib$lib$system$inflector$$Inflector.prototype = { /** @public As inflections can be costly, and commonly the same subset of words are repeatedly inflected an optional cache is provided. @method enableCache */ enableCache: function() { this.purgeCache(); this.singularize = function(word) { this._cacheUsed = true; return this._sCache[word] || (this._sCache[word] = this._singularize(word)); }; this.pluralize = function(word) { this._cacheUsed = true; return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); }; }, /** @public @method purgedCache */ purgeCache: function() { this._cacheUsed = false; this._sCache = ember$inflector$lib$lib$system$inflector$$makeDictionary(); this._pCache = ember$inflector$lib$lib$system$inflector$$makeDictionary(); }, /** @public disable caching @method disableCache; */ disableCache: function() { this._sCache = null; this._pCache = null; this.singularize = function(word) { return this._singularize(word); }; this.pluralize = function(word) { return this._pluralize(word); }; }, /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { if (this._cacheUsed) { this.purgeCache(); } ember$inflector$lib$lib$system$inflector$$loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { if (this._cacheUsed) { this.purgeCache(); } ember$inflector$lib$lib$system$inflector$$loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this._pluralize(word); }, _pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this._singularize(word); }, _singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, isUncountable, isIrregular, rule; isBlank = ember$inflector$lib$lib$system$inflector$$BLANK_REGEX.test(word); isCamelized = ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX.test(word); firstPhrase = ""; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX.exec(word) || ember$inflector$lib$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX.exec(word); if (wordSplit){ firstPhrase = wordSplit[1]; lastWord = wordSplit[2].toLowerCase(); } isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; if (isUncountable) { return word; } isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]); if (isIrregular) { if (irregular[lowercase]){ return isIrregular; } else { isIrregular = (isCamelized) ? ember$inflector$lib$lib$system$inflector$$capitalize(isIrregular) : isIrregular; return firstPhrase + isIrregular; } } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; var ember$inflector$lib$lib$system$inflector$$default = ember$inflector$lib$lib$system$inflector$$Inflector; function ember$inflector$lib$lib$system$string$$pluralize(word) { return ember$inflector$lib$lib$system$inflector$$default.inflector.pluralize(word); } function ember$inflector$lib$lib$system$string$$singularize(word) { return ember$inflector$lib$lib$system$inflector$$default.inflector.singularize(word); } var ember$inflector$lib$lib$system$inflections$$default = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; ember$inflector$lib$lib$system$inflector$$default.inflector = new ember$inflector$lib$lib$system$inflector$$default(ember$inflector$lib$lib$system$inflections$$default); function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, helperFunction) { //earlier versions of ember with htmlbars used this ember$lib$main$$default.HTMLBars.helpers[name] = helperFunction; } function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, helperFunction) { //registerHelper has been made private as _registerHelper //this is kept here if anyone is using it ember$lib$main$$default.HTMLBars.registerHelper(name, helperFunction); } function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, helperFunction) { //latest versin of ember uses this ember$lib$main$$default.HTMLBars._registerHelper(name, helperFunction); } function ember$inflector$lib$lib$utils$register$helper$$registerHelper(name, helperFunction) { if (ember$lib$main$$default.HTMLBars) { var fn = ember$lib$main$$default.HTMLBars.makeBoundHelper(helperFunction); if (ember$lib$main$$default.HTMLBars._registerHelper) { if (ember$lib$main$$default.HTMLBars.helpers) { ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, fn); } else { ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, fn); } } else if (ember$lib$main$$default.HTMLBars.registerHelper) { ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, fn); } } else if (ember$lib$main$$default.Handlebars) { ember$lib$main$$default.Handlebars.helper(name, helperFunction); } } var ember$inflector$lib$lib$utils$register$helper$$default = ember$inflector$lib$lib$utils$register$helper$$registerHelper; /** * * If you have Ember Inflector (such as if Ember Data is present), * singularize a word. For example, turn "oxen" into "ox". * * Example: * * {{singularize myProperty}} * {{singularize "oxen"}} * * @for Ember.HTMLBars.helpers * @method singularize * @param {String|Property} word word to singularize */ ember$inflector$lib$lib$utils$register$helper$$default('singularize', function(params){ return ember$inflector$lib$lib$system$string$$singularize(params[0]); }); /** * * If you have Ember Inflector (such as if Ember Data is present), * pluralize a word. For example, turn "ox" into "oxen". * * Example: * * {{pluralize count myProperty}} * {{pluralize 1 "oxen"}} * {{pluralize myProperty}} * {{pluralize "ox"}} * * @for Ember.HTMLBars.helpers * @method pluralize * @param {Number|Property} [count] count of objects * @param {String|Property} word word to pluralize */ ember$inflector$lib$lib$utils$register$helper$$default('pluralize', function(params) { var count, word; if (params.length === 1) { word = params[0]; return ember$inflector$lib$lib$system$string$$pluralize(word); } else { count = params[0]; word = params[1]; if (count !== 1) { word = ember$inflector$lib$lib$system$string$$pluralize(word); } return count + " " + word; } }); if (ember$lib$main$$default.EXTEND_PROTOTYPES === true || ember$lib$main$$default.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return ember$inflector$lib$lib$system$string$$pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return ember$inflector$lib$lib$system$string$$singularize(this); }; } ember$inflector$lib$lib$system$inflector$$default.defaultRules = ember$inflector$lib$lib$system$inflections$$default; ember$lib$main$$default.Inflector = ember$inflector$lib$lib$system$inflector$$default; ember$lib$main$$default.String.pluralize = ember$inflector$lib$lib$system$string$$pluralize; ember$lib$main$$default.String.singularize = ember$inflector$lib$lib$system$string$$singularize; var ember$inflector$lib$main$$default = ember$inflector$lib$lib$system$inflector$$default; if (typeof define !== 'undefined' && define.amd){ define('ember-inflector', ['exports'], function(__exports__){ __exports__['default'] = ember$inflector$lib$lib$system$inflector$$default; return ember$inflector$lib$lib$system$inflector$$default; }); } else if (typeof module !== 'undefined' && module['exports']){ module['exports'] = ember$inflector$lib$lib$system$inflector$$default; } /** @module ember-data */ var activemodel$adapter$lib$system$active$model$adapter$$decamelize = Ember.String.decamelize; var activemodel$adapter$lib$system$active$model$adapter$$underscore = Ember.String.underscore; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active\_model\_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers, `embed :ids, embed_in_root: true` which sideloads the records. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. Unlike the DS.RESTAdapter, async relationship keys must be the singular form of the relationship name, followed by "_id" for DS.belongsTo relationships, or "_ids" for DS.hasMany relationships. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.RESTAdapter **/ var activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter = ember$data$lib$adapters$rest$adapter$$default.extend({ defaultSerializer: '-active-model', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @return String */ pathForType: function(type) { var decamelized = activemodel$adapter$lib$system$active$model$adapter$$decamelize(type); var underscored = activemodel$adapter$lib$system$active$model$adapter$$underscore(decamelized); return ember$inflector$lib$lib$system$string$$pluralize(underscored); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param {Object} jqXHR @return error */ ajaxError: function(jqXHR) { var error = this._super.apply(this, arguments); if (jqXHR && jqXHR.status === 422) { return new ember$data$lib$system$adapter$$InvalidError(Ember.$.parseJSON(jqXHR.responseText)); } else { return error; } } }); var activemodel$adapter$lib$system$active$model$adapter$$default = activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter; var ember$data$lib$system$serializer$$Serializer = Ember.Object.extend({ /** The `store` property is the application's `store` that contains all records. It's injected as a service. It can be used to push records from a non flat data structure server response. @property store @type {DS.Store} @public */ /** The `extract` method is used to deserialize the payload received from your data source into the form that Ember Data expects. @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} */ extract: null, /** The `serialize` method is used when a record is saved in order to convert the record into the form that your external data source expects. `serialize` takes an optional `options` hash with a single option: - `includeId`: If this is `true`, `serialize` should include the ID in the serialized object it builds. @method serialize @param {subclass of DS.Model} record @param {Object} [options] @return {Object} */ serialize: null, /** The `normalize` method is used to convert a payload received from your external data source into the normalized form `store.push()` expects. You should override this method, munge the hash and return the normalized payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { return hash; } }); var ember$data$lib$system$serializer$$default = ember$data$lib$system$serializer$$Serializer; var ember$data$lib$serializers$json$serializer$$get = Ember.get; var ember$data$lib$serializers$json$serializer$$isNone = Ember.isNone; var ember$data$lib$serializers$json$serializer$$map = Ember.ArrayPolyfills.map; var ember$data$lib$serializers$json$serializer$$merge = Ember.merge; var ember$data$lib$serializers$json$serializer$$default = ember$data$lib$system$serializer$$default.extend({ /** The primaryKey is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the primaryKey property to match the primaryKey of your external store. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** The `attrs` object can be used to declare a simple mapping between property names on `DS.Model` records and payload keys in the serialized JSON object representing the record. An object with the property `key` can also be used to designate the attribute's key on the response payload. Example ```javascript App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); App.PersonSerializer = DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: {key: 'career'} } }); ``` You can also remove attributes by setting the `serialize` key to false in your mapping object. Example ```javascript App.PersonSerializer = DS.JSONSerializer.extend({ attrs: { admin: {serialize: false}, occupation: {key: 'career'} } }); ``` When serialized: ```javascript { "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {subclass of DS.Model} type @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(type, data) { type.eachTransformedAttribute(function applyTransform(key, type) { if (!data.hasOwnProperty(key)) { return; } var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ normalize: function(type, hash) { var fields = Ember.get(type, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { if (!hash) { return hash; } this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); this.applyTransforms(type, hash); return hash; }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.JSONSerializer.extend({ normalizePayload: function(payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {Object} payload @return {Object} the normalized payload */ normalizePayload: function(payload) { return payload; }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs'); var payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = this._getMappedKey(key); if (!hash.hasOwnProperty(payloadKey)) { continue; } if (payloadKey !== key) { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = ember$data$lib$serializers$json$serializer$$get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** @method normalizeErrors @private */ normalizeErrors: function(type, hash) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); }, /** Looks up the property key that was set by the custom `attr` mapping passed to the serializer. @method _getMappedKey @private @param {String} key @return {String} key */ _getMappedKey: function(key) { var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs'); var mappedKey; if (attrs && attrs[key]) { mappedKey = attrs[key]; //We need to account for both the {title: 'post_title'} and //{title: {key: 'post_title'}} forms if (mappedKey.key) { mappedKey = mappedKey.key; } if (typeof mappedKey === 'string') { key = mappedKey; } } return key; }, /** Check attrs.key.serialize property to inform if the `key` can be serialized @method _canSerialize @private @param {String} key @return {boolean} true if the key can be serialized */ _canSerialize: function(key) { var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs'); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```javascript App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function(snapshot, options) { var json = {}; if (options && options.includeId) { var id = snapshot.id; if (id) { json[ember$data$lib$serializers$json$serializer$$get(this, 'primaryKey')] = id; } } snapshot.eachAttribute(function(key, attribute) { this.serializeAttribute(snapshot, json, key, attribute); }, this); snapshot.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(snapshot, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(snapshot, json, relationship); } }, this); return json; }, /** You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, snapshot, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(snapshot, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function(hash, type, snapshot, options) { ember$data$lib$serializers$json$serializer$$merge(hash, this.serialize(snapshot, options)); }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all your attributes were always serialized as properties on an `attributes` object you could write: ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serializeAttribute: function(snapshot, json, key, attributes) { json.attributes = json.attributes || {}; this._super(snapshot, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function(snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key); } json[payloadKey] = value; } }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeBelongsTo: function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsToId = snapshot.belongsTo(key, { id: true }); // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo"); } //Need to check whether the id is there for new&async records if (ember$data$lib$serializers$json$serializer$$isNone(belongsToId)) { json[payloadKey] = null; } else { json[payloadKey] = belongsToId; } if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeHasMany: function(snapshot, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function(snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var payloadKey; // if provided, use the mapping provided by `attrs` in // the serializer payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany"); } var relationshipType = snapshot.type.determineRelationshipType(relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[payloadKey] = snapshot.hasMany(key, { ids: true }); // TODO support for polymorphic manyToNone and manyToMany relationships } } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{polymorphic: true}` is pass as the second argument to the `DS.belongsTo` function. Example ```javascript App.CommentSerializer = DS.JSONSerializer.extend({ serializePolymorphicType: function(snapshot, json, relationship) { var key = relationship.key, belongsTo = snapshot.belongsTo(key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; if (Ember.isNone(belongsTo)) { json[key + "_type"] = null; } else { json[key + "_type"] = belongsTo.typeKey; } } }); ``` @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method delegates to a more specific extract method based on the `requestType`. To override this method with a custom one, make sure to call `return this._super(store, type, payload, id, requestType)` with your pre-processed data. Here's an example of using `extract` manually: ```javascript socket.on('message', function(message) { var data = message.data; var type = store.modelFor(message.modelName); var serializer = store.serializerFor(type.typeKey); var record = serializer.extract(store, type, data, data.id, 'single'); store.push(message.modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindAll: function(store, type, payload, id, requestType) { return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindQuery: function(store, type, payload, id, requestType) { return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindMany: function(store, type, payload, id, requestType) { return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindHasMany: function(store, type, payload, id, requestType) { return this.extractArray(store, type, payload, id, requestType); }, /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Model#save` and the record is new. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractCreateRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Model#save` and the record has been updated. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractUpdateRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Model#save` and the record has been deleted. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractDeleteRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFind: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFindBelongsTo: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractSave: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractSingle: function(store, type, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, type, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractSingle: function(store, type, payload, id, requestType) { payload = this.normalizePayload(payload); return this.normalize(type, payload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, type, payload) { return payload.map(function(json) { return this.extractSingle(store, type, json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractArray: function(store, type, arrayPayload, id, requestType) { var normalizedPayload = this.normalizePayload(arrayPayload); var serializer = this; return ember$data$lib$serializers$json$serializer$$map.call(normalizedPayload, function(singlePayload) { return serializer.normalize(type, singlePayload); }); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractMeta: function(store, type, payload) { if (payload && payload._pagination) { store.setMetadataFor(type, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload */ extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.setMetadataFor(type, payload.meta); delete payload.meta; } }, /** `extractErrors` is used to extract model errors when a call is made to `DS.Model#save` which fails with an `InvalidError`. By default Ember Data expects error information to be located on the `errors` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractErrors: function(store, type, payload, id) { if (payload && typeof payload === 'object' && payload._problems) { payload = payload._problems; this.normalizeErrors(type, payload); } return payload; } }); ``` @method extractErrors @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @return {Object} json The deserialized errors */ extractErrors: function(store, type, payload, id) { if (payload && typeof payload === 'object' && payload.errors) { payload = payload.errors; this.normalizeErrors(type, payload); } return payload; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```javascript App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @return {String} normalized key */ keyForAttribute: function(key) { return key; }, /** `keyForRelationship` can be used to define a custom key when serializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship type @return {String} normalized key */ keyForRelationship: function(key, type) { return key; }, // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function(attributeType, skipAssertion) { var transform = this.container.lookup('transform:' + attributeType); Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); return transform; } }); var ember$data$lib$serializers$rest$serializer$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$serializers$rest$serializer$$map = Ember.ArrayPolyfills.map; var ember$data$lib$serializers$rest$serializer$$camelize = Ember.String.camelize; function ember$data$lib$serializers$rest$serializer$$coerceId(id) { return id == null ? null : id + ''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to define across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ var ember$data$lib$serializers$rest$serializer$$RESTSerializer = ember$data$lib$serializers$json$serializer$$default.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```javascript App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implementation makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return {Object} */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } this.applyTransforms(type, hash); return hash; }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @param {String} recordId @return {Object} the primary response to the original request */ extractSingle: function(store, primaryType, rawPayload, recordId) { var payload = this.normalizePayload(rawPayload); var primaryTypeName = primaryType.typeKey; var primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop); if (!store.modelFactoryFor(typeName)) { Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false); continue; } var type = store.modelFor(typeName); var isPrimary = type.typeKey === primaryTypeName; var value = payload[prop]; if (value === null) { continue; } // legacy support for singular resources if (isPrimary && Ember.typeOf(value) !== "array" ) { primaryRecord = this.normalize(primaryType, value, prop); continue; } /*jshint loopfunc:true*/ ember$data$lib$serializers$rest$serializer$$forEach.call(value, function(hash) { var typeName = this.typeForRoot(prop); var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord; var isUpdatedRecord = isPrimary && ember$data$lib$serializers$rest$serializer$$coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; }); payload = { comments: comments, posts: payload }; return this._super(store, type, payload); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @return {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, rawPayload) { var payload = this.normalizePayload(rawPayload); var primaryTypeName = primaryType.typeKey; var primaryArray; for (var prop in payload) { var typeKey = prop; var forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey); if (!store.modelFactoryFor(typeName)) { Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false); continue; } var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); var isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = ember$data$lib$serializers$rest$serializer$$map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, rawPayload) { var payload = this.normalizePayload(rawPayload); for (var prop in payload) { var typeName = this.typeForRoot(prop); if (!store.modelFactoryFor(typeName, prop)) { Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false); continue; } var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); /*jshint loopfunc:true*/ var normalizedArray = ember$data$lib$serializers$rest$serializer$$map.call(Ember.makeArray(payload[prop]), function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** This method is used to convert each JSON root key in the payload into a typeKey that it can use to look up the appropriate model for that part of the payload. By default the typeKey for a model is its name in camelCase, so if your JSON root key is 'fast-car' you would use typeForRoot to convert it to 'fastCar' so that Ember Data finds the `FastCar` model. If you diverge from this norm you should also consider changes to store._normalizeTypeKey as well. For example, your server may return prefixed root keys like so: ```js { "response-fast-car": { "id": "1", "name": "corvette" } } ``` In order for Ember Data to know that the model corresponding to the 'response-fast-car' hash is `FastCar` (typeKey: 'fastCar'), you can override typeForRoot to convert 'response-fast-car' to 'fastCar' like so: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { // 'response-fast-car' should become 'fast-car' var subRoot = root.substring(9); // _super normalizes 'fast-car' to 'fastCar' return this._super(subRoot); } }); ``` @method typeForRoot @param {String} key @return {String} the model's typeKey */ typeForRoot: function(key) { return ember$data$lib$serializers$rest$serializer$$camelize(ember$inflector$lib$lib$system$string$$singularize(key)); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = this._super(snapshot, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function(snapshot, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends the typeKey of a model, which is a camelized version of the name. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function(hash, type, snapshot, options) { hash[type.typeKey] = this.serialize(snapshot, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; if (Ember.isNone(belongsTo)) { json[key + "Type"] = null; } else { json[key + "Type"] = Ember.String.camelize(belongsTo.typeKey); } } }); Ember.runInDebug(function() { ember$data$lib$serializers$rest$serializer$$RESTSerializer.reopen({ warnMessageNoModelForKey: function(prop, typeKey) { return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.typeForRoot("' + prop + '"))'; } }); }); var ember$data$lib$serializers$rest$serializer$$default = ember$data$lib$serializers$rest$serializer$$RESTSerializer; /** @module ember-data */ var activemodel$adapter$lib$system$active$model$serializer$$forEach = Ember.EnumerableUtils.forEach; var activemodel$adapter$lib$system$active$model$serializer$$camelize = Ember.String.camelize; var activemodel$adapter$lib$system$active$model$serializer$$capitalize = Ember.String.capitalize; var activemodel$adapter$lib$system$active$model$serializer$$decamelize = Ember.String.decamelize; var activemodel$adapter$lib$system$active$model$serializer$$underscore = Ember.String.underscore; /** The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active\_model\_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers, `embed :ids, embed_in_root: true` which sideloads the records. This serializer extends the DS.RESTSerializer by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelSerializer expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelSerializer @namespace DS @extends DS.RESTSerializer */ var activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer = ember$data$lib$serializers$rest$serializer$$default.extend({ // SERIALIZE /** Converts camelCased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @return String */ keyForAttribute: function(attr) { return activemodel$adapter$lib$system$active$model$serializer$$decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @return String */ keyForRelationship: function(rawKey, kind) { var key = activemodel$adapter$lib$system$active$model$serializer$$decamelize(rawKey); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return ember$inflector$lib$lib$system$string$$singularize(key) + "_ids"; } else { return key; } }, /* Does not serialize hasMany relationships by default. */ serializeHasMany: Ember.K, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function(data, type, snapshot, options) { var root = activemodel$adapter$lib$system$active$model$serializer$$underscore(activemodel$adapter$lib$system$active$model$serializer$$decamelize(type.typeKey)); data[root] = this.serialize(snapshot, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); var jsonKey = activemodel$adapter$lib$system$active$model$serializer$$underscore(key + "_type"); if (Ember.isNone(belongsTo)) { json[jsonKey] = null; } else { json[jsonKey] = activemodel$adapter$lib$system$active$model$serializer$$capitalize(activemodel$adapter$lib$system$active$model$serializer$$camelize(belongsTo.typeKey)); } }, // EXTRACT /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return Object */ normalize: function(type, hash, prop) { this.normalizeLinks(hash); return this._super(type, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} data */ normalizeLinks: function(data) { if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = activemodel$adapter$lib$system$active$model$serializer$$camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { var payloadKey, payload; if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } else if (payload && relationship.kind === "hasMany") { var self = this; activemodel$adapter$lib$system$active$model$serializer$$forEach(payload, function(single) { single.type = self.typeForRoot(single.type); }); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); if (!hash.hasOwnProperty(payloadKey)) { return; } payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } } }); var activemodel$adapter$lib$system$active$model$serializer$$default = activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer; function ember$data$lib$system$container$proxy$$ContainerProxy(container) { this.container = container; } ember$data$lib$system$container$proxy$$ContainerProxy.prototype.aliasedFactory = function(path, preLookup) { var _this = this; return { create: function() { if (preLookup) { preLookup(); } return _this.container.lookup(path); } }; }; ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) { var preLookupCallback = function() { Ember.deprecate("You tried to look up '" + deprecated + "', " + "but this has been deprecated in favor of '" + valid + "'.", false); }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecations = function(proxyPairs) { var i, proxyPair, deprecated, valid; for (i = proxyPairs.length; i > 0; i--) { proxyPair = proxyPairs[i - 1]; deprecated = proxyPair['deprecated']; valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } }; var ember$data$lib$system$container$proxy$$default = ember$data$lib$system$container$proxy$$ContainerProxy; function activemodel$adapter$lib$setup$container$$setupActiveModelAdapter(registry, application) { var proxy = new ember$data$lib$system$container$proxy$$default(registry); proxy.registerDeprecations([ { deprecated: 'serializer:_ams', valid: 'serializer:-active-model' }, { deprecated: 'adapter:_ams', valid: 'adapter:-active-model' } ]); registry.register('serializer:-active-model', activemodel$adapter$lib$system$active$model$serializer$$default); registry.register('adapter:-active-model', activemodel$adapter$lib$system$active$model$adapter$$default); } var activemodel$adapter$lib$setup$container$$default = activemodel$adapter$lib$setup$container$$setupActiveModelAdapter; var ember$data$lib$core$$DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.16.1' }); if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', ember$data$lib$core$$DS.VERSION); } var ember$data$lib$core$$default = ember$data$lib$core$$DS; var ember$data$lib$system$promise$proxies$$Promise = Ember.RSVP.Promise; var ember$data$lib$system$promise$proxies$$get = Ember.get; /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ var ember$data$lib$system$promise$proxies$$PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved, then the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ var ember$data$lib$system$promise$proxies$$PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); var ember$data$lib$system$promise$proxies$$promiseObject = function(promise, label) { return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label) }); }; var ember$data$lib$system$promise$proxies$$promiseArray = function(promise, label) { return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label) }); }; /** A PromiseManyArray is a PromiseArray that also proxies certain method calls to the underlying manyArray. Right now we proxy: * `reload()` * `createRecord()` * `on()` * `one()` * `trigger()` * `off()` * `has()` @class PromiseManyArray @namespace DS @extends Ember.ArrayProxy */ function ember$data$lib$system$promise$proxies$$proxyToContent(method) { return function() { var content = ember$data$lib$system$promise$proxies$$get(this, 'content'); return content[method].apply(content, arguments); }; } var ember$data$lib$system$promise$proxies$$PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseArray.extend({ reload: function() { //I don't think this should ever happen right now, but worth guarding if we refactor the async relationships Ember.assert('You are trying to reload an async manyArray before it has been created', ember$data$lib$system$promise$proxies$$get(this, 'content')); return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({ promise: ember$data$lib$system$promise$proxies$$get(this, 'content').reload() }); }, createRecord: ember$data$lib$system$promise$proxies$$proxyToContent('createRecord'), on: ember$data$lib$system$promise$proxies$$proxyToContent('on'), one: ember$data$lib$system$promise$proxies$$proxyToContent('one'), trigger: ember$data$lib$system$promise$proxies$$proxyToContent('trigger'), off: ember$data$lib$system$promise$proxies$$proxyToContent('off'), has: ember$data$lib$system$promise$proxies$$proxyToContent('has') }); var ember$data$lib$system$promise$proxies$$promiseManyArray = function(promise, label) { return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({ promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label) }); }; var ember$data$lib$system$store$common$$get = Ember.get; function ember$data$lib$system$store$common$$_bind(fn) { var args = Array.prototype.slice.call(arguments, 1); return function() { return fn.apply(undefined, args); }; } function ember$data$lib$system$store$common$$_guard(promise, test) { var guarded = promise['finally'](function() { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function ember$data$lib$system$store$common$$_objectIsAlive(object) { return !(ember$data$lib$system$store$common$$get(object, "isDestroyed") || ember$data$lib$system$store$common$$get(object, "isDestroying")); } function ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type) { var serializer = adapter.serializer; if (serializer === undefined) { serializer = store.serializerFor(type); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } var ember$data$lib$system$store$finders$$get = Ember.get; var ember$data$lib$system$store$finders$$Promise = Ember.RSVP.Promise; function ember$data$lib$system$store$finders$$_find(adapter, store, type, id, record) { var snapshot = record._createSnapshot(); var promise = adapter.find(store, type, id, snapshot); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type); var label = "DS: Handle Adapter#find of " + type + " with id: " + id; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function(adapterPayload) { Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload); return store._adapterRun(function() { var payload = serializer.extract(store, type, adapterPayload, id, 'find'); return store.push(type, payload); }); }, function(error) { var record = store.getById(type, id); if (record) { record.notFound(); if (ember$data$lib$system$store$finders$$get(record, 'isEmpty')) { store.unloadRecord(record); } } throw error; }, "DS: Extract payload of '" + type + "'"); } function ember$data$lib$system$store$finders$$_findMany(adapter, store, type, ids, records) { var snapshots = Ember.A(records).invoke('_createSnapshot'); var promise = adapter.findMany(store, type, ids, snapshots); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type); var label = "DS: Handle Adapter#findMany of " + type; if (promise === undefined) { throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); } promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function(adapterPayload) { return store._adapterRun(function() { var payload = serializer.extract(store, type, adapterPayload, null, 'findMany'); Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); return store.pushMany(type, payload); }); }, null, "DS: Extract payload of " + type); } function ember$data$lib$system$store$finders$$_findHasMany(adapter, store, record, link, relationship) { var snapshot = record._createSnapshot(); var promise = adapter.findHasMany(store, snapshot, link, relationship); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type); var label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, record)); return promise.then(function(adapterPayload) { return store._adapterRun(function() { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany'); Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); var records = store.pushMany(relationship.type, payload); return records; }); }, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type); } function ember$data$lib$system$store$finders$$_findBelongsTo(adapter, store, record, link, relationship) { var snapshot = record._createSnapshot(); var promise = adapter.findBelongsTo(store, snapshot, link, relationship); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type); var label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, record)); return promise.then(function(adapterPayload) { return store._adapterRun(function() { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo'); if (!payload) { return null; } var record = store.push(relationship.type, payload); return record; }); }, null, "DS: Extract payload of " + record + " : " + relationship.type); } function ember$data$lib$system$store$finders$$_findAll(adapter, store, type, sinceToken) { var promise = adapter.findAll(store, type, sinceToken); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type); var label = "DS: Handle Adapter#findAll of " + type; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function(adapterPayload) { store._adapterRun(function() { var payload = serializer.extract(store, type, adapterPayload, null, 'findAll'); Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); store.pushMany(type, payload); }); store.didUpdateAll(type); return store.all(type); }, null, "DS: Extract payload of findAll " + type); } function ember$data$lib$system$store$finders$$_findQuery(adapter, store, type, query, recordArray) { var promise = adapter.findQuery(store, type, query, recordArray); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type); var label = "DS: Handle Adapter#findQuery of " + type; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function(adapterPayload) { var payload; store._adapterRun(function() { payload = serializer.extract(store, type, adapterPayload, null, 'findQuery'); Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); }); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + type); } var ember$data$lib$system$record$arrays$record$array$$get = Ember.get; var ember$data$lib$system$record$arrays$record$array$$set = Ember.set; var ember$data$lib$system$record$arrays$record$array$$default = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function(index) { var content = ember$data$lib$system$record$arrays$record$array$$get(this, 'content'); return content.objectAt(index); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @method update */ update: function() { if (ember$data$lib$system$record$arrays$record$array$$get(this, 'isUpdating')) { return; } var store = ember$data$lib$system$record$arrays$record$array$$get(this, 'store'); var type = ember$data$lib$system$record$arrays$record$array$$get(this, 'type'); return store.fetchAll(type, this); }, /** Adds a record to the `RecordArray` without duplicates @method addRecord @private @param {DS.Model} record @param {DS.Model} an optional index to insert at */ addRecord: function(record, idx) { var content = ember$data$lib$system$record$arrays$record$array$$get(this, 'content'); if (idx === undefined) { content.addObject(record); } else if (!content.contains(record)) { content.insertAt(idx, record); } }, _pushRecord: function(record) { ember$data$lib$system$record$arrays$record$array$$get(this, 'content').pushObject(record); }, /** Adds a record to the `RecordArray`, but allows duplicates @deprecated @method pushRecord @private @param {DS.Model} record */ pushRecord: function(record) { Ember.deprecate('Usage of `recordArray.pushRecord` is deprecated, use `recordArray.addObject` instead'); this._pushRecord(record); }, /** Removes a record to the `RecordArray`. @method removeRecord @private @param {DS.Model} record */ removeRecord: function(record) { ember$data$lib$system$record$arrays$record$array$$get(this, 'content').removeObject(record); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.all('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var recordArray = this; var promiseLabel = "DS: RecordArray#save " + ember$data$lib$system$record$arrays$record$array$$get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return recordArray; }, null, "DS: RecordArray#save return RecordArray"); return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function() { var array = this; this.forEach(function(record) { var recordArrays = record._recordArrays; if (recordArrays) { recordArrays["delete"](array); } }); }, /** @method _unregisterFromManager @private */ _unregisterFromManager: function() { var manager = ember$data$lib$system$record$arrays$record$array$$get(this, 'manager'); //We will stop needing this stupid if statement soon, once manyArray are refactored to not be RecordArrays if (manager) { manager.unregisterFilteredRecordArray(this); } }, willDestroy: function() { this._unregisterFromManager(); this._dissociateFromOwnRecords(); ember$data$lib$system$record$arrays$record$array$$set(this, 'content', undefined); this._super.apply(this, arguments); } }); /** @module ember-data */ var ember$data$lib$system$record$arrays$filtered$record$array$$get = Ember.get; var ember$data$lib$system$record$arrays$filtered$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.all('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function() { var type = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ _updateFilter: function() { var manager = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, 'manager'); manager.updateFilter(this, ember$data$lib$system$record$arrays$filtered$record$array$$get(this, 'type'), ember$data$lib$system$record$arrays$filtered$record$array$$get(this, 'filterFunction')); }, updateFilter: Ember.observer(function() { Ember.run.once(this, this._updateFilter); }, 'filterFunction') }); /** @module ember-data */ var ember$data$lib$system$record$arrays$adapter$populated$record$array$$get = Ember.get; function ember$data$lib$system$record$arrays$adapter$populated$record$array$$cloneNull(source) { var clone = Ember.create(null); for (var key in source) { clone[key] = source[key]; } return clone; } var ember$data$lib$system$record$arrays$adapter$populated$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({ query: null, replace: function() { var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function(data) { var store = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, 'store'); var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, 'type'); var records = store.pushMany(type, data); var meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: ember$data$lib$system$record$arrays$adapter$populated$record$array$$cloneNull(meta) }); records.forEach(function(record) { this.manager.recordArraysForRecord(record).add(this); }, this); // TODO: should triggering didLoad event be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); var ember$data$lib$system$ordered$set$$EmberOrderedSet = Ember.OrderedSet; var ember$data$lib$system$ordered$set$$guidFor = Ember.guidFor; var ember$data$lib$system$ordered$set$$OrderedSet = function() { this._super$constructor(); }; ember$data$lib$system$ordered$set$$OrderedSet.create = function() { var Constructor = this; return new Constructor(); }; ember$data$lib$system$ordered$set$$OrderedSet.prototype = Ember.create(ember$data$lib$system$ordered$set$$EmberOrderedSet.prototype); ember$data$lib$system$ordered$set$$OrderedSet.prototype.constructor = ember$data$lib$system$ordered$set$$OrderedSet; ember$data$lib$system$ordered$set$$OrderedSet.prototype._super$constructor = ember$data$lib$system$ordered$set$$EmberOrderedSet; ember$data$lib$system$ordered$set$$OrderedSet.prototype.addWithIndex = function(obj, idx) { var guid = ember$data$lib$system$ordered$set$$guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { return; } presenceSet[guid] = true; if (idx === undefined || idx == null) { list.push(obj); } else { list.splice(idx, 0, obj); } this.size += 1; return this; }; var ember$data$lib$system$ordered$set$$default = ember$data$lib$system$ordered$set$$OrderedSet; var ember$data$lib$system$record$array$manager$$get = Ember.get; var ember$data$lib$system$record$array$manager$$forEach = Ember.EnumerableUtils.forEach; var ember$data$lib$system$record$array$manager$$indexOf = Ember.EnumerableUtils.indexOf; var ember$data$lib$system$record$array$manager$$default = Ember.Object.extend({ init: function() { this.filteredRecordArrays = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function(record) { if (this.changedRecords.push(record) !== 1) { return; } Ember.run.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || ember$data$lib$system$ordered$set$$default.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { ember$data$lib$system$record$array$manager$$forEach(this.changedRecords, function(record) { if (ember$data$lib$system$record$array$manager$$get(record, 'isDeleted')) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } recordArrays.forEach(function(array) { array.removeRecord(record); }); record._recordArrays = null; }, //Don't need to update non filtered arrays on simple changes _recordWasChanged: function (record) { var type = record.constructor; var recordArrays = this.filteredRecordArrays.get(type); var filter; ember$data$lib$system$record$array$manager$$forEach(recordArrays, function(array) { filter = ember$data$lib$system$record$array$manager$$get(array, 'filterFunction'); if (filter) { this.updateRecordArray(array, filter, type, record); } }, this); }, //Need to update live arrays on loading recordWasLoaded: function(record) { var type = record.constructor; var recordArrays = this.filteredRecordArrays.get(type); var filter; ember$data$lib$system$record$array$manager$$forEach(recordArrays, function(array) { filter = ember$data$lib$system$record$array$manager$$get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { if (!recordArrays.has(array)) { array._pushRecord(record); recordArrays.add(array); } } else if (!shouldBeInArray) { recordArrays["delete"](array); array.removeRecord(record); } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param {Array} array @param {String} type @param {Function} filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type); var records = typeMap.records; var record; for (var i = 0, l = records.length; i < l; i++) { record = records[i]; if (!ember$data$lib$system$record$array$manager$$get(record, 'isDeleted') && !ember$data$lib$system$record$array$manager$$get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} type @return {DS.RecordArray} */ createRecordArray: function(type) { var array = ember$data$lib$system$record$arrays$record$array$$default.create({ type: type, content: Ember.A(), store: this.store, isLoaded: true, manager: this }); this.registerFilteredRecordArray(array, type); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {Class} type @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(type, filter, query) { var array = ember$data$lib$system$record$arrays$filtered$record$array$$default.create({ query: query, type: type, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, type, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {Class} type @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(type, query) { var array = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default.create({ type: type, query: query, content: Ember.A(), store: this.store, manager: this }); this._adapterPopulatedRecordArrays.push(array); return array; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, /** Unregister a FilteredRecordArray. So manager will not update this array. @method unregisterFilteredRecordArray @param {DS.RecordArray} array */ unregisterFilteredRecordArray: function(array) { var recordArrays = this.filteredRecordArrays.get(array.type); var index = ember$data$lib$system$record$array$manager$$indexOf(recordArrays, array); recordArrays.splice(index, 1); }, willDestroy: function() { this._super.apply(this, arguments); this.filteredRecordArrays.forEach(function(value) { ember$data$lib$system$record$array$manager$$forEach(ember$data$lib$system$record$array$manager$$flatten(value), ember$data$lib$system$record$array$manager$$destroy); }); ember$data$lib$system$record$array$manager$$forEach(this._adapterPopulatedRecordArrays, ember$data$lib$system$record$array$manager$$destroy); } }); function ember$data$lib$system$record$array$manager$$destroy(entry) { entry.destroy(); } function ember$data$lib$system$record$array$manager$$flatten(list) { var length = list.length; var result = Ember.A(); for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } var ember$data$lib$system$model$states$$get = Ember.get; var ember$data$lib$system$model$states$$set = Ember.set; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (This state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What that means is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ function ember$data$lib$system$model$states$$didSetProperty(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); } // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: The adapter did not report any server-side validation // failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var ember$data$lib$system$model$states$$DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: ember$data$lib$system$model$states$$didSetProperty, //TODO(Igor) reloading now triggers a //loadingData event, though it seems fine? loadingData: Ember.K, propertyWasReset: function(record, name) { var length = Ember.keys(record._attributes).length; var stillDirty = length > 0; if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolve) { resolve(ember$data$lib$system$model$states$$get(record, 'store').reloadRecord(record)); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); record.triggerLater('ready'); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: ember$data$lib$system$model$states$$didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, unloadRecord: function(record) { Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + " `", false); }, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = ember$data$lib$system$model$states$$get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.disconnectRelationships(); }, didSetProperty: function(record, context) { ember$data$lib$system$model$states$$get(record, 'errors').remove(context.name); ember$data$lib$system$model$states$$didSetProperty(record, context); }, becomeDirty: Ember.K, willCommit: function(record) { ember$data$lib$system$model$states$$get(record, 'errors').clear(); record.transitionTo('inFlight'); }, rolledBack: function(record) { ember$data$lib$system$model$states$$get(record, 'errors').clear(); record.triggerLater('ready'); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); }, exit: function(record) { record._inFlightAttributes = {}; } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function ember$data$lib$system$model$states$$deepClone(object) { var clone = {}; var value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = ember$data$lib$system$model$states$$deepClone(value); } else { clone[prop] = value; } } return clone; } function ember$data$lib$system$model$states$$mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function ember$data$lib$system$model$states$$dirtyState(options) { var newState = ember$data$lib$system$model$states$$deepClone(ember$data$lib$system$model$states$$DirtyState); return ember$data$lib$system$model$states$$mixin(newState, options); } var ember$data$lib$system$model$states$$createdState = ember$data$lib$system$model$states$$dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); ember$data$lib$system$model$states$$createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var ember$data$lib$system$model$states$$updatedState = ember$data$lib$system$model$states$$dirtyState({ dirtyType: 'updated' }); ember$data$lib$system$model$states$$createdState.uncommitted.deleteRecord = function(record) { record.disconnectRelationships(); record.transitionTo('deleted.saved'); record.send('invokeLifecycleCallbacks'); }; ember$data$lib$system$model$states$$createdState.uncommitted.rollback = function(record) { ember$data$lib$system$model$states$$DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; ember$data$lib$system$model$states$$createdState.uncommitted.pushedData = function(record) { record.transitionTo('loaded.updated.uncommitted'); record.triggerLater('didLoad'); }; ember$data$lib$system$model$states$$createdState.uncommitted.propertyWasReset = Ember.K; function ember$data$lib$system$model$states$$assertAgainstUnloadRecord(record) { Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + "`", false); } ember$data$lib$system$model$states$$updatedState.inFlight.unloadRecord = ember$data$lib$system$model$states$$assertAgainstUnloadRecord; ember$data$lib$system$model$states$$updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.disconnectRelationships(); }; var ember$data$lib$system$model$states$$RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.triggerLater('ready'); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); record.triggerLater('ready'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); record.triggerLater('ready'); ember$data$lib$system$model$states$$set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, //TODO(Igor) Reloading now triggers a loadingData event, //but it should be ok? loadingData: Ember.K, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes; var isDirty = Ember.keys(attrs).length > 0; if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: ember$data$lib$system$model$states$$didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolve) { resolve(ember$data$lib$system$model$states$$get(record, 'store').reloadRecord(record)); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.disconnectRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', ember$data$lib$system$model$states$$get(record, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: ember$data$lib$system$model$states$$createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: ember$data$lib$system$model$states$$updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { record.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); record.triggerLater('ready'); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('ready'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS unloadRecord: ember$data$lib$system$model$states$$assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.triggerLater('becameInvalid', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = ember$data$lib$system$model$states$$get(record, 'store'); store._dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); }, willCommit: Ember.K, didCommit: Ember.K }, invalid: { isValid: false, didSetProperty: function(record, context) { ember$data$lib$system$model$states$$get(record, 'errors').remove(context.name); ember$data$lib$system$model$states$$didSetProperty(record, context); }, deleteRecord: Ember.K, becomeDirty: Ember.K, willCommit: Ember.K, rolledBack: function(record) { ember$data$lib$system$model$states$$get(record, 'errors').clear(); record.transitionTo('loaded.saved'); record.triggerLater('ready'); }, becameValid: function(record) { record.transitionTo('uncommitted'); } } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function ember$data$lib$system$model$states$$wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = ember$data$lib$system$model$states$$mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = ember$data$lib$system$model$states$$wireState(object[prop], object, name + "." + prop); } } return object; } ember$data$lib$system$model$states$$RootState = ember$data$lib$system$model$states$$wireState(ember$data$lib$system$model$states$$RootState, null, "root"); var ember$data$lib$system$model$states$$default = ember$data$lib$system$model$states$$RootState; var ember$data$lib$system$model$errors$$get = Ember.get; var ember$data$lib$system$model$errors$$isEmpty = Ember.isEmpty; var ember$data$lib$system$model$errors$$map = Ember.EnumerableUtils.map; var ember$data$lib$system$model$errors$$default = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.reduceComputed("content", { initialValue: function() { return ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); }, addedItem: function(errors, error) { errors.get(error.attribute).pushObject(error); return errors; }, removedItem: function(errors, error) { errors.get(error.attribute).removeObject(error); return errors; } }), /** Returns errors for a given attribute ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save().catch(function(){ user.get('errors').errorsFor('email'); // returns: // [{attribute: "email", message: "Doesn't look like a valid email."}] }); ``` @method errorsFor @param {String} attribute @return {Array} */ errorsFor: function(attribute) { return ember$data$lib$system$model$errors$$get(this, 'errorsByAttributeName').get(attribute); }, /** An array containing all of the error messages for this record. This is useful for displaying all errors to the user. ```handlebars {{#each message in model.errors.messages}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: Ember.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function() { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function(attribute) { var errors = this.errorsFor(attribute); if (ember$data$lib$system$model$errors$$isEmpty(errors)) { return null; } return errors; }, /** @method nextObject @private */ nextObject: function(index, previousObject, context) { return ember$data$lib$system$model$errors$$get(this, 'content').objectAt(index); }, /** Total number of errors. @property length @type {Number} @readOnly */ length: Ember.computed.oneWay('content.length').readOnly(), /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. Example: ```javascript if (!user.get('username') { user.get('errors').add('username', 'This field is required'); } ``` @method add @param {String} attribute @param {Array|String} messages */ add: function(attribute, messages) { var wasEmpty = ember$data$lib$system$model$errors$$get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); ember$data$lib$system$model$errors$$get(this, 'content').addObjects(messages); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (wasEmpty && !ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function(attribute, messages) { var errors = this.errorsFor(attribute); return ember$data$lib$system$model$errors$$map(Ember.makeArray(messages), function(message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```javascript App.User = DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute */ remove: function(attribute) { if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { return; } var content = ember$data$lib$system$model$errors$$get(this, 'content').rejectBy('attribute', attribute); ember$data$lib$system$model$errors$$get(this, 'content').setObjects(content); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear */ clear: function() { if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { return; } ember$data$lib$system$model$errors$$get(this, 'content').clear(); this.enumerableContentDidChange(); this.trigger('becameValid'); }, /** Checks if there is error messages for the given attribute. ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (user.get('errors').has('email')) { return alert('Please update your email before attempting to save.'); } user.save(); } } }); ``` @method has @param {String} attribute @return {Boolean} true if there some errors on given attribute */ has: function(attribute) { return !ember$data$lib$system$model$errors$$isEmpty(this.errorsFor(attribute)); } }); function ember$data$lib$system$merge$$merge(original, updates) { if (!updates || typeof updates !== 'object') { return original; } var props = Ember.keys(updates); var prop; var length = props.length; for (var i = 0; i < length; i++) { prop = props[i]; original[prop] = updates[prop]; } return original; } var ember$data$lib$system$merge$$default = ember$data$lib$system$merge$$merge; var ember$data$lib$system$relationships$state$relationship$$forEach = Ember.EnumerableUtils.forEach; var ember$data$lib$system$relationships$state$relationship$$Relationship = function(store, record, inverseKey, relationshipMeta) { this.members = new ember$data$lib$system$ordered$set$$default(); this.canonicalMembers = new ember$data$lib$system$ordered$set$$default(); this.store = store; this.key = relationshipMeta.key; this.inverseKey = inverseKey; this.record = record; this.isAsync = relationshipMeta.options.async; this.relationshipMeta = relationshipMeta; //This probably breaks for polymorphic relationship in complex scenarios, due to //multiple possible typeKeys this.inverseKeyForImplicit = this.store.modelFor(this.record.constructor).typeKey + this.key; this.linkPromise = null; }; ember$data$lib$system$relationships$state$relationship$$Relationship.prototype = { constructor: ember$data$lib$system$relationships$state$relationship$$Relationship, destroy: Ember.K, clear: function() { var members = this.members.list; var member; while (members.length > 0) { member = members[0]; this.removeRecord(member); } }, disconnect: function() { this.members.forEach(function(member) { this.removeRecordFromInverse(member); }, this); }, reconnect: function() { this.members.forEach(function(member) { this.addRecordToInverse(member); }, this); }, removeRecords: function(records) { var self = this; ember$data$lib$system$relationships$state$relationship$$forEach(records, function(record) { self.removeRecord(record); }); }, addRecords: function(records, idx) { var self = this; ember$data$lib$system$relationships$state$relationship$$forEach(records, function(record) { self.addRecord(record, idx); if (idx !== undefined) { idx++; } }); }, addCanonicalRecords: function(records, idx) { for (var i=0; i<records.length; i++) { if (idx !== undefined) { this.addCanonicalRecord(records[i], i+idx); } else { this.addCanonicalRecord(records[i]); } } }, addCanonicalRecord: function(record, idx) { if (!this.canonicalMembers.has(record)) { this.canonicalMembers.add(record); if (this.inverseKey) { record._relationships[this.inverseKey].addCanonicalRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record); } } this.flushCanonicalLater(); }, removeCanonicalRecords: function(records, idx) { for (var i=0; i<records.length; i++) { if (idx !== undefined) { this.removeCanonicalRecord(records[i], i+idx); } else { this.removeCanonicalRecord(records[i]); } } }, removeCanonicalRecord: function(record, idx) { if (this.canonicalMembers.has(record)) { this.removeCanonicalRecordFromOwn(record); if (this.inverseKey) { this.removeCanonicalRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record); } } } this.flushCanonicalLater(); }, addRecord: function(record, idx) { if (!this.members.has(record)) { this.members.addWithIndex(record, idx); this.notifyRecordRelationshipAdded(record, idx); if (this.inverseKey) { record._relationships[this.inverseKey].addRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record); } this.record.updateRecordArraysLater(); } }, removeRecord: function(record) { if (this.members.has(record)) { this.removeRecordFromOwn(record); if (this.inverseKey) { this.removeRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record); } } } }, addRecordToInverse: function(record) { if (this.inverseKey) { record._relationships[this.inverseKey].addRecord(this.record); } }, removeRecordFromInverse: function(record) { var inverseRelationship = record._relationships[this.inverseKey]; //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeRecordFromOwn(this.record); } }, removeRecordFromOwn: function(record) { this.members["delete"](record); this.notifyRecordRelationshipRemoved(record); this.record.updateRecordArrays(); }, removeCanonicalRecordFromInverse: function(record) { var inverseRelationship = record._relationships[this.inverseKey]; //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeCanonicalRecordFromOwn(this.record); } }, removeCanonicalRecordFromOwn: function(record) { this.canonicalMembers["delete"](record); this.flushCanonicalLater(); }, flushCanonical: function() { this.willSync = false; //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = []; for (var i=0; i<this.members.list.length; i++) { if (this.members.list[i].get('isNew')) { newRecords.push(this.members.list[i]); } } //TODO(Igor) make this less abysmally slow this.members = this.canonicalMembers.copy(); for (i=0; i<newRecords.length; i++) { this.members.add(newRecords[i]); } }, flushCanonicalLater: function() { if (this.willSync) { return; } this.willSync = true; var self = this; this.store._backburner.join(function() { self.store._backburner.schedule('syncRelationships', self, self.flushCanonical); }); }, updateLink: function(link) { Ember.warn("You have pushed a record of type '" + this.record.constructor.typeKey + "' with '" + this.key + "' as a link, but the association is not an async relationship.", this.isAsync); Ember.assert("You have pushed a record of type '" + this.record.constructor.typeKey + "' with '" + this.key + "' as a link, but the value of that link is not a string.", typeof link === 'string' || link === null); if (link !== this.link) { this.link = link; this.linkPromise = null; this.record.notifyPropertyChange(this.key); } }, findLink: function() { if (this.linkPromise) { return this.linkPromise; } else { var promise = this.fetchLink(); this.linkPromise = promise; return promise.then(function(result) { return result; }); } }, updateRecordsFromAdapter: function(records) { //TODO(Igor) move this to a proper place var self = this; //TODO Once we have adapter support, we need to handle updated and canonical changes self.computeChanges(records); }, notifyRecordRelationshipAdded: Ember.K, notifyRecordRelationshipRemoved: Ember.K }; var ember$data$lib$system$relationships$state$relationship$$default = ember$data$lib$system$relationships$state$relationship$$Relationship; var ember$data$lib$system$many$array$$get = Ember.get; var ember$data$lib$system$many$array$$set = Ember.set; var ember$data$lib$system$many$array$$filter = Ember.ArrayPolyfills.filter; var ember$data$lib$system$many$array$$default = Ember.Object.extend(Ember.MutableArray, Ember.Evented, { init: function() { this.currentState = Ember.A([]); }, record: null, canonicalState: null, currentState: null, length: 0, objectAt: function(index) { if (this.currentState[index]) { return this.currentState[index]; } else { return this.canonicalState[index]; } }, flushCanonical: function() { //TODO make this smarter, currently its plenty stupid var toSet = ember$data$lib$system$many$array$$filter.call(this.canonicalState, function(record) { return !record.get('isDeleted'); }); //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = this.currentState.filter(function(record) { return record.get('isNew'); }); toSet = toSet.concat(newRecords); var oldLength = this.length; this.arrayContentWillChange(0, this.length, toSet.length); this.set('length', toSet.length); this.currentState = toSet; this.arrayContentDidChange(0, oldLength, this.length); //TODO Figure out to notify only on additions and maybe only if unloaded this.relationship.notifyHasManyChanged(); this.record.updateRecordArrays(); }, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, /** The loading state of this array @property {Boolean} isLoaded */ isLoaded: false, /** The relationship which manages this array. @property {ManyRelationship} relationship @private */ relationship: null, internalReplace: function(idx, amt, objects) { if (!objects) { objects = []; } this.arrayContentWillChange(idx, amt, objects.length); this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects)); this.set('length', this.currentState.length); this.arrayContentDidChange(idx, amt, objects.length); if (objects) { //TODO(Igor) probably needed only for unloaded records this.relationship.notifyHasManyChanged(); } this.record.updateRecordArrays(); }, //TODO(Igor) optimize internalRemoveRecords: function(records) { var index; for (var i=0; i < records.length; i++) { index = this.currentState.indexOf(records[i]); this.internalReplace(index, 1); } }, //TODO(Igor) optimize internalAddRecords: function(records, idx) { if (idx === undefined) { idx = this.currentState.length; } this.internalReplace(idx, 0, records); }, replace: function(idx, amt, objects) { var records; if (amt > 0) { records = this.currentState.slice(idx, idx+amt); this.get('relationship').removeRecords(records); } if (objects) { this.get('relationship').addRecords(objects, idx); } }, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { ember$data$lib$system$many$array$$set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method reload @public */ reload: function() { return this.relationship.reload(); }, /** Saves all of the records in the `ManyArray`. Example ```javascript store.find('inbox', 1).then(function(inbox) { inbox.get('messages').then(function(messages) { messages.forEach(function(message) { message.set('isRead', true); }); messages.save() }); }); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var manyArray = this; var promiseLabel = "DS: ManyArray#save " + ember$data$lib$system$many$array$$get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return manyArray; }, null, "DS: ManyArray#save return ManyArray"); return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: promise }); }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function(hash) { var store = ember$data$lib$system$many$array$$get(this, 'store'); var type = ember$data$lib$system$many$array$$get(this, 'type'); var record; Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !ember$data$lib$system$many$array$$get(this, 'isPolymorphic')); record = store.createRecord(type, hash); this.pushObject(record); return record; }, /** @method addRecord @param {DS.Model} record @deprecated Use `addObject()` instead */ addRecord: function(record) { Ember.deprecate('Using manyArray.addRecord() has been deprecated. You should use manyArray.addObject() instead.'); this.addObject(record); }, /** @method removeRecord @param {DS.Model} record @deprecated Use `removeObject()` instead */ removeRecord: function(record) { Ember.deprecate('Using manyArray.removeRecord() has been deprecated. You should use manyArray.removeObject() instead.'); this.removeObject(record); } }); var ember$data$lib$system$relationships$state$has$many$$ManyRelationship = function(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.belongsToType = relationshipMeta.type; this.canonicalState = []; this.manyArray = ember$data$lib$system$many$array$$default.create({ canonicalState: this.canonicalState, store: this.store, relationship: this, type: this.belongsToType, record: record }); this.isPolymorphic = relationshipMeta.options.polymorphic; this.manyArray.isPolymorphic = this.isPolymorphic; }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype); ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.constructor = ember$data$lib$system$relationships$state$has$many$$ManyRelationship; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.destroy = function() { this.manyArray.destroy(); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addCanonicalRecord = function(record, idx) { if (this.canonicalMembers.has(record)) { return; } if (idx !== undefined) { this.canonicalState.splice(idx, 0, record); } else { this.canonicalState.push(record); } this._super$addCanonicalRecord(record, idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addRecord = function(record, idx) { if (this.members.has(record)) { return; } this._super$addRecord(record, idx); this.manyArray.internalAddRecords([record], idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeCanonicalRecordFromOwn = function(record, idx) { var i = idx; if (!this.canonicalMembers.has(record)) { return; } if (i === undefined) { i = this.canonicalState.indexOf(record); } if (i > -1) { this.canonicalState.splice(i, 1); } this._super$removeCanonicalRecordFromOwn(record, idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.flushCanonical = function() { this.manyArray.flushCanonical(); this._super$flushCanonical(); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeRecordFromOwn = function(record, idx) { if (!this.members.has(record)) { return; } this._super$removeRecordFromOwn(record, idx); if (idx !== undefined) { //TODO(Igor) not used currently, fix this.manyArray.currentState.removeAt(idx); } else { this.manyArray.internalRemoveRecords([record]); } }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyRecordRelationshipAdded = function(record, idx) { var type = this.relationshipMeta.type; Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to the " + this.record.constructor.typeKey + "." + this.key + " relationship (only '" + this.belongsToType.typeKey + "' allowed)", (function () { if (type.__isMixin) { return type.__mixin.detect(record); } if (Ember.MODEL_FACTORY_INJECTIONS) { type = type.superclass; } return record instanceof type; })()); this.record.notifyHasManyAdded(this.key, record, idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.reload = function() { var self = this; if (this.link) { return this.fetchLink(); } else { return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function() { //Goes away after the manyArray refactor self.manyArray.set('isLoaded', true); return self.manyArray; }); } }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.computeChanges = function(records) { var members = this.canonicalMembers; var recordsToRemove = []; var length; var record; var i; records = ember$data$lib$system$relationships$state$has$many$$setForArray(records); members.forEach(function(member) { if (records.has(member)) { return; } recordsToRemove.push(member); }); this.removeCanonicalRecords(recordsToRemove); // Using records.toArray() since currently using // removeRecord can modify length, messing stuff up // forEach since it directly looks at "length" each // iteration records = records.toArray(); length = records.length; for (i = 0; i < length; i++) { record = records[i]; this.removeCanonicalRecord(record); this.addCanonicalRecord(record, i); } }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.fetchLink = function() { var self = this; return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function(records) { self.store._backburner.join(function() { self.updateRecordsFromAdapter(records); }); return self.manyArray; }); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.findRecords = function() { var manyArray = this.manyArray; return this.store.findMany(manyArray.toArray()).then(function() { //Goes away after the manyArray refactor manyArray.set('isLoaded', true); return manyArray; }); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyHasManyChanged = function() { this.record.notifyHasManyAdded(this.key); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.getRecords = function() { //TODO(Igor) sync server here, once our syncing is not stupid if (this.isAsync) { var self = this; var promise; if (this.link) { promise = this.findLink().then(function() { return self.findRecords(); }); } else { promise = this.findRecords(); } return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({ content: this.manyArray, promise: promise }); } else { Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.constructor.typeKey + "' with id " + this.record.get('id') + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", this.manyArray.isEvery('isEmpty', false)); //TODO(Igor) WTF DO I DO HERE? if (!this.manyArray.get('isDestroyed')) { this.manyArray.set('isLoaded', true); } return this.manyArray; } }; function ember$data$lib$system$relationships$state$has$many$$setForArray(array) { var set = new ember$data$lib$system$ordered$set$$default(); if (array) { for (var i=0, l=array.length; i<l; i++) { set.add(array[i]); } } return set; } var ember$data$lib$system$relationships$state$has$many$$default = ember$data$lib$system$relationships$state$has$many$$ManyRelationship; var ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship = function(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.record = record; this.key = relationshipMeta.key; this.inverseRecord = null; this.canonicalState = null; }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype); ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.constructor = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecord = function(newRecord) { if (newRecord) { this.addRecord(newRecord); } else if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setCanonicalRecord = function(newRecord) { if (newRecord) { this.addCanonicalRecord(newRecord); } else if (this.inverseRecord) { this.removeCanonicalRecord(this.inverseRecord); } }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addCanonicalRecord = function(newRecord) { if (this.canonicalMembers.has(newRecord)) { return;} if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.canonicalState = newRecord; this._super$addCanonicalRecord(newRecord); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.flushCanonical = function() { //temporary fix to not remove newly created records if server returned null. //TODO remove once we have proper diffing if (this.inverseRecord && this.inverseRecord.get('isNew') && !this.canonicalState) { return; } this.inverseRecord = this.canonicalState; this.record.notifyBelongsToChanged(this.key); this._super$flushCanonical(); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addRecord = function(newRecord) { if (this.members.has(newRecord)) { return;} var type = this.relationshipMeta.type; Ember.assert("You cannot add a '" + newRecord.constructor.typeKey + "' record to the '" + this.record.constructor.typeKey + "." + this.key +"'. " + "You can only add a '" + type.typeKey + "' record to this relationship.", (function () { if (type.__isMixin) { return type.__mixin.detect(newRecord); } if (Ember.MODEL_FACTORY_INJECTIONS) { type = type.superclass; } return newRecord instanceof type; })()); if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.inverseRecord = newRecord; this._super$addRecord(newRecord); this.record.notifyBelongsToChanged(this.key); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecordPromise = function(newPromise) { var content = newPromise.get && newPromise.get('content'); Ember.assert("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined); this.setRecord(content); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeRecordFromOwn = function(record) { if (!this.members.has(record)) { return;} this.inverseRecord = null; this._super$removeRecordFromOwn(record); this.record.notifyBelongsToChanged(this.key); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function(record) { if (!this.canonicalMembers.has(record)) { return;} this.canonicalState = null; this._super$removeCanonicalRecordFromOwn(record); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.findRecord = function() { if (this.inverseRecord) { return this.store._findByRecord(this.inverseRecord); } else { return Ember.RSVP.Promise.resolve(null); } }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.fetchLink = function() { var self = this; return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function(record) { if (record) { self.addRecord(record); } return record; }); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.getRecord = function() { //TODO(Igor) flushCanonical here once our syncing is not stupid if (this.isAsync) { var promise; if (this.link) { var self = this; promise = this.findLink().then(function() { return self.findRecord(); }); } else { promise = this.findRecord(); } return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: promise, content: this.inverseRecord }); } else { Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.constructor.typeKey + "' with id " + this.record.get('id') + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", this.inverseRecord === null || !this.inverseRecord.get('isEmpty')); return this.inverseRecord; } }; var ember$data$lib$system$relationships$state$belongs$to$$default = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship; var ember$data$lib$system$relationships$state$create$$createRelationshipFor = function(record, relationshipMeta, store) { var inverseKey; var inverse = record.constructor.inverseFor(relationshipMeta.key); if (inverse) { inverseKey = inverse.name; } if (relationshipMeta.kind === 'hasMany') { return new ember$data$lib$system$relationships$state$has$many$$default(store, record, inverseKey, relationshipMeta); } else { return new ember$data$lib$system$relationships$state$belongs$to$$default(store, record, inverseKey, relationshipMeta); } }; var ember$data$lib$system$relationships$state$create$$default = ember$data$lib$system$relationships$state$create$$createRelationshipFor; var ember$data$lib$system$snapshot$$get = Ember.get; /** @class Snapshot @namespace DS @private @constructor @param {DS.Model} record The record to create a snapshot from */ function ember$data$lib$system$snapshot$$Snapshot(record) { this._attributes = Ember.create(null); this._belongsToRelationships = Ember.create(null); this._belongsToIds = Ember.create(null); this._hasManyRelationships = Ember.create(null); this._hasManyIds = Ember.create(null); record.eachAttribute(function(keyName) { this._attributes[keyName] = ember$data$lib$system$snapshot$$get(record, keyName); }, this); this.id = ember$data$lib$system$snapshot$$get(record, 'id'); this.record = record; this.type = record.constructor; this.typeKey = record.constructor.typeKey; // The following code is here to keep backwards compatibility when accessing // `constructor` directly. // // With snapshots you should use `type` instead of `constructor`. // // Remove for Ember Data 1.0. if (Ember.platform.hasPropertyAccessors) { var callDeprecate = true; Ember.defineProperty(this, 'constructor', { get: function() { // Ugly hack since accessing error.stack (done in `Ember.deprecate()`) // causes the internals of Chrome to access the constructor, which then // causes an infinite loop if accessed and calls `Ember.deprecate()` // again. if (callDeprecate) { callDeprecate = false; Ember.deprecate('Usage of `snapshot.constructor` is deprecated, use `snapshot.type` instead.'); callDeprecate = true; } return this.type; } }); } else { this.constructor = this.type; } } ember$data$lib$system$snapshot$$Snapshot.prototype = { constructor: ember$data$lib$system$snapshot$$Snapshot, /** The id of the snapshot's underlying record Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.id; // => '1' ``` @property id @type {String} */ id: null, /** The underlying record for this snapshot. Can be used to access methods and properties defined on the record. Example ```javascript var json = snapshot.record.toJSON(); ``` @property record @type {DS.Model} */ record: null, /** The type of the underlying record for this snapshot, as a subclass of DS.Model. @property type @type {subclass of DS.Model} */ type: null, /** The name of the type of the underlying record for this snapshot, as a string. @property typeKey @type {String} */ typeKey: null, /** Returns the value of an attribute. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attr('author'); // => 'Tomster' postSnapshot.attr('title'); // => 'Ember.js rocks' ``` Note: Values are loaded eagerly and cached when the snapshot is created. @method attr @param {String} keyName @return {Object} The attribute value or undefined */ attr: function(keyName) { if (keyName in this._attributes) { return this._attributes[keyName]; } throw new Ember.Error("Model '" + Ember.inspect(this.record) + "' has no attribute named '" + keyName + "' defined."); }, /** Returns all attributes and their corresponding values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Hello World' }); postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' } ``` @method attributes @return {Object} All attributes of the current snapshot */ attributes: function() { return Ember.copy(this._attributes); }, /** Returns the current value of a belongsTo relationship. `belongsTo` takes an optional hash of options as a second parameter, currently supported options are: - `id`: set to `true` if you only want the ID of the related record to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World' }); // store.createRecord('comment', { body: 'Lorem ipsum', post: post }); commentSnapshot.belongsTo('post'); // => DS.Snapshot commentSnapshot.belongsTo('post', { id: true }); // => '1' ``` Calling `belongsTo` will return a new Snapshot as long as there's any data available, such as an ID. If there's no data available `belongsTo` will return undefined. Note: Relationships are loaded lazily and cached upon first access. @method belongsTo @param {String} keyName @param {Object} [options] @return {DS.Snapshot|String|undefined} A snapshot or ID of a belongsTo relationship, or undefined */ belongsTo: function(keyName, options) { var id = options && options.id; var result; var relationship, inverseRecord; if (id && keyName in this._belongsToIds) { return this._belongsToIds[keyName]; } if (!id && keyName in this._belongsToRelationships) { return this._belongsToRelationships[keyName]; } relationship = this.record._relationships[keyName]; if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) { throw new Ember.Error("Model '" + Ember.inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined."); } inverseRecord = ember$data$lib$system$snapshot$$get(relationship, 'inverseRecord'); if (id) { if (inverseRecord) { result = ember$data$lib$system$snapshot$$get(inverseRecord, 'id'); } this._belongsToIds[keyName] = result; } else { if (inverseRecord) { result = inverseRecord._createSnapshot(); } this._belongsToRelationships[keyName] = result; } return result; }, /** Returns the current value of a hasMany relationship. `hasMany` takes an optional hash of options as a second parameter, currently supported options are: - `ids`: set to `true` if you only want the IDs of the related records to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] }); postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot] postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3'] ``` Note: Relationships are loaded lazily and cached upon first access. @method hasMany @param {String} keyName @param {Object} [options] @return {Array} An array of snapshots or IDs of a hasMany relationship */ hasMany: function(keyName, options) { var ids = options && options.ids; var results = []; var relationship, members; if (ids && keyName in this._hasManyIds) { return this._hasManyIds[keyName]; } if (!ids && keyName in this._hasManyRelationships) { return this._hasManyRelationships[keyName]; } relationship = this.record._relationships[keyName]; if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) { throw new Ember.Error("Model '" + Ember.inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined."); } members = ember$data$lib$system$snapshot$$get(relationship, 'members'); if (ids) { members.forEach(function(member) { results.push(ember$data$lib$system$snapshot$$get(member, 'id')); }); this._hasManyIds[keyName] = results; } else { members.forEach(function(member) { results.push(member._createSnapshot()); }); this._hasManyRelationships[keyName] = results; } return results; }, /** Iterates through all the attributes of the model, calling the passed function on each attribute. Example ```javascript snapshot.eachAttribute(function(name, meta) { // ... }); ``` @method eachAttribute @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachAttribute: function(callback, binding) { this.record.eachAttribute(callback, binding); }, /** Iterates through all the relationships of the model, calling the passed function on each relationship. Example ```javascript snapshot.eachRelationship(function(name, relationship) { // ... }); ``` @method eachRelationship @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.record.eachRelationship(callback, binding); }, /** @method get @param {String} keyName @return {Object} The property value @deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead */ get: function(keyName) { Ember.deprecate('Using DS.Snapshot.get() is deprecated. Use .attr(), .belongsTo() or .hasMany() instead.'); if (keyName === 'id') { return this.id; } if (keyName in this._attributes) { return this.attr(keyName); } var relationship = this.record._relationships[keyName]; if (relationship && relationship.relationshipMeta.kind === 'belongsTo') { return this.belongsTo(keyName); } if (relationship && relationship.relationshipMeta.kind === 'hasMany') { return this.hasMany(keyName); } return ember$data$lib$system$snapshot$$get(this.record, keyName); }, /** @method unknownProperty @param {String} keyName @return {Object} The property value @deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead */ unknownProperty: function(keyName) { return this.get(keyName); }, /** @method _createSnapshot @private */ _createSnapshot: function() { Ember.deprecate("You called _createSnapshot on what's already a DS.Snapshot. You shouldn't manually create snapshots in your adapter since the store passes snapshots to adapters by default."); return this; } }; var ember$data$lib$system$snapshot$$default = ember$data$lib$system$snapshot$$Snapshot; /** @module ember-data */ var ember$data$lib$system$model$model$$get = Ember.get; var ember$data$lib$system$model$model$$set = Ember.set; var ember$data$lib$system$model$model$$Promise = Ember.RSVP.Promise; var ember$data$lib$system$model$model$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$system$model$model$$map = Ember.ArrayPolyfills.map; var ember$data$lib$system$model$model$$intersection = Ember.EnumerableUtils.intersection; var ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS = [ 'attributes', 'currentState', 'data', 'relatedTypes', 'relationshipNames', 'relationships', 'relationshipsByName', 'transformedAttributes', 'store' ]; var ember$data$lib$system$model$model$$retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { return ember$data$lib$system$model$model$$get(ember$data$lib$system$model$model$$get(this, 'currentState'), key); }).readOnly(); var ember$data$lib$system$model$model$$_extractPivotNameCache = Ember.create(null); var ember$data$lib$system$model$model$$_splitOnDotCache = Ember.create(null); function ember$data$lib$system$model$model$$splitOnDot(name) { return ember$data$lib$system$model$model$$_splitOnDotCache[name] || ( (ember$data$lib$system$model$model$$_splitOnDotCache[name] = name.split('.')) ); } function ember$data$lib$system$model$model$$extractPivotName(name) { return ember$data$lib$system$model$model$$_extractPivotNameCache[name] || ( (ember$data$lib$system$model$model$$_extractPivotNameCache[name] = ember$data$lib$system$model$model$$splitOnDot(name)[0]) ); } // Like Ember.merge, but instead returns a list of keys // for values that fail a strict equality check // instead of the original object. function ember$data$lib$system$model$model$$mergeAndReturnChangedKeys(original, updates) { var changedKeys = []; if (!updates || typeof updates !== 'object') { return changedKeys; } var keys = Ember.keys(updates); var length = keys.length; var i, val, key; for (i = 0; i < length; i++) { key = keys[i]; val = updates[key]; if (original[key] !== val) { changedKeys.push(key); } original[key] = val; } return changedKeys; } /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var ember$data$lib$system$model$model$$Model = Ember.Object.extend(Ember.Evented, { _recordArrays: undefined, _relationships: undefined, store: null, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord('model'); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord('model'); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.get('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly */ isDirty: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('isDirty'); // true record.get('isSaving'); // false // Persisting the deletion var promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('isDirty'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** The `clientId` property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id. @property clientId @private @type {Number|String} */ clientId: null, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord('model'); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ currentState: ember$data$lib$system$model$states$$default.empty, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().catch(function() { record.get('errors').get('foo'); // [{message: 'foo should be a number.', attribute: 'foo'}] }); ``` The `errors` property us useful for displaying error messages to the user. ```handlebars <label>Username: {{input value=username}} </label> {{#each error in model.errors.username}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each error in model.errors.email}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each message in model.errors.messages}} <div class="error"> {{message}} </div> {{/each}} ``` @property errors @type {DS.Errors} */ errors: Ember.computed(function() { var errors = ember$data$lib$system$model$errors$$default.create(); errors.registerHandlers(this, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); return errors; }).readOnly(), /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function(options) { return this.store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ toJSON: function(options) { // container is for lazy transform lookups var serializer = ember$data$lib$serializers$json$serializer$$default.create({ container: this.container }); var snapshot = this._createSnapshot(); return serializer.serialize(snapshot, options); }, /** Fired when the record is ready to be interacted with, that is either loaded from the server or created locally. @event ready */ ready: function() { this.store.recordArrayManager.recordWasLoaded(this); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when a new record is commited to the server. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).readOnly(), _data: null, init: function() { this._super.apply(this, arguments); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = Ember.create(null); this._inFlightAttributes = Ember.create(null); this._relationships = {}; /* implicit relationships are relationship which have not been declared but the inverse side exists on another record somewhere For example if there was ``` App.Comment = DS.Model.extend({ name: DS.attr() }) ``` but there is also ``` App.Post = DS.Model.extend({ name: DS.attr(), comments: DS.hasMany('comment') }) ``` would have a implicit post relationship in order to be do things like remove ourselves from the post when we are deleted */ this._implicitRelationships = Ember.create(null); var model = this; //TODO Move into a getter for better perf this.constructor.eachRelationship(function(key, descriptor) { model._relationships[key] = ember$data$lib$system$relationships$state$create$$default(model, descriptor, model.store); }); }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = ember$data$lib$system$model$model$$get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = ember$data$lib$system$model$model$$extractPivotName(name); var currentState = ember$data$lib$system$model$model$$get(this, 'currentState'); var state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = ember$data$lib$system$model$model$$splitOnDot(name); var setups = []; var enters = []; var i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } ember$data$lib$system$model$model$$set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = ember$data$lib$system$model$model$$get(this, 'transaction'); if (transaction) { fn(transaction); } }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollback()` a delete after it was made. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollback(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this.send('deleteRecord'); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function() { this.deleteRecord(); return this.save(); }, /** @method unloadRecord @private */ unloadRecord: function() { if (this.isDestroyed) { return; } this.send('unloadRecord'); }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship(function(name, relationship) { var rel = this._relationships[name]; if (rel) { //TODO(Igor) figure out whether we want to clear or disconnect rel.clear(); rel.destroy(); } }, this); var model = this; ember$data$lib$system$model$model$$forEach.call(Ember.keys(this._implicitRelationships), function(key) { model._implicitRelationships[key].clear(); model._implicitRelationships[key].destroy(); }); }, disconnectRelationships: function() { this.eachRelationship(function(name, relationship) { this._relationships[name].disconnect(); }, this); var model = this; ember$data$lib$system$model$model$$forEach.call(Ember.keys(this._implicitRelationships), function(key) { model._implicitRelationships[key].disconnect(); }); }, reconnectRelationships: function() { this.eachRelationship(function(name, relationship) { this._relationships[name].reconnect(); }, this); var model = this; ember$data$lib$system$model$model$$forEach.call(Ember.keys(this._implicitRelationships), function(key) { model._implicitRelationships[key].reconnect(); }); }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { this._updatingRecordArraysLater = false; this.store.dataWasUpdated(this.constructor, this); }, /** When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.find('comment', 2, {post:1})` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method _preloadData @private @param {Object} preload */ _preloadData: function(preload) { var record = this; //TODO(Igor) consider the polymorphic case ember$data$lib$system$model$model$$forEach.call(Ember.keys(preload), function(key) { var preloadValue = ember$data$lib$system$model$model$$get(preload, key); var relationshipMeta = record.constructor.metaForProperty(key); if (relationshipMeta.isRelationship) { record._preloadRelationship(key, preloadValue); } else { ember$data$lib$system$model$model$$get(record, '_data')[key] = preloadValue; } }); }, _preloadRelationship: function(key, preloadValue) { var relationshipMeta = this.constructor.metaForProperty(key); var type = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany') { this._preloadHasMany(key, preloadValue, type); } else { this._preloadBelongsTo(key, preloadValue, type); } }, _preloadHasMany: function(key, preloadValue, type) { Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue)); var record = this; var recordsToSet = ember$data$lib$system$model$model$$map.call(preloadValue, function(recordToPush) { return record._convertStringOrNumberIntoRecord(recordToPush, type); }); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships[key].updateRecordsFromAdapter(recordsToSet); }, _preloadBelongsTo: function(key, preloadValue, type) { var recordToSet = this._convertStringOrNumberIntoRecord(preloadValue, type); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships[key].setRecord(recordToSet); }, _convertStringOrNumberIntoRecord: function(value, type) { if (Ember.typeOf(value) === 'string' || Ember.typeOf(value) === 'number') { return this.store.recordForId(type, value); } return value; }, /** @method _notifyProperties @private */ _notifyProperties: function(keys) { Ember.beginPropertyChanges(); var key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; this.notifyPropertyChange(key); } Ember.endPropertyChanges(); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```javascript App.Mascot = DS.Model.extend({ name: attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.set('name', 'Tomster'); person.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = ember$data$lib$system$model$model$$get(this, '_data'); var newData = ember$data$lib$system$model$model$$get(this, '_attributes'); var diffData = {}; var prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { var changedKeys; ember$data$lib$system$model$model$$set(this, 'isError', false); if (data) { changedKeys = ember$data$lib$system$model$model$$mergeAndReturnChangedKeys(this._data, data); } else { ember$data$lib$system$merge$$default(this._data, this._inFlightAttributes); } this._inFlightAttributes = Ember.create(null); this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this._notifyProperties(changedKeys); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; Ember.run.schedule('actions', this, this.updateRecordArrays); }, /** @method setupData @private @param {Object} data */ setupData: function(data) { Ember.assert("Expected an object as `data` in `setupData`", Ember.typeOf(data) === 'object'); var changedKeys = ember$data$lib$system$model$model$$mergeAndReturnChangedKeys(this._data, data); this.pushedData(); this._notifyProperties(changedKeys); }, materializeId: function(id) { ember$data$lib$system$model$model$$set(this, 'id', id); }, materializeAttributes: function(attributes) { Ember.assert("Must pass an object to materializeAttributes", !!attributes); ember$data$lib$system$merge$$default(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, /** If the model `isDirty` this function will discard any unsaved changes Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback */ rollback: function() { var dirtyKeys = Ember.keys(this._attributes); this._attributes = Ember.create(null); if (ember$data$lib$system$model$model$$get(this, 'isError')) { this._inFlightAttributes = Ember.create(null); ember$data$lib$system$model$model$$set(this, 'isError', false); } //Eventually rollback will always work for relationships //For now we support it only out of deleted state, because we //have an explicit way of knowing when the server acked the relationship change if (ember$data$lib$system$model$model$$get(this, 'isDeleted')) { this.reconnectRelationships(); } if (ember$data$lib$system$model$model$$get(this, 'isNew')) { this.clearRelationships(); } if (!ember$data$lib$system$model$model$$get(this, 'isValid')) { this._inFlightAttributes = Ember.create(null); } this.send('rolledBack'); this._notifyProperties(dirtyKeys); }, /** @method _createSnapshot @private */ _createSnapshot: function() { return new ember$data$lib$system$snapshot$$default(this); }, toStringExtension: function() { return ember$data$lib$system$model$model$$get(this, 'id'); }, /** Save the record and persist any changes to the record to an external source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function() { // Success callback }, function() { // Error callback }); ``` @method save @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function() { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.store.scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = Ember.create(null); return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```javascript App.ModelViewRoute = Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload().then(function(model) { // do something with the reloaded model }); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { ember$data$lib$system$model$model$$set(this, 'isReloading', true); var record = this; var promiseLabel = "DS: Model#reload of " + this; var promise = new ember$data$lib$system$model$model$$Promise(function(resolve) { record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags")['finally'](function () { record.updateRecordArrays(); }); return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: promise }); }, // FOR USE DURING COMMIT PROCESS /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var recordErrors = ember$data$lib$system$model$model$$get(this, 'errors'); for (var key in errors) { if (!errors.hasOwnProperty(key)) { continue; } recordErrors.add(key, errors[key]); } this._saveWasRejected(); }, /** @method adapterDidError @private */ adapterDidError: function() { this.send('becameError'); ember$data$lib$system$model$model$$set(this, 'isError', true); this._saveWasRejected(); }, _saveWasRejected: function() { var keys = Ember.keys(this._inFlightAttributes); for (var i=0; i < keys.length; i++) { if (this._attributes[keys[i]] === undefined) { this._attributes[keys[i]] = this._inFlightAttributes[keys[i]]; } } this._inFlightAttributes = Ember.create(null); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param {String} name */ trigger: function() { var length = arguments.length; var args = new Array(length - 1); var name = arguments[0]; for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } Ember.tryInvoke(this, name, args); this._super.apply(this, arguments); }, triggerLater: function() { var length = arguments.length; var args = new Array(length); for (var i = 0; i < length; i++) { args[i] = arguments[i]; } if (this._deferredTriggers.push(args) !== 1) { return; } Ember.run.schedule('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l= this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, willDestroy: function() { this._super.apply(this, arguments); this.clearRelationships(); }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function(props) { var constructor = this.constructor; Ember.assert('`' + ember$data$lib$system$model$model$$intersection(Ember.keys(props), ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !ember$data$lib$system$model$model$$intersection(Ember.keys(props), ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS)[0]); }, attr: function() { Ember.assert("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); }, belongsTo: function() { Ember.assert("The `belongsTo` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); }, hasMany: function() { Ember.assert("The `hasMany` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); } }); ember$data$lib$system$model$model$$Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: ember$data$lib$system$model$model$$Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); var ember$data$lib$system$model$model$$default = ember$data$lib$system$model$model$$Model; /** @module ember-data */ var ember$data$lib$system$model$attributes$$get = Ember.get; /** @class Model @namespace DS */ ember$data$lib$system$model$model$$default.reopenClass({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); var attributes = Ember.get(App.Person, 'attributes') attributes.forEach(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: Ember.computed(function() { var map = ember$data$lib$system$map$$Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }).readOnly(), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: Ember.computed(function() { var map = ember$data$lib$system$map$$Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); App.Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachAttribute: function(callback, binding) { ember$data$lib$system$model$attributes$$get(this, 'attributes').forEach(function(meta, name) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); App.Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachTransformedAttribute: function(callback, binding) { ember$data$lib$system$model$attributes$$get(this, 'transformedAttributes').forEach(function(type, name) { callback.call(binding, name, type); }); } }); ember$data$lib$system$model$model$$default.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function ember$data$lib$system$model$attributes$$getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue.apply(null, arguments); } else { return options.defaultValue; } } function ember$data$lib$system$model$attributes$$hasValue(record, key) { return key in record._attributes || key in record._inFlightAttributes || record._data.hasOwnProperty(key); } function ember$data$lib$system$model$attributes$$getValue(record, key) { if (key in record._attributes) { return record._attributes[key]; } else if (key in record._inFlightAttributes) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } function ember$data$lib$system$model$attributes$$attr(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { options = options || {}; } var meta = { type: type, isAttribute: true, options: options }; return Ember.computed(function(key, value) { if (arguments.length > 1) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id'); var oldValue = ember$data$lib$system$model$attributes$$getValue(this, key); if (value !== oldValue) { // Add the new value to the changed attributes hash; it will get deleted by // the 'didSetProperty' handler if it is no different from the original value this._attributes[key] = value; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); } return value; } else if (ember$data$lib$system$model$attributes$$hasValue(this, key)) { return ember$data$lib$system$model$attributes$$getValue(this, key); } else { return ember$data$lib$system$model$attributes$$getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).meta(meta); } var ember$data$lib$system$model$attributes$$default = ember$data$lib$system$model$attributes$$attr; var ember$data$lib$system$model$$default = ember$data$lib$system$model$model$$default; //Stanley told me to do this var ember$data$lib$system$store$$Backburner = Ember.__loader.require('backburner')['default'] || Ember.__loader.require('backburner')['Backburner']; //Shim Backburner.join if (!ember$data$lib$system$store$$Backburner.prototype.join) { var ember$data$lib$system$store$$isString = function(suspect) { return typeof suspect === 'string'; }; ember$data$lib$system$store$$Backburner.prototype.join = function(/*target, method, args */) { var method, target; if (this.currentInstance) { var length = arguments.length; if (length === 1) { method = arguments[0]; target = null; } else { target = arguments[0]; method = arguments[1]; } if (ember$data$lib$system$store$$isString(method)) { method = target[method]; } if (length === 1) { return method(); } else if (length === 2) { return method.call(target); } else { var args = new Array(length - 2); for (var i =0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } return method.apply(target, args); } } else { return this.run.apply(this, arguments); } }; } var ember$data$lib$system$store$$get = Ember.get; var ember$data$lib$system$store$$set = Ember.set; var ember$data$lib$system$store$$once = Ember.run.once; var ember$data$lib$system$store$$isNone = Ember.isNone; var ember$data$lib$system$store$$forEach = Ember.EnumerableUtils.forEach; var ember$data$lib$system$store$$indexOf = Ember.EnumerableUtils.indexOf; var ember$data$lib$system$store$$map = Ember.EnumerableUtils.map; var ember$data$lib$system$store$$Promise = Ember.RSVP.Promise; var ember$data$lib$system$store$$copy = Ember.copy; var ember$data$lib$system$store$$Store; var ember$data$lib$system$store$$camelize = Ember.String.camelize; var ember$data$lib$system$store$$Service = Ember.Service; if (!ember$data$lib$system$store$$Service) { ember$data$lib$system$store$$Service = Ember.Object; } // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. function ember$data$lib$system$store$$coerceId(id) { return id == null ? null : id+''; } /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```javascript MyApp.ApplicationStore = DS.Store.extend(); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `find()` method: ```javascript store.find('person', 123).then(function (person) { }); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```javascript MyApp.ApplicationAdapter = MyApp.CustomAdapter ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates (full or partial) that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#all()`, `store#findAll()` or `store#filter()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Service */ ember$data$lib$system$store$$Store = ember$data$lib$system$store$$Service.extend({ /** @method init @private */ init: function() { this._backburner = new ember$data$lib$system$store$$Backburner(['normalizeRelationships', 'syncRelationships', 'finished']); // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = ember$data$lib$system$record$array$manager$$default.create({ store: this }); this._pendingSave = []; this._containerCache = Ember.create(null); //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = ember$data$lib$system$map$$Map.create(); }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '-rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { var snapshot = record._createSnapshot(); return this.serializerFor(snapshot.typeKey).serialize(snapshot, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: Ember.computed('adapter', function() { var adapter = ember$data$lib$system$store$$get(this, 'adapter'); Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof ember$data$lib$system$adapter$$Adapter)); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container, store: this }); } return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function(typeName, inputProperties) { var type = this.modelFor(typeName); var properties = ember$data$lib$system$store$$copy(inputProperties) || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (ember$data$lib$system$store$$isNone(properties.id)) { properties.id = this._generateId(type, properties); } // Coerce ID to a string properties.id = ember$data$lib$system$store$$coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} type @param {Object} properties from the new record @return {String} if the adapter can generate one, an ID */ _generateId: function(type, properties) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this, type, properties); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- You can optionally `preload` specific attributes and relationships that you know of by passing them as the third argument to find. For example, if your Ember route looks like `/posts/1/comments/2` and your API route for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment without fetching the post you can pass in the post to the `find` call: ```javascript store.find('comment', 2, {post: 1}); ``` If you have access to the post model you can also pass the model itself: ```javascript store.find('post', 1).then(function (myPostModel) { store.find('comment', 2, {post: myPostModel}); }); ``` This way, your adapter's `find` or `buildURL` method will be able to look up the relationship on the record and construct the nested URL without having to first fetch the post. --- To find all records for a type, call `find` with no additional parameters: ```javascript store.find('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. The promise will resolve into all records of this type present in the store, even if the server only returns a subset of them. --- To find a record by a query, call `find` with a hash as the second parameter: ```javascript store.find('person', { page: 1 }); ``` By passing an object `{page: 1}` as an argument to the find method, it delegates to the adapter's findQuery method. The adapter then makes a call to the server, transforming the object `{page: 1}` as parameters that are sent along, and will return a RecordArray when the promise resolves. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. The call made to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?page=1" Processing by Api::V1::PersonsController#index as HTML Parameters: {"page"=>"1"} ``` If you do something like this: ```javascript store.find('person', {ids: [1, 2, 3]}); ``` The call to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" Processing by Api::V1::PersonsController#index as HTML Parameters: {"ids"=>["1", "2", "3"]} ``` @method find @param {String or subclass of DS.Model} type @param {Object|String|Integer|null} id @param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models @return {Promise} promise */ find: function(type, id, preload) { Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1); Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id)); if (arguments.length === 1) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, ember$data$lib$system$store$$coerceId(id), preload); }, /** This method returns a fresh record for a given type and id combination. If a record is available for the given type/id combination, then it will fetch this record from the store and call `reload()` on it. That will fire a request to server and return a promise that will resolve once the record has been reloaded. If there's no record corresponding in the store it will simply call `store.find`. Example ```javascript App.PostRoute = Ember.Route.extend({ model: function(params) { return this.store.fetchById('post', params.post_id); } }); ``` @method fetchById @param {String or subclass of DS.Model} type @param {String|Integer} id @param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models @return {Promise} promise */ fetchById: function(type, id, preload) { if (this.hasRecordForId(type, id)) { return this.getById(type, id).reload(); } else { return this.find(type, id, preload); } }, /** This method returns a fresh collection from the server, regardless of if there is already records in the store or not. @method fetchAll @param {String or subclass of DS.Model} type @return {Promise} promise */ fetchAll: function(type) { type = this.modelFor(type); return this._fetchAll(type, this.all(type)); }, /** @method fetch @param {String or subclass of DS.Model} type @param {String|Integer} id @param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models @return {Promise} promise @deprecated Use [fetchById](#method_fetchById) instead */ fetch: function(type, id, preload) { Ember.deprecate('Using store.fetch() has been deprecated. Use store.fetchById for fetching individual records or store.fetchAll for collections'); return this.fetchById(type, id, preload); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String or subclass of DS.Model} type @param {String|Integer} id @param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models @return {Promise} promise */ findById: function(typeName, id, preload) { var type = this.modelFor(typeName); var record = this.recordForId(type, id); return this._findByRecord(record, preload); }, _findByRecord: function(record, preload) { var fetchedRecord; if (preload) { record._preloadData(preload); } if (ember$data$lib$system$store$$get(record, 'isEmpty')) { fetchedRecord = this.scheduleFetch(record); //TODO double check about reloading } else if (ember$data$lib$system$store$$get(record, 'isLoading')) { fetchedRecord = record._loadingPromise; } return ember$data$lib$system$promise$proxies$$promiseObject(fetchedRecord || record, "DS: Store#findByRecord " + record.typeKey + " with id: " + ember$data$lib$system$store$$get(record, 'id')); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} type @param {Array} ids @return {Promise} promise */ findByIds: function(type, ids) { var store = this; return ember$data$lib$system$promise$proxies$$promiseArray(Ember.RSVP.all(ember$data$lib$system$store$$map(ids, function(id) { return store.findById(type, id); })).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete")); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @return {Promise} promise */ fetchRecord: function(record) { var type = record.constructor; var id = ember$data$lib$system$store$$get(record, 'id'); var adapter = this.adapterFor(type); Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", typeof adapter.find === 'function'); var promise = ember$data$lib$system$store$finders$$_find(adapter, this, type, id, record); return promise; }, scheduleFetchMany: function(records) { return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(records, this.scheduleFetch, this)); }, scheduleFetch: function(record) { var type = record.constructor; if (ember$data$lib$system$store$$isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } var resolver = Ember.RSVP.defer('Fetching ' + type + 'with id: ' + record.get('id')); var recordResolverPair = { record: record, resolver: resolver }; var promise = resolver.promise; record.loadingData(promise); if (!this._pendingFetch.get(type)) { this._pendingFetch.set(type, [recordResolverPair]); } else { this._pendingFetch.get(type).push(recordResolverPair); } Ember.run.scheduleOnce('afterRender', this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function() { if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch = ember$data$lib$system$map$$Map.create(); }, _flushPendingFetchForType: function (recordResolverPairs, type) { var store = this; var adapter = store.adapterFor(type); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var records = Ember.A(recordResolverPairs).mapBy('record'); function _fetchRecord(recordResolverPair) { recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record)); } function resolveFoundRecords(records) { ember$data$lib$system$store$$forEach(records, function(record) { var pair = Ember.A(recordResolverPairs).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.resolve(record); } }); return records; } function makeMissingRecordsRejector(requestedRecords) { return function rejectMissingRecords(resolvedRecords) { resolvedRecords = Ember.A(resolvedRecords); var missingRecords = requestedRecords.reject(function(record) { return resolvedRecords.contains(record); }); if (missingRecords.length) { Ember.warn('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + Ember.inspect(Ember.A(missingRecords).mapBy('id')), false); } rejectRecords(missingRecords); }; } function makeRecordsRejector(records) { return function (error) { rejectRecords(records, error); }; } function rejectRecords(records, error) { ember$data$lib$system$store$$forEach(records, function(record) { var pair = Ember.A(recordResolverPairs).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.reject(error); } }); } if (recordResolverPairs.length === 1) { _fetchRecord(recordResolverPairs[0]); } else if (shouldCoalesce) { // TODO: Improve records => snapshots => records => snapshots // // We want to provide records to all store methods and snapshots to all // adapter methods. To make sure we're doing that we're providing an array // of snapshots to adapter.groupRecordsForFindMany(), which in turn will // return grouped snapshots instead of grouped records. // // But since the _findMany() finder is a store method we need to get the // records from the grouped snapshots even though the _findMany() finder // will once again convert the records to snapshots for adapter.findMany() var snapshots = Ember.A(records).invoke('_createSnapshot'); var groups = adapter.groupRecordsForFindMany(this, snapshots); ember$data$lib$system$store$$forEach(groups, function (groupOfSnapshots) { var groupOfRecords = Ember.A(groupOfSnapshots).mapBy('record'); var requestedRecords = Ember.A(groupOfRecords); var ids = requestedRecords.mapBy('id'); if (ids.length > 1) { ember$data$lib$system$store$finders$$_findMany(adapter, store, type, ids, requestedRecords). then(resolveFoundRecords). then(makeMissingRecordsRejector(requestedRecords)). then(null, makeRecordsRejector(requestedRecords)); } else if (ids.length === 1) { var pair = Ember.A(recordResolverPairs).findBy('record', groupOfRecords[0]); _fetchRecord(pair); } else { Ember.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); } }); } else { ember$data$lib$system$store$$forEach(recordResolverPairs, _fetchRecord); } }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.getById('post', 1); post.get('id'); // 1 ``` @method getById @param {String or subclass of DS.Model} type @param {String|Integer} id @return {DS.Model|null} record */ getById: function(type, id) { if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @return {Promise} promise */ reloadRecord: function(record) { var type = record.constructor; var adapter = this.adapterFor(type); var id = ember$data$lib$system$store$$get(record, 'id'); Ember.assert("You cannot reload a record without an ID", id); Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to reload a record but your adapter does not implement `find`", typeof adapter.find === 'function'); return this.scheduleFetch(record); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Boolean} */ hasRecordForId: function(typeName, inputId) { var type = this.modelFor(typeName); var id = ember$data$lib$system$store$$coerceId(inputId); var record = this.typeMapFor(type).idToRecord[id]; return !!record && ember$data$lib$system$store$$get(record, 'isLoaded'); }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {DS.Model} record */ recordForId: function(typeName, inputId) { var type = this.modelFor(typeName); var id = ember$data$lib$system$store$$coerceId(inputId); var idToRecord = this.typeMapFor(type).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array} records @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} records */ findMany: function(records) { var store = this; return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(records, function(record) { return store._findByRecord(record); })); }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String or subclass of DS.Model} type @return {Promise} promise */ findHasMany: function(owner, link, type) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", typeof adapter.findHasMany === 'function'); return ember$data$lib$system$store$finders$$_findHasMany(adapter, this, owner, link, type); }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function(owner, link, relationship) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", typeof adapter.findBelongsTo === 'function'); return ember$data$lib$system$store$finders$$_findBelongsTo(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ findQuery: function(typeName, query) { var type = this.modelFor(typeName); var array = this.recordArrayManager .createAdapterPopulatedRecordArray(type, query); var adapter = this.adapterFor(type); Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", typeof adapter.findQuery === 'function'); return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findQuery(adapter, this, type, query, array)); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {String or subclass of DS.Model} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(typeName) { return this.fetchAll(typeName); }, /** @method _fetchAll @private @param {DS.Model} type @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function(type, array) { var adapter = this.adapterFor(type); var sinceToken = this.typeMapFor(type).metadata.since; ember$data$lib$system$store$$set(array, 'isUpdating', true); Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", typeof adapter.findAll === 'function'); return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findAll(adapter, this, type, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; ember$data$lib$system$store$$set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type in the store. Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use [store.find](#method_find). Also note that multiple calls to `all` for a given type will always return the same `RecordArray`. Example ```javascript var localPosts = store.all('post'); ``` @method all @param {String or subclass of DS.Model} type @return {DS.RecordArray} */ all: function(typeName) { var type = this.modelFor(typeName); var typeMap = this.typeMapFor(type); var findAllCache = typeMap.findAllCache; if (findAllCache) { this.recordArrayManager.updateFilter(findAllCache, type); return findAllCache; } var array = this.recordArrayManager.createRecordArray(type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. ```javascript store.unloadAll('post'); ``` @method unloadAll @param {String or subclass of DS.Model} type */ unloadAll: function(type) { var modelType = this.modelFor(type); var typeMap = this.typeMapFor(modelType); var records = typeMap.records.slice(); var record; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.findAllCache = null; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The filter function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. Example ```javascript store.filter('post', function(post) { return post.get('unread'); }); ``` The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query, which is the equivalent of calling [find](#method_find) with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function. The query itself is not used to filter records, it's only sent to your server for you to be able to do server-side filtering. The filter function will be applied on the returned results regardless. Example ```javascript store.filter('post', { unread: true }, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String or subclass of DS.Model} type @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function(type, query, filter) { var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(type, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(type, filter); } promise = promise || ember$data$lib$system$store$$Promise.cast(array); return ember$data$lib$system$promise$proxies$$promiseArray(promise.then(function() { return array; }, null, "DS: Store#filter of " + type)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.find('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String or subclass of DS.Model} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !ember$data$lib$system$store$$get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String or subclass of DS.Model} typeName @return {object} */ metadataFor: function(typeName) { var type = this.modelFor(typeName); return this.typeMapFor(type).metadata; }, /** This method sets the metadata for a specific type. @method setMetadataFor @param {String or subclass of DS.Model} typeName @param {Object} metadata metadata to set @return {object} */ setMetadataFor: function(typeName, metadata) { var type = this.modelFor(typeName); Ember.merge(this.typeMapFor(type).metadata, metadata); }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {DS.Model} record */ dataWasUpdated: function(type, record) { this.recordArrayManager.recordDidChange(record); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); ember$data$lib$system$store$$once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; ember$data$lib$system$store$$forEach(pending, function(tuple) { var record = tuple[0]; var resolver = tuple[1]; var adapter = this.adapterFor(record.constructor); var operation; if (ember$data$lib$system$store$$get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(record); } else if (ember$data$lib$system$store$$get(record, 'isNew')) { operation = 'createRecord'; } else if (ember$data$lib$system$store$$get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(ember$data$lib$system$store$$_commit(adapter, this, operation, record)); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records this._backburner.schedule('normalizeRelationships', this, '_setupRelationships', record, record.constructor, data); this.updateId(record, data); } //We first make sure the primary data has been updated //TODO try to move notification to the user to the end of the runloop record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = ember$data$lib$system$store$$get(record, 'id'); var id = ember$data$lib$system$store$$coerceId(data.id); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(record.constructor).idToRecord[id] = record; ember$data$lib$system$store$$set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param {subclass of DS.Model} type @return {Object} typeMap */ typeMapFor: function(type) { var typeMaps = ember$data$lib$system$store$$get(this, 'typeMaps'); var guid = Ember.guidFor(type); var typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: Ember.create(null), records: [], metadata: Ember.create(null), type: type }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {String or subclass of DS.Model} type @param {Object} data */ _load: function(type, data) { var id = ember$data$lib$system$store$$coerceId(data.id); var record = this.recordForId(type, id); record.setupData(data); this.recordArrayManager.recordDidChange(record); return record; }, /* In case someone defined a relationship to a mixin, for example: ``` var Comment = DS.Model.extend({ owner: belongsTo('commentable'. { polymorphic: true}) }); var Commentable = Ember.Mixin.create({ comments: hasMany('comment') }); ``` we want to look up a Commentable class which has all the necessary relationship metadata. Thus, we look up the mixin and create a mock DS.Model, so we can access the relationship CPs of the mixin (`comments`) in this case */ _modelForMixin: function(key) { var registry = this.container._registry ? this.container._registry : this.container; var mixin = registry.resolve('mixin:' + key); if (mixin) { //Cache the class as a model registry.register('model:' + key, DS.Model.extend(mixin)); } var factory = this.modelFactoryFor(key); if (factory) { factory.__isMixin = true; factory.__mixin = mixin; } return factory; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String or subclass of DS.Model} key @return {subclass of DS.Model} */ modelFor: function(key) { var factory; if (typeof key === 'string') { factory = this.modelFactoryFor(key); if (!factory) { //Support looking up mixins as base types for polymorphic relationships factory = this._modelForMixin(key); } if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); } factory.typeKey = factory.typeKey || this._normalizeTypeKey(key); } else { // A factory already supplied. Ensure it has a normalized key. factory = key; if (factory.typeKey) { factory.typeKey = this._normalizeTypeKey(factory.typeKey); } } factory.store = this; return factory; }, modelFactoryFor: function(key) { return this.container.lookupFactory('model:' + key); }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's [normalize](#method_normalize) method is a convenience helper for converting a json payload into the form Ember Data expects. ```js store.push('person', store.normalize('person', data)); ``` This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String or subclass of DS.Model} type @param {Object} data @return {DS.Model} the record that was created or updated. */ push: function(typeName, data) { Ember.assert("Expected an object as `data` in a call to `push` for " + typeName + " , but was " + data, Ember.typeOf(data) === 'object'); Ember.assert("You must include an `id` for " + typeName + " in an object passed to `push`", data.id != null && data.id !== ''); var type = this.modelFor(typeName); var filter = Ember.EnumerableUtils.filter; // If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload // contains unknown keys, log a warning. if (Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS) { Ember.warn("The payload for '" + type.typeKey + "' contains these unknown keys: " + Ember.inspect(filter(Ember.keys(data), function(key) { return !(key === 'id' || key === 'links' || ember$data$lib$system$store$$get(type, 'fields').has(key) || key.match(/Type$/)); })) + ". Make sure they've been defined in your model.", filter(Ember.keys(data), function(key) { return !(key === 'id' || key === 'links' || ember$data$lib$system$store$$get(type, 'fields').has(key) || key.match(/Type$/)); }).length === 0 ); } // Actually load the record into the store. this._load(type, data); var record = this.recordForId(type, data.id); var store = this; this._backburner.join(function() { store._backburner.schedule('normalizeRelationships', store, '_setupRelationships', record, type, data); }); return record; }, _setupRelationships: function(record, type, data) { // If the payload contains relationships that are specified as // IDs, normalizeRelationships will convert them into DS.Model instances // (possibly unloaded) before we push the payload into the // store. data = ember$data$lib$system$store$$normalizeRelationships(this, type, data); // Now that the pushed record as well as any related records // are in the store, create the data structures used to track // relationships. ember$data$lib$system$store$$setupRelationships(this, record, data); }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. However, the serializer itself (processing this data via `normalizePayload`) will not know which model it is deserializing. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; App.PostSerializer = DS.JSONSerializer; store.pushPayload('comment', pushData); // Will use the ApplicationSerializer store.pushPayload('post', pushData); // Will use the PostSerializer ``` @method pushPayload @param {String} type Optionally, a model used to determine which serializer will be used @param {Object} payload */ pushPayload: function (type, inputPayload) { var serializer; var payload; if (!inputPayload) { payload = type; serializer = ember$data$lib$system$store$$defaultSerializer(this.container); Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", typeof serializer.pushPayload === 'function'); } else { payload = inputPayload; serializer = this.serializerFor(type); } var store = this; this._adapterRun(function() { serializer.pushPayload(store, payload); }); }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { var modelName = message.model; var data = message.data; store.push(modelName, store.normalize(modelName, data)); }); ``` @method normalize @param {String} type The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function (type, payload) { var serializer = this.serializerFor(type); var model = this.modelFor(type); return serializer.normalize(model, payload); }, /** @method update @param {String} type @param {Object} data @return {DS.Model} the record that was updated. @deprecated Use [push](#method_push) instead */ update: function(type, data) { Ember.deprecate('Using store.update() has been deprecated since store.push() now handles partial updates. You should use store.push() instead.'); return this.push(type, data); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String or subclass of DS.Model} type @param {Array} datas @return {Array} */ pushMany: function(type, datas) { var length = datas.length; var result = new Array(length); for (var i = 0; i < length; i++) { result[i] = this.push(type, datas[i]); } return result; }, /** @method metaForType @param {String or subclass of DS.Model} typeName @param {Object} metadata @deprecated Use [setMetadataFor](#method_setMetadataFor) instead */ metaForType: function(typeName, metadata) { Ember.deprecate('Using store.metaForType() has been deprecated. Use store.setMetadataFor() to set metadata for a specific type.'); this.setMetadataFor(typeName, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @return {DS.Model} record */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type); var idToRecord = typeMap.idToRecord; Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); Ember.assert("`" + Ember.inspect(type)+ "` does not appear to be an ember-data model", (typeof type._create === 'function') ); // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, //Called by the state machine to notify the store that the record is ready to be interacted with recordWasLoaded: function(record) { this.recordArrayManager.recordWasLoaded(record); }, // ............... // . DESTRUCTION . // ............... /** @method dematerializeRecord @private @param {DS.Model} record @deprecated Use [unloadRecord](#method_unloadRecord) instead */ dematerializeRecord: function(record) { Ember.deprecate('Using store.dematerializeRecord() has been deprecated since it was intended for private use only. You should use store.unloadRecord() instead.'); this._dematerializeRecord(record); }, /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method _dematerializeRecord @private @param {DS.Model} record */ _dematerializeRecord: function(record) { var type = record.constructor; var typeMap = this.typeMapFor(type); var id = ember$data$lib$system$store$$get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = ember$data$lib$system$store$$indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns an instance of the adapter for a given type. For example, `adapterFor('person')` will return an instance of `App.PersonAdapter`. If no `App.PersonAdapter` is found, this method will look for an `App.ApplicationAdapter` (the default adapter for your entire application). If no `App.ApplicationAdapter` is found, it will return the value of the `defaultAdapter`. @method adapterFor @private @param {String or subclass of DS.Model} type @return DS.Adapter */ adapterFor: function(type) { if (type !== 'application') { type = this.modelFor(type); } var adapter = this.lookupAdapter(type.typeKey) || this.lookupAdapter('application'); return adapter || ember$data$lib$system$store$$get(this, 'defaultAdapter'); }, _adapterRun: function (fn) { return this._backburner.run(fn); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). if no `App.ApplicationSerializer` is found, it will attempt to get the `defaultSerializer` from the `PersonAdapter` (`adapterFor('person')`). If a serializer cannot be found on the adapter, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String or subclass of DS.Model} type the record to serialize @return {DS.Serializer} */ serializerFor: function(type) { if (type !== 'application') { type = this.modelFor(type); } var serializer = this.lookupSerializer(type.typeKey) || this.lookupSerializer('application'); if (!serializer) { var adapter = this.adapterFor(type); serializer = this.lookupSerializer(ember$data$lib$system$store$$get(adapter, 'defaultSerializer')); } if (!serializer) { serializer = this.lookupSerializer('-default'); } return serializer; }, /** Retrieve a particular instance from the container cache. If not found, creates it and placing it in the cache. Enabled a store to manage local instances of adapters and serializers. @method retrieveManagedInstance @private @param {String} type the object type @param {String} type the object name @return {Ember.Object} */ retrieveManagedInstance: function(type, name) { var key = type+":"+name; if (!this._containerCache[key]) { var instance = this.container.lookup(key); if (instance) { ember$data$lib$system$store$$set(instance, 'store', this); this._containerCache[key] = instance; } } return this._containerCache[key]; }, lookupAdapter: function(name) { return this.retrieveManagedInstance('adapter', name); }, lookupSerializer: function(name) { return this.retrieveManagedInstance('serializer', name); }, willDestroy: function() { var typeMaps = this.typeMaps; var keys = Ember.keys(typeMaps); var types = ember$data$lib$system$store$$map(keys, byType); this.recordArrayManager.destroy(); ember$data$lib$system$store$$forEach(types, this.unloadAll, this); function byType(entry) { return typeMaps[entry]['type']; } for (var cacheKey in this._containerCache) { this._containerCache[cacheKey].destroy(); delete this._containerCache[cacheKey]; } delete this._containerCache; }, /** All typeKeys are camelCase internally. Changing this function may require changes to other normalization hooks (such as typeForRoot). @method _normalizeTypeKey @private @param {String} type @return {String} if the adapter can generate one, an ID */ _normalizeTypeKey: function(key) { return ember$data$lib$system$store$$camelize(ember$inflector$lib$lib$system$string$$singularize(key)); } }); function ember$data$lib$system$store$$normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { var kind = relationship.kind; var value = data[key]; if (kind === 'belongsTo') { ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, value); } }); return data; } function ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, id) { if (ember$data$lib$system$store$$isNone(id) || id instanceof ember$data$lib$system$model$$default) { return; } Ember.assert("A " + relationship.parentType + " record was pushed into the store with the value of " + key + " being " + Ember.inspect(id) + ", but " + key + " is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.", !Ember.isArray(id)); var type; if (typeof id === 'number' || typeof id === 'string') { type = ember$data$lib$system$store$$typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // hasMany polymorphic Ember.assert('Ember Data expected a number or string to represent the record(s) in the `' + relationship.key + '` relationship instead it found an object. If this is a polymorphic relationship please specify a `type` key. If this is an embedded relationship please include the `DS.EmbeddedRecordsMixin` and specify the `' + relationship.key +'` property in your serializer\'s attrs object.', id.type); data[key] = store.recordForId(id.type, id.id); } } function ember$data$lib$system$store$$typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, ids) { if (ember$data$lib$system$store$$isNone(ids)) { return; } Ember.assert("A " + relationship.parentType + " record was pushed into the store with the value of " + key + " being '" + Ember.inspect(ids) + "', but " + key + " is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.", Ember.isArray(ids)); for (var i=0, l=ids.length; i<l; i++) { ember$data$lib$system$store$$deserializeRecordId(store, ids, i, relationship, ids[i]); } } // Delegation to the adapter and promise management function ember$data$lib$system$store$$defaultSerializer(container) { return container.lookup('serializer:application') || container.lookup('serializer:-default'); } function ember$data$lib$system$store$$_commit(adapter, store, operation, record) { var type = record.constructor; var snapshot = record._createSnapshot(); var promise = adapter[operation](store, type, snapshot); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type); var label = "DS: Extract and notify about " + operation + " completion of " + record; Ember.assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !==undefined); promise = ember$data$lib$system$store$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, record)); return promise.then(function(adapterPayload) { var payload; store._adapterRun(function() { if (adapterPayload) { payload = serializer.extract(store, type, adapterPayload, ember$data$lib$system$store$$get(record, 'id'), operation); } else { payload = adapterPayload; } store.didSaveRecord(record, payload); }); return record; }, function(reason) { if (reason instanceof ember$data$lib$system$adapter$$InvalidError) { var errors = serializer.extractErrors(store, type, reason.errors, ember$data$lib$system$store$$get(record, 'id')); store.recordWasInvalid(record, errors); reason = new ember$data$lib$system$adapter$$InvalidError(errors); } else { store.recordWasError(record, reason); } throw reason; }, label); } function ember$data$lib$system$store$$setupRelationships(store, record, data) { var type = record.constructor; type.eachRelationship(function(key, descriptor) { var kind = descriptor.kind; var value = data[key]; var relationship = record._relationships[key]; if (data.links && data.links[key]) { relationship.updateLink(data.links[key]); } if (kind === 'belongsTo') { if (value === undefined) { return; } relationship.setCanonicalRecord(value); } else if (kind === 'hasMany' && value) { relationship.updateRecordsFromAdapter(value); } }); } var ember$data$lib$system$store$$default = ember$data$lib$system$store$$Store; function ember$data$lib$initializers$store$$initializeStore(registry, application) { Ember.deprecate('Specifying a custom Store for Ember Data on your global namespace as `App.Store` ' + 'has been deprecated. Please use `App.ApplicationStore` instead.', !(application && application.Store)); registry.optionsForType('serializer', { singleton: false }); registry.optionsForType('adapter', { singleton: false }); registry.register('store:main', registry.lookupFactory('store:application') || (application && application.Store) || ember$data$lib$system$store$$default); // allow older names to be looked up var proxy = new ember$data$lib$system$container$proxy$$default(registry); proxy.registerDeprecations([ { deprecated: 'serializer:_default', valid: 'serializer:-default' }, { deprecated: 'serializer:_rest', valid: 'serializer:-rest' }, { deprecated: 'adapter:_rest', valid: 'adapter:-rest' } ]); // new go forward paths registry.register('serializer:-default', ember$data$lib$serializers$json$serializer$$default); registry.register('serializer:-rest', ember$data$lib$serializers$rest$serializer$$default); registry.register('adapter:-rest', ember$data$lib$adapters$rest$adapter$$default); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook var store = registry.lookup('store:main'); registry.register('service:store', store, { instantiate: false }); } var ember$data$lib$initializers$store$$default = ember$data$lib$initializers$store$$initializeStore; var ember$data$lib$transforms$base$$default = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param {mixed} deserialized The deserialized value @return {mixed} The serialized value */ serialize: null, /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param {mixed} serialized The serialized value @return {mixed} The deserialized value */ deserialize: null }); var ember$data$lib$transforms$number$$empty = Ember.isEmpty; function ember$data$lib$transforms$number$$isNumber(value) { return value === value && value !== Infinity && value !== -Infinity; } var ember$data$lib$transforms$number$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function(serialized) { var transformed; if (ember$data$lib$transforms$number$$empty(serialized)) { return null; } else { transformed = Number(serialized); return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null; } }, serialize: function(deserialized) { var transformed; if (ember$data$lib$transforms$number$$empty(deserialized)) { return null; } else { transformed = Number(deserialized); return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null; } } }); // Date.prototype.toISOString shim // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString var ember$data$lib$transforms$date$$toISOString = Date.prototype.toISOString || function() { function pad(number) { if ( number < 10 ) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; if (Ember.SHIM_ES5) { if (!Date.prototype.toISOString) { Date.prototype.toISOString = ember$data$lib$transforms$date$$toISOString; } } var ember$data$lib$transforms$date$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { return ember$data$lib$transforms$date$$toISOString.call(date); } else { return null; } } }); var ember$data$lib$transforms$string$$none = Ember.isNone; var ember$data$lib$transforms$string$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function(serialized) { return ember$data$lib$transforms$string$$none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return ember$data$lib$transforms$string$$none(deserialized) ? null : String(deserialized); } }); var ember$data$lib$transforms$boolean$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); function ember$data$lib$initializers$transforms$$initializeTransforms(registry) { registry.register('transform:boolean', ember$data$lib$transforms$boolean$$default); registry.register('transform:date', ember$data$lib$transforms$date$$default); registry.register('transform:number', ember$data$lib$transforms$number$$default); registry.register('transform:string', ember$data$lib$transforms$string$$default); } var ember$data$lib$initializers$transforms$$default = ember$data$lib$initializers$transforms$$initializeTransforms; function ember$data$lib$initializers$store$injections$$initializeStoreInjections(registry) { registry.injection('controller', 'store', 'store:main'); registry.injection('route', 'store', 'store:main'); registry.injection('data-adapter', 'store', 'store:main'); } var ember$data$lib$initializers$store$injections$$default = ember$data$lib$initializers$store$injections$$initializeStoreInjections; var ember$data$lib$system$debug$debug$adapter$$get = Ember.get; var ember$data$lib$system$debug$debug$adapter$$capitalize = Ember.String.capitalize; var ember$data$lib$system$debug$debug$adapter$$underscore = Ember.String.underscore; var ember$data$lib$system$debug$debug$adapter$$default = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== ember$data$lib$system$model$$default && ember$data$lib$system$model$$default.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; ember$data$lib$system$debug$debug$adapter$$get(type, 'attributes').forEach(function(meta, name) { if (count++ > self.attributeLimit) { return false; } var desc = ember$data$lib$system$debug$debug$adapter$$capitalize(ember$data$lib$system$debug$debug$adapter$$underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this; var count = 0; var columnValues = { id: ember$data$lib$system$debug$debug$adapter$$get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = ember$data$lib$system$debug$debug$adapter$$get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = []; var keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(ember$data$lib$system$debug$debug$adapter$$get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(); var self = this; var keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); function ember$data$lib$initializers$data$adapter$$initializeDebugAdapter(registry) { registry.register('data-adapter:main', ember$data$lib$system$debug$debug$adapter$$default); } var ember$data$lib$initializers$data$adapter$$default = ember$data$lib$initializers$data$adapter$$initializeDebugAdapter; function ember$data$lib$setup$container$$setupContainer(container, application) { // application is not a required argument. This ensures // testing setups can setup a container without booting an // entire ember application. ember$data$lib$initializers$data$adapter$$default(container, application); ember$data$lib$initializers$transforms$$default(container, application); ember$data$lib$initializers$store$injections$$default(container, application); ember$data$lib$initializers$store$$default(container, application); activemodel$adapter$lib$setup$container$$default(container, application); } var ember$data$lib$setup$container$$default = ember$data$lib$setup$container$$setupContainer; var ember$data$lib$ember$initializer$$K = Ember.K; /** @module ember-data */ /* This code initializes Ember-Data onto an Ember application. If an Ember.js developer defines a subclass of DS.Store on their application, as `App.ApplicationStore` (or via a module system that resolves to `store:application`) this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.ApplicationStore = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.ApplicationStore` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "ember-data", initialize: ember$data$lib$setup$container$$default }); // Deprecated initializers to satisfy old code that depended on them Application.initializer({ name: "store", after: "ember-data", initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: "activeModelAdapter", before: "store", initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: "transforms", before: "store", initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: "data-adapter", before: "store", initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: "injectStore", before: "store", initialize: ember$data$lib$ember$initializer$$K }); }); Ember.Date = Ember.Date || {}; var origParse = Date.parse; var numericKeys = [1, 4, 5, 6, 7, 10, 11]; /** @method parse @param {Date} date @return {Number} timestamp */ Ember.Date.parse = function (date) { var timestamp, struct; var minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } ember$data$lib$system$model$$default.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id']; var relationships = { belongsTo: [], hasMany: [] }; var expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); var ember$data$lib$system$debug$debug$info$$default = ember$data$lib$system$model$$default; var ember$data$lib$system$debug$$default = ember$data$lib$system$debug$debug$adapter$$default; var ember$data$lib$serializers$embedded$records$mixin$$get = Ember.get; var ember$data$lib$serializers$embedded$records$mixin$$forEach = Ember.EnumerableUtils.forEach; var ember$data$lib$serializers$embedded$records$mixin$$camelize = Ember.String.camelize; /** ## Using Embedded Records `DS.EmbeddedRecordsMixin` supports serializing embedded records. To set up embedded records, include the mixin when extending a serializer then define and configure embedded (model) relationships. Below is an example of a per-type serializer ('post' type). ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' }, comments: { serialize: 'ids' } } }); ``` Note that this use of `{ embedded: 'always' }` is unrelated to the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of defining a model while working with the ActiveModelSerializer. Nevertheless, using `{ embedded: 'always' }` as an option to DS.attr is not a valid way to setup embedded records. The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for: ```js { serialize: 'records', deserialize: 'records' } ``` ### Configuring Attrs A resource's `attrs` option may be set to use `ids`, `records` or false for the `serialize` and `deserialize` settings. The `attrs` property can be set on the ApplicationSerializer or a per-type serializer. In the case where embedded JSON is expected while extracting a payload (reading) the setting is `deserialize: 'records'`, there is no need to use `ids` when extracting as that is the default behavior without this mixin if you are using the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while serializing `serialize: 'records'` is the setting to use. There is an option of not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you do not want the relationship sent at all, you can use `serialize: false`. ### EmbeddedRecordsMixin defaults If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` will behave in the following way: BelongsTo: `{ serialize: 'id', deserialize: 'id' }` HasMany: `{ serialize: false, deserialize: 'ids' }` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. Note that when defining any relationships on your model such as `belongsTo` and `hasMany`, you should not both specify `async:true` and also indicate through the serializer's `attrs` attribute that the related model should be embedded. If a model is declared embedded, then do not use `async:true`. To successfully extract and serialize embedded records the model relationships must be setup correcty See the [defining relationships](/guides/models/defining-models/#toc_defining-relationships) section of the **Defining Models** guide page. Records without an `id` property are not considered embedded records, model instances must have an `id` property to be used with Ember Data. ### Example JSON payloads, Models and Serializers **When customizing a serializer it is important to grok what the customizations are. Please read the docs for the methods this mixin provides, in case you need to modify it to fit your specific needs.** For example review the docs for each method of this mixin: * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ var ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin = Ember.Mixin.create({ /** Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered A payload with an attr configured for embedded records needs to be extracted: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash to be normalized @param {String} key the hash has been referenced by @return {Object} the normalized hash **/ normalize: function(type, hash, prop) { var normalizedHash = this._super(type, hash, prop); return ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedRecords(this, this.store, type, normalizedHash); }, keyForRelationship: function(key, type) { if (this.hasDeserializeRecordsOption(key)) { return this.keyForAttribute(key); } else { return this._super(key, type) || key; } }, /** Serialize `belongsTo` relationship when it is configured as an embedded object. This example of an author model belongs to a post model: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), author: DS.belongsTo('author') }); Author = DS.Model.extend({ name: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded author ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var embeddedSnapshot = snapshot.belongsTo(attr); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); if (!embeddedSnapshot) { json[key] = null; } else { json[key] = embeddedSnapshot.id; } } else if (includeRecords) { key = this.keyForAttribute(attr); if (!embeddedSnapshot) { json[key] = null; } else { json[key] = embeddedSnapshot.record.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[key]); } } }, /** Serialize `hasMany` relationship when it is configured as embedded objects. This example of a post model has many comments: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded comments ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed `ids` or `records` can be set. When extracting the only option is `records`. So `{embedded: 'always'}` is shorthand for: `{serialize: 'records', deserialize: 'records'}` To embed the `ids` for a related object (using a hasMany relationship): ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {serialize: 'ids', deserialize: 'records'} } }) ``` ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } } ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function(snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); json[key] = snapshot.hasMany(attr, { ids: true }); } else if (includeRecords) { key = this.keyForAttribute(attr); json[key] = snapshot.hasMany(attr).map(function(embeddedSnapshot) { var embeddedJson = embeddedSnapshot.record.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson); return embeddedJson; }, this); } }, /** When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship). Serializing a `belongsTo` relationship removes the property that refers to the parent record Serializing a `hasMany` relationship does not remove the property that refers to the parent record. @method removeEmbeddedForeignKey @param {DS.Snapshot} snapshot @param {DS.Snapshot} embeddedSnapshot @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) { if (relationship.kind === 'hasMany') { return; } else if (relationship.kind === 'belongsTo') { var parentRecord = snapshot.type.inverseFor(relationship.key); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.type); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind); if (parentKey) { delete json[parentKey]; } } } }, // checks config for attrs option to embedded (always) - serialize and deserialize hasEmbeddedAlwaysOption: function (attr) { var option = this.attrsOption(attr); return option && option.embedded === 'always'; }, // checks config for attrs option to serialize ids hasSerializeRecordsOption: function(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || (option && (option.serialize === 'records')); }, // checks config for attrs option to serialize records hasSerializeIdsOption: function(attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); }, // checks config for attrs option to serialize records noSerializeOptionSpecified: function(attr) { var option = this.attrsOption(attr); return !(option && (option.serialize || option.embedded)); }, // checks config for attrs option to deserialize records // a defined option object for a resource is treated the same as // `deserialize: 'records'` hasDeserializeRecordsOption: function(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || (option && option.deserialize === 'records'); }, attrsOption: function(attr) { var attrs = this.get('attrs'); return attrs && (attrs[ember$data$lib$serializers$embedded$records$mixin$$camelize(attr)] || attrs[attr]); } }); // chooses a relationship kind to branch which function is used to update payload // does not change payload if attr is not embedded function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedRecords(serializer, store, type, partial) { type.eachRelationship(function(key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { var embeddedType = store.modelFor(relationship.type.typeKey); if (relationship.kind === "hasMany") { if (relationship.options.polymorphic) { ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasManyPolymorphic(store, key, partial); } else { ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasMany(store, key, embeddedType, partial); } } if (relationship.kind === "belongsTo") { if (relationship.options.polymorphic) { ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsToPolymorphic(store, key, partial); } else { ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsTo(store, key, embeddedType, partial); } } } }); return partial; } // handles embedding for `hasMany` relationship function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasMany(store, key, embeddedType, hash) { if (!hash[key]) { return hash; } var ids = []; var embeddedSerializer = store.serializerFor(embeddedType.typeKey); ember$data$lib$serializers$embedded$records$mixin$$forEach(hash[key], function(data) { var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null); store.push(embeddedType, embeddedRecord); ids.push(embeddedRecord.id); }); hash[key] = ids; return hash; } function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasManyPolymorphic(store, key, hash) { if (!hash[key]) { return hash; } var ids = []; ember$data$lib$serializers$embedded$records$mixin$$forEach(hash[key], function(data) { var typeKey = data.type; var embeddedSerializer = store.serializerFor(typeKey); var embeddedType = store.modelFor(typeKey); var primaryKey = ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'primaryKey'); var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null); store.push(embeddedType, embeddedRecord); ids.push({ id: embeddedRecord[primaryKey], type: typeKey }); }); hash[key] = ids; return hash; } function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsTo(store, key, embeddedType, hash) { if (!hash[key]) { return hash; } var embeddedSerializer = store.serializerFor(embeddedType.typeKey); var embeddedRecord = embeddedSerializer.normalize(embeddedType, hash[key], null); store.push(embeddedType, embeddedRecord); hash[key] = embeddedRecord.id; //TODO Need to add a reference to the parent later so relationship works between both `belongsTo` records return hash; } function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsToPolymorphic(store, key, hash) { if (!hash[key]) { return hash; } var data = hash[key]; var typeKey = data.type; var embeddedSerializer = store.serializerFor(typeKey); var embeddedType = store.modelFor(typeKey); var primaryKey = ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'primaryKey'); var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null); store.push(embeddedType, embeddedRecord); hash[key] = embeddedRecord[primaryKey]; hash[key + 'Type'] = typeKey; return hash; } var ember$data$lib$serializers$embedded$records$mixin$$default = ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin; /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```javascript App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the key name. ```javascript App.Comment = DS.Model.extend({ post: DS.belongsTo() }); ``` will lookup for a Post type. @namespace @method belongsTo @for DS @param {String} type (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function ember$data$lib$system$relationships$belongs$to$$belongsTo(type, options) { if (typeof type === 'object') { options = type; type = undefined; } Ember.assert("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + Ember.inspect(type) + ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", typeof type === 'string' || typeof type === 'undefined'); options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo', key: null }; return Ember.computed(function(key, value) { if (arguments.length>1) { if ( value === undefined ) { value = null; } if (value && value.then) { this._relationships[key].setRecordPromise(value); } else { this._relationships[key].setRecord(value); } } return this._relationships[key].getRecord(); }).meta(meta); } /* These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. */ ember$data$lib$system$model$$default.reopen({ notifyBelongsToChanged: function(key) { this.notifyPropertyChange(key); } }); var ember$data$lib$system$relationships$belongs$to$$default = ember$data$lib$system$relationships$belongs$to$$belongsTo; /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); App.Tag = DS.Model.extend({ posts: DS.hasMany('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the singularized key name. ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany() }); ``` will lookup for a Tag type. #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```javascript var belongsTo = DS.belongsTo, hasMany = DS.hasMany; App.Comment = DS.Model.extend({ onePost: belongsTo('post'), twoPost: belongsTo('post'), redPost: belongsTo('post'), bluePost: belongsTo('post') }); App.Post = DS.Model.extend({ comments: hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String} type (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function ember$data$lib$system$relationships$has$many$$hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } Ember.assert("The first argument to DS.hasMany must be a string representing a model type key, not an instance of " + Ember.inspect(type) + ". E.g., to define a relation to the Comment model, use DS.hasMany('comment')", typeof type === 'string' || typeof type === 'undefined'); options = options || {}; // Metadata about relationships is stored on the meta of // the relationship. This is used for introspection and // serialization. Note that `key` is populated lazily // the first time the CP is called. var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany', key: null }; return Ember.computed(function(key) { var relationship = this._relationships[key]; return relationship.getRecords(); }).meta(meta).readOnly(); } ember$data$lib$system$model$$default.reopen({ notifyHasManyAdded: function(key) { //We need to notifyPropertyChange in the adding case because we need to make sure //we fetch the newly added record in case it is unloaded //TODO(Igor): Consider whether we could do this only if the record state is unloaded //Goes away once hasMany is double promisified this.notifyPropertyChange(key); } }); var ember$data$lib$system$relationships$has$many$$default = ember$data$lib$system$relationships$has$many$$hasMany; function ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(store, meta) { var typeKey, type; typeKey = meta.type || meta.key; if (typeof typeKey === 'string') { if (meta.kind === 'hasMany') { typeKey = ember$inflector$lib$lib$system$string$$singularize(typeKey); } type = store.modelFor(typeKey); } else { type = meta.type; } return type; } function ember$data$lib$system$relationship$meta$$relationshipFromMeta(store, meta) { return { key: meta.key, kind: meta.kind, type: ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(store, meta), options: meta.options, parentType: meta.parentType, isRelationship: true }; } var ember$data$lib$system$relationships$ext$$get = Ember.get; var ember$data$lib$system$relationships$ext$$filter = Ember.ArrayPolyfills.filter; var ember$data$lib$system$relationships$ext$$relationshipsDescriptor = Ember.computed(function() { if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable === true) { ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable = false; } var map = new ember$data$lib$system$map$$MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { meta.key = name; var relationshipsForType = map.get(ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(this.store, meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).readOnly(); var ember$data$lib$system$relationships$ext$$relatedTypesDescriptor = Ember.computed(function() { if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable === true) { ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable = false; } var type; var types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(this.store, meta); Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); if (!types.contains(type)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); types.push(type); } } }); return types; }).readOnly(); var ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor = Ember.computed(function() { if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable === true) { ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable = false; } var map = ember$data$lib$system$map$$Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = ember$data$lib$system$relationship$meta$$relationshipFromMeta(this.store, meta); relationship.type = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(this.store, meta); map.set(name, relationship); } }); return map; }).readOnly(); /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ ember$data$lib$system$model$$default.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param {Object} proto @param {String} key @param {Ember.ComputedProperty} value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.ComputedProperty) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ ember$data$lib$system$model$$default.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = ember$data$lib$system$relationships$ext$$get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseMap: Ember.computed(function() { return Ember.create(null); }), /** Find the relationship which is the inverse of the one asked for. For example, if you define models like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('message') }); App.Message = DS.Model.extend({ owner: DS.belongsTo('post') }); ``` App.Post.inverseFor('comments') -> {type: App.Message, name:'owner', kind:'belongsTo'} App.Message.inverseFor('owner') -> {type: App.Post, name:'comments', kind:'hasMany'} @method inverseFor @static @param {String} name the name of the relationship @return {Object} the inverse relationship, or null */ inverseFor: function(name) { var inverseMap = ember$data$lib$system$relationships$ext$$get(this, 'inverseMap'); if (inverseMap[name]) { return inverseMap[name]; } else { var inverse = this._findInverseFor(name); inverseMap[name] = inverse; return inverse; } }, //Calculate the inverse, ignoring the cache _findInverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var propertyMeta = this.metaForProperty(name); //If inverse is manually specified to be null, like `comments: DS.hasMany('message', {inverse: null})` var options = propertyMeta.options; if (options.inverse === null) { return null; } var inverseName, inverseKind, inverse; Ember.warn("Detected a reflexive relationship by the name of '" + name + "' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.", options.inverse || propertyMeta.type !== propertyMeta.parentType.typeKey); //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName); Ember.assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.typeKey + "' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse)); inverseKind = inverse.kind; } else { //No inverse was specified manually, we need to use a heuristic to guess one var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } var filteredRelationships = ember$data$lib$system$relationships$ext$$filter.call(possibleRelationships, function(possibleRelationship) { var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; return name === optionsForRelationship.inverse; }); Ember.assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2); if (filteredRelationships.length === 1 ) { possibleRelationships = filteredRelationships; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, relationshipsSoFar) { var possibleRelationships = relationshipsSoFar || []; var relationshipMap = ember$data$lib$system$relationships$ext$$get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); relationships = ember$data$lib$system$relationships$ext$$filter.call(relationships, function(relationship) { var optionsForRelationship = inverseType.metaForProperty(relationship.name).options; if (!optionsForRelationship.inverse) { return true; } return name === optionsForRelationship.inverse; }); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationships); } //Recurse to support polymorphism if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: ember$data$lib$system$relationships$ext$$relationshipsDescriptor, /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: ember$data$lib$system$relationships$ext$$relatedTypesDescriptor, /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor, /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(kind, field) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = ember$data$lib$system$map$$Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }).readOnly(), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { ember$data$lib$system$relationships$ext$$get(this, 'relationshipsByName').forEach(function(relationship, name) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { ember$data$lib$system$relationships$ext$$get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); }, determineRelationshipType: function(knownSide) { var knownKey = knownSide.key; var knownKind = knownSide.kind; var inverse = this.inverseFor(knownKey); var key, otherKind; if (!inverse) { return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; } key = inverse.name; otherKind = inverse.kind; if (otherKind === 'belongsTo') { return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; } else { return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; } } }); ember$data$lib$system$model$$default.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, descriptor); ``` - `name` the name of the current property in the iteration - `descriptor` the meta object that describes this relationship The relationship descriptor argument is an object with the following properties. - **key** <span class="type">String</span> the name of this relationship on the Model - **kind** <span class="type">String</span> "hasMany" or "belongsTo" - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared - **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship - **type** <span class="type">DS.Model</span> the type of the related Model Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachRelationship(function(name, descriptor) { if (descriptor.kind === 'hasMany') { var serializedHasManyName = name.toUpperCase() + '_IDS'; json[name.toUpperCase()] = record.get(name).mapBy('id'); } }); return json; } }); ``` @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); }, relationshipFor: function(name) { return ember$data$lib$system$relationships$ext$$get(this.constructor, 'relationshipsByName').get(name); }, inverseFor: function(key) { return this.constructor.inverseFor(key); } }); Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve; Ember.runInDebug(function() { if (Ember.VERSION.match(/1\.[0-7]\./)) { throw new Ember.Error("Ember Data requires at least Ember 1.8.0, but you have " + Ember.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data"); } }); ember$data$lib$core$$default.Store = ember$data$lib$system$store$$Store; ember$data$lib$core$$default.PromiseArray = ember$data$lib$system$promise$proxies$$PromiseArray; ember$data$lib$core$$default.PromiseObject = ember$data$lib$system$promise$proxies$$PromiseObject; ember$data$lib$core$$default.PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseManyArray; ember$data$lib$core$$default.Model = ember$data$lib$system$model$$default; ember$data$lib$core$$default.RootState = ember$data$lib$system$model$states$$default; ember$data$lib$core$$default.attr = ember$data$lib$system$model$attributes$$default; ember$data$lib$core$$default.Errors = ember$data$lib$system$model$errors$$default; ember$data$lib$core$$default.Snapshot = ember$data$lib$system$snapshot$$default; ember$data$lib$core$$default.Adapter = ember$data$lib$system$adapter$$Adapter; ember$data$lib$core$$default.InvalidError = ember$data$lib$system$adapter$$InvalidError; ember$data$lib$core$$default.Serializer = ember$data$lib$system$serializer$$default; ember$data$lib$core$$default.DebugAdapter = ember$data$lib$system$debug$$default; ember$data$lib$core$$default.RecordArray = ember$data$lib$system$record$arrays$record$array$$default; ember$data$lib$core$$default.FilteredRecordArray = ember$data$lib$system$record$arrays$filtered$record$array$$default; ember$data$lib$core$$default.AdapterPopulatedRecordArray = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default; ember$data$lib$core$$default.ManyArray = ember$data$lib$system$many$array$$default; ember$data$lib$core$$default.RecordArrayManager = ember$data$lib$system$record$array$manager$$default; ember$data$lib$core$$default.RESTAdapter = ember$data$lib$adapters$rest$adapter$$default; ember$data$lib$core$$default.BuildURLMixin = ember$data$lib$adapters$build$url$mixin$$default; ember$data$lib$core$$default.FixtureAdapter = ember$data$lib$adapters$fixture$adapter$$default; ember$data$lib$core$$default.RESTSerializer = ember$data$lib$serializers$rest$serializer$$default; ember$data$lib$core$$default.JSONSerializer = ember$data$lib$serializers$json$serializer$$default; ember$data$lib$core$$default.Transform = ember$data$lib$transforms$base$$default; ember$data$lib$core$$default.DateTransform = ember$data$lib$transforms$date$$default; ember$data$lib$core$$default.StringTransform = ember$data$lib$transforms$string$$default; ember$data$lib$core$$default.NumberTransform = ember$data$lib$transforms$number$$default; ember$data$lib$core$$default.BooleanTransform = ember$data$lib$transforms$boolean$$default; ember$data$lib$core$$default.ActiveModelAdapter = activemodel$adapter$lib$system$active$model$adapter$$default; ember$data$lib$core$$default.ActiveModelSerializer = activemodel$adapter$lib$system$active$model$serializer$$default; ember$data$lib$core$$default.EmbeddedRecordsMixin = ember$data$lib$serializers$embedded$records$mixin$$default; ember$data$lib$core$$default.belongsTo = ember$data$lib$system$relationships$belongs$to$$default; ember$data$lib$core$$default.hasMany = ember$data$lib$system$relationships$has$many$$default; ember$data$lib$core$$default.Relationship = ember$data$lib$system$relationships$state$relationship$$default; ember$data$lib$core$$default.ContainerProxy = ember$data$lib$system$container$proxy$$default; ember$data$lib$core$$default._setupContainer = ember$data$lib$setup$container$$default; Ember.lookup.DS = ember$data$lib$core$$default; var ember$data$lib$main$$default = ember$data$lib$core$$default; }).call(this); //# sourceMappingURL=ember-data.js.map
(function() { "use strict"; var $$utils$$hop = Object.prototype.hasOwnProperty; function $$utils$$extend(obj) { var sources = Array.prototype.slice.call(arguments, 1), i, len, source, key; for (i = 0, len = sources.length; i < len; i += 1) { source = sources[i]; if (!source) { continue; } for (key in source) { if ($$utils$$hop.call(source, key)) { obj[key] = source[key]; } } } return obj; } // Purposely using the same implementation as the Intl.js `Intl` polyfill. // Copyright 2013 Andy Earnshaw, MIT License var $$es51$$realDefineProp = (function () { try { return !!Object.defineProperty({}, 'a', {}); } catch (e) { return false; } })(); var $$es51$$es3 = !$$es51$$realDefineProp && !Object.prototype.__defineGetter__; var $$es51$$defineProperty = $$es51$$realDefineProp ? Object.defineProperty : function (obj, name, desc) { if ('get' in desc && obj.__defineGetter__) { obj.__defineGetter__(name, desc.get); } else if (!$$utils$$hop.call(obj, name) || 'value' in desc) { obj[name] = desc.value; } }; var $$es51$$objCreate = Object.create || function (proto, props) { var obj, k; function F() {} F.prototype = proto; obj = new F(); for (k in props) { if ($$utils$$hop.call(props, k)) { $$es51$$defineProperty(obj, k, props[k]); } } return obj; }; var $$compiler$$default = $$compiler$$Compiler; function $$compiler$$Compiler(locales, formats, pluralFn) { this.locales = locales; this.formats = formats; this.pluralFn = pluralFn; } $$compiler$$Compiler.prototype.compile = function (ast) { this.pluralStack = []; this.currentPlural = null; this.pluralNumberFormat = null; return this.compileMessage(ast); }; $$compiler$$Compiler.prototype.compileMessage = function (ast) { if (!(ast && ast.type === 'messageFormatPattern')) { throw new Error('Message AST is not of type: "messageFormatPattern"'); } var elements = ast.elements, pattern = []; var i, len, element; for (i = 0, len = elements.length; i < len; i += 1) { element = elements[i]; switch (element.type) { case 'messageTextElement': pattern.push(this.compileMessageText(element)); break; case 'argumentElement': pattern.push(this.compileArgument(element)); break; default: throw new Error('Message element does not have a valid type'); } } return pattern; }; $$compiler$$Compiler.prototype.compileMessageText = function (element) { // When this `element` is part of plural sub-pattern and its value contains // an unescaped '#', use a `PluralOffsetString` helper to properly output // the number with the correct offset in the string. if (this.currentPlural && /(^|[^\\])#/g.test(element.value)) { // Create a cache a NumberFormat instance that can be reused for any // PluralOffsetString instance in this message. if (!this.pluralNumberFormat) { this.pluralNumberFormat = new Intl.NumberFormat(this.locales); } return new $$compiler$$PluralOffsetString( this.currentPlural.id, this.currentPlural.format.offset, this.pluralNumberFormat, element.value); } // Unescape the escaped '#'s in the message text. return element.value.replace(/\\#/g, '#'); }; $$compiler$$Compiler.prototype.compileArgument = function (element) { var format = element.format; if (!format) { return new $$compiler$$StringFormat(element.id); } var formats = this.formats, locales = this.locales, pluralFn = this.pluralFn, options; switch (format.type) { case 'numberFormat': options = formats.number[format.style]; return { id : element.id, format: new Intl.NumberFormat(locales, options).format }; case 'dateFormat': options = formats.date[format.style]; return { id : element.id, format: new Intl.DateTimeFormat(locales, options).format }; case 'timeFormat': options = formats.time[format.style]; return { id : element.id, format: new Intl.DateTimeFormat(locales, options).format }; case 'pluralFormat': options = this.compileOptions(element); return new $$compiler$$PluralFormat(element.id, format.offset, options, pluralFn); case 'selectFormat': options = this.compileOptions(element); return new $$compiler$$SelectFormat(element.id, options); default: throw new Error('Message element does not have a valid format type'); } }; $$compiler$$Compiler.prototype.compileOptions = function (element) { var format = element.format, options = format.options, optionsHash = {}; // Save the current plural element, if any, then set it to a new value when // compiling the options sub-patterns. This conform's the spec's algorithm // for handling `"#"` synax in message text. this.pluralStack.push(this.currentPlural); this.currentPlural = format.type === 'pluralFormat' ? element : null; var i, len, option; for (i = 0, len = options.length; i < len; i += 1) { option = options[i]; // Compile the sub-pattern and save it under the options's selector. optionsHash[option.selector] = this.compileMessage(option.value); } // Pop the plural stack to put back the original currnet plural value. this.currentPlural = this.pluralStack.pop(); return optionsHash; }; // -- Compiler Helper Classes -------------------------------------------------- function $$compiler$$StringFormat(id) { this.id = id; } $$compiler$$StringFormat.prototype.format = function (value) { if (!value) { return ''; } return typeof value === 'string' ? value : String(value); }; function $$compiler$$PluralFormat(id, offset, options, pluralFn) { this.id = id; this.offset = offset; this.options = options; this.pluralFn = pluralFn; } $$compiler$$PluralFormat.prototype.getOption = function (value) { var options = this.options; var option = options['=' + value] || options[this.pluralFn(value - this.offset)]; return option || options.other; }; function $$compiler$$PluralOffsetString(id, offset, numberFormat, string) { this.id = id; this.offset = offset; this.numberFormat = numberFormat; this.string = string; } $$compiler$$PluralOffsetString.prototype.format = function (value) { var number = this.numberFormat.format(value - this.offset); return this.string .replace(/(^|[^\\])#/g, '$1' + number) .replace(/\\#/g, '#'); }; function $$compiler$$SelectFormat(id, options) { this.id = id; this.options = options; } $$compiler$$SelectFormat.prototype.getOption = function (value) { var options = this.options; return options[value] || options.other; }; var intl$messageformat$parser$$default = (function() { /* * Generated by PEG.js 0.8.0. * * http://pegjs.majda.cz/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function SyntaxError(message, expected, found, offset, line, column) { this.message = message; this.expected = expected; this.found = found; this.offset = offset; this.line = line; this.column = column; this.name = "SyntaxError"; } peg$subclass(SyntaxError, Error); function parse(input) { var options = arguments.length > 1 ? arguments[1] : {}, peg$FAILED = {}, peg$startRuleFunctions = { start: peg$parsestart }, peg$startRuleFunction = peg$parsestart, peg$c0 = [], peg$c1 = function(elements) { return { type : 'messageFormatPattern', elements: elements }; }, peg$c2 = peg$FAILED, peg$c3 = function(text) { var string = '', i, j, outerLen, inner, innerLen; for (i = 0, outerLen = text.length; i < outerLen; i += 1) { inner = text[i]; for (j = 0, innerLen = inner.length; j < innerLen; j += 1) { string += inner[j]; } } return string; }, peg$c4 = function(messageText) { return { type : 'messageTextElement', value: messageText }; }, peg$c5 = /^[^ \t\n\r,.+={}#]/, peg$c6 = { type: "class", value: "[^ \\t\\n\\r,.+={}#]", description: "[^ \\t\\n\\r,.+={}#]" }, peg$c7 = "{", peg$c8 = { type: "literal", value: "{", description: "\"{\"" }, peg$c9 = null, peg$c10 = ",", peg$c11 = { type: "literal", value: ",", description: "\",\"" }, peg$c12 = "}", peg$c13 = { type: "literal", value: "}", description: "\"}\"" }, peg$c14 = function(id, format) { return { type : 'argumentElement', id : id, format: format && format[2] }; }, peg$c15 = "number", peg$c16 = { type: "literal", value: "number", description: "\"number\"" }, peg$c17 = "date", peg$c18 = { type: "literal", value: "date", description: "\"date\"" }, peg$c19 = "time", peg$c20 = { type: "literal", value: "time", description: "\"time\"" }, peg$c21 = function(type, style) { return { type : type + 'Format', style: style && style[2] }; }, peg$c22 = "plural", peg$c23 = { type: "literal", value: "plural", description: "\"plural\"" }, peg$c24 = function(offset, options) { return { type : 'pluralFormat', offset : offset || 0, options: options } }, peg$c25 = "select", peg$c26 = { type: "literal", value: "select", description: "\"select\"" }, peg$c27 = function(options) { return { type : 'selectFormat', options: options } }, peg$c28 = "=", peg$c29 = { type: "literal", value: "=", description: "\"=\"" }, peg$c30 = function(selector, pattern) { return { type : 'optionalFormatPattern', selector: selector, value : pattern }; }, peg$c31 = "offset:", peg$c32 = { type: "literal", value: "offset:", description: "\"offset:\"" }, peg$c33 = function(number) { return number; }, peg$c34 = { type: "other", description: "whitespace" }, peg$c35 = /^[ \t\n\r]/, peg$c36 = { type: "class", value: "[ \\t\\n\\r]", description: "[ \\t\\n\\r]" }, peg$c37 = { type: "other", description: "optionalWhitespace" }, peg$c38 = /^[0-9]/, peg$c39 = { type: "class", value: "[0-9]", description: "[0-9]" }, peg$c40 = /^[0-9a-f]/i, peg$c41 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" }, peg$c42 = "0", peg$c43 = { type: "literal", value: "0", description: "\"0\"" }, peg$c44 = /^[1-9]/, peg$c45 = { type: "class", value: "[1-9]", description: "[1-9]" }, peg$c46 = function(digits) { return parseInt(digits, 10); }, peg$c47 = /^[^{}\\\0-\x1F \t\n\r]/, peg$c48 = { type: "class", value: "[^{}\\\\\\0-\\x1F \\t\\n\\r]", description: "[^{}\\\\\\0-\\x1F \\t\\n\\r]" }, peg$c49 = "\\#", peg$c50 = { type: "literal", value: "\\#", description: "\"\\\\#\"" }, peg$c51 = function() { return '\\#'; }, peg$c52 = "\\{", peg$c53 = { type: "literal", value: "\\{", description: "\"\\\\{\"" }, peg$c54 = function() { return '\u007B'; }, peg$c55 = "\\}", peg$c56 = { type: "literal", value: "\\}", description: "\"\\\\}\"" }, peg$c57 = function() { return '\u007D'; }, peg$c58 = "\\u", peg$c59 = { type: "literal", value: "\\u", description: "\"\\\\u\"" }, peg$c60 = function(digits) { return String.fromCharCode(parseInt(digits, 16)); }, peg$c61 = function(chars) { return chars.join(''); }, peg$currPos = 0, peg$reportedPos = 0, peg$cachedPos = 0, peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$reportedPos, peg$currPos); } function offset() { return peg$reportedPos; } function line() { return peg$computePosDetails(peg$reportedPos).line; } function column() { return peg$computePosDetails(peg$reportedPos).column; } function expected(description) { throw peg$buildException( null, [{ type: "other", description: description }], peg$reportedPos ); } function error(message) { throw peg$buildException(message, null, peg$reportedPos); } function peg$computePosDetails(pos) { function advance(details, startPos, endPos) { var p, ch; for (p = startPos; p < endPos; p++) { ch = input.charAt(p); if (ch === "\n") { if (!details.seenCR) { details.line++; } details.column = 1; details.seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { details.line++; details.column = 1; details.seenCR = true; } else { details.column++; details.seenCR = false; } } } if (peg$cachedPos !== pos) { if (peg$cachedPos > pos) { peg$cachedPos = 0; peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; } advance(peg$cachedPosDetails, peg$cachedPos, pos); peg$cachedPos = pos; } return peg$cachedPosDetails; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildException(message, expected, pos) { function cleanupExpected(expected) { var i = 1; expected.sort(function(a, b) { if (a.description < b.description) { return -1; } else if (a.description > b.description) { return 1; } else { return 0; } }); while (i < expected.length) { if (expected[i - 1] === expected[i]) { expected.splice(i, 1); } else { i++; } } } function buildMessage(expected, found) { function stringEscape(s) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\x08/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); } var expectedDescs = new Array(expected.length), expectedDesc, foundDesc, i; for (i = 0; i < expected.length; i++) { expectedDescs[i] = expected[i].description; } expectedDesc = expected.length > 1 ? expectedDescs.slice(0, -1).join(", ") + " or " + expectedDescs[expected.length - 1] : expectedDescs[0]; foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; return "Expected " + expectedDesc + " but " + foundDesc + " found."; } var posDetails = peg$computePosDetails(pos), found = pos < input.length ? input.charAt(pos) : null; if (expected !== null) { cleanupExpected(expected); } return new SyntaxError( message !== null ? message : buildMessage(expected, found), expected, found, pos, posDetails.line, posDetails.column ); } function peg$parsestart() { var s0; s0 = peg$parsemessageFormatPattern(); return s0; } function peg$parsemessageFormatPattern() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsemessageFormatElement(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsemessageFormatElement(); } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c1(s1); } s0 = s1; return s0; } function peg$parsemessageFormatElement() { var s0; s0 = peg$parsemessageTextElement(); if (s0 === peg$FAILED) { s0 = peg$parseargumentElement(); } return s0; } function peg$parsemessageText() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = []; s2 = peg$currPos; s3 = peg$parse_(); if (s3 !== peg$FAILED) { s4 = peg$parsechars(); if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c2; } } else { peg$currPos = s2; s2 = peg$c2; } } else { peg$currPos = s2; s2 = peg$c2; } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$currPos; s3 = peg$parse_(); if (s3 !== peg$FAILED) { s4 = peg$parsechars(); if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c2; } } else { peg$currPos = s2; s2 = peg$c2; } } else { peg$currPos = s2; s2 = peg$c2; } } } else { s1 = peg$c2; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c3(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsews(); if (s1 !== peg$FAILED) { s1 = input.substring(s0, peg$currPos); } s0 = s1; } return s0; } function peg$parsemessageTextElement() { var s0, s1; s0 = peg$currPos; s1 = peg$parsemessageText(); if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c4(s1); } s0 = s1; return s0; } function peg$parseargument() { var s0, s1, s2; s0 = peg$parsenumber(); if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = []; if (peg$c5.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c6); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c5.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c6); } } } } else { s1 = peg$c2; } if (s1 !== peg$FAILED) { s1 = input.substring(s0, peg$currPos); } s0 = s1; } return s0; } function peg$parseargumentElement() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 123) { s1 = peg$c7; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseargument(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = peg$currPos; if (input.charCodeAt(peg$currPos) === 44) { s6 = peg$c10; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c11); } } if (s6 !== peg$FAILED) { s7 = peg$parse_(); if (s7 !== peg$FAILED) { s8 = peg$parseelementFormat(); if (s8 !== peg$FAILED) { s6 = [s6, s7, s8]; s5 = s6; } else { peg$currPos = s5; s5 = peg$c2; } } else { peg$currPos = s5; s5 = peg$c2; } } else { peg$currPos = s5; s5 = peg$c2; } if (s5 === peg$FAILED) { s5 = peg$c9; } if (s5 !== peg$FAILED) { s6 = peg$parse_(); if (s6 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 125) { s7 = peg$c12; peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c13); } } if (s7 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c14(s3, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } return s0; } function peg$parseelementFormat() { var s0; s0 = peg$parsesimpleFormat(); if (s0 === peg$FAILED) { s0 = peg$parsepluralFormat(); if (s0 === peg$FAILED) { s0 = peg$parseselectFormat(); } } return s0; } function peg$parsesimpleFormat() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; if (input.substr(peg$currPos, 6) === peg$c15) { s1 = peg$c15; peg$currPos += 6; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c16); } } if (s1 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c17) { s1 = peg$c17; peg$currPos += 4; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c18); } } if (s1 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c19) { s1 = peg$c19; peg$currPos += 4; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 44) { s4 = peg$c10; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c11); } } if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s6 = peg$parsechars(); if (s6 !== peg$FAILED) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c2; } } else { peg$currPos = s3; s3 = peg$c2; } } else { peg$currPos = s3; s3 = peg$c2; } if (s3 === peg$FAILED) { s3 = peg$c9; } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c21(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } return s0; } function peg$parsepluralFormat() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; if (input.substr(peg$currPos, 6) === peg$c22) { s1 = peg$c22; peg$currPos += 6; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c10; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c11); } } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = peg$parseoffset(); if (s5 === peg$FAILED) { s5 = peg$c9; } if (s5 !== peg$FAILED) { s6 = peg$parse_(); if (s6 !== peg$FAILED) { s7 = []; s8 = peg$parseoptionalFormatPattern(); if (s8 !== peg$FAILED) { while (s8 !== peg$FAILED) { s7.push(s8); s8 = peg$parseoptionalFormatPattern(); } } else { s7 = peg$c2; } if (s7 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c24(s5, s7); s0 = s1; } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } return s0; } function peg$parseselectFormat() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; if (input.substr(peg$currPos, 6) === peg$c25) { s1 = peg$c25; peg$currPos += 6; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c10; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c11); } } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseoptionalFormatPattern(); if (s6 !== peg$FAILED) { while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseoptionalFormatPattern(); } } else { s5 = peg$c2; } if (s5 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c27(s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } return s0; } function peg$parseselector() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c28; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c29); } } if (s2 !== peg$FAILED) { s3 = peg$parsenumber(); if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$c2; } } else { peg$currPos = s1; s1 = peg$c2; } if (s1 !== peg$FAILED) { s1 = input.substring(s0, peg$currPos); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$parsechars(); } return s0; } function peg$parseoptionalFormatPattern() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== peg$FAILED) { s2 = peg$parseselector(); if (s2 !== peg$FAILED) { s3 = peg$parse_(); if (s3 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 123) { s4 = peg$c7; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s6 = peg$parsemessageFormatPattern(); if (s6 !== peg$FAILED) { s7 = peg$parse_(); if (s7 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 125) { s8 = peg$c12; peg$currPos++; } else { s8 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c13); } } if (s8 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c30(s2, s6); s0 = s1; } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } return s0; } function peg$parseoffset() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.substr(peg$currPos, 7) === peg$c31) { s1 = peg$c31; peg$currPos += 7; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c32); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parsenumber(); if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c33(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } return s0; } function peg$parsews() { var s0, s1; peg$silentFails++; s0 = []; if (peg$c35.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c36); } } if (s1 !== peg$FAILED) { while (s1 !== peg$FAILED) { s0.push(s1); if (peg$c35.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c36); } } } } else { s0 = peg$c2; } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c34); } } return s0; } function peg$parse_() { var s0, s1, s2; peg$silentFails++; s0 = peg$currPos; s1 = []; s2 = peg$parsews(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsews(); } if (s1 !== peg$FAILED) { s1 = input.substring(s0, peg$currPos); } s0 = s1; peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c37); } } return s0; } function peg$parsedigit() { var s0; if (peg$c38.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c39); } } return s0; } function peg$parsehexDigit() { var s0; if (peg$c40.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c41); } } return s0; } function peg$parsenumber() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 48) { s1 = peg$c42; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c43); } } if (s1 === peg$FAILED) { s1 = peg$currPos; s2 = peg$currPos; if (peg$c44.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c45); } } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parsedigit(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parsedigit(); } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$c2; } } else { peg$currPos = s2; s2 = peg$c2; } if (s2 !== peg$FAILED) { s2 = input.substring(s1, peg$currPos); } s1 = s2; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c46(s1); } s0 = s1; return s0; } function peg$parsechar() { var s0, s1, s2, s3, s4, s5, s6, s7; if (peg$c47.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c48); } } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c49) { s1 = peg$c49; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c50); } } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c51(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c52) { s1 = peg$c52; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c53); } } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c54(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c55) { s1 = peg$c55; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c56); } } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c57(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c58) { s1 = peg$c58; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c59); } } if (s1 !== peg$FAILED) { s2 = peg$currPos; s3 = peg$currPos; s4 = peg$parsehexDigit(); if (s4 !== peg$FAILED) { s5 = peg$parsehexDigit(); if (s5 !== peg$FAILED) { s6 = peg$parsehexDigit(); if (s6 !== peg$FAILED) { s7 = peg$parsehexDigit(); if (s7 !== peg$FAILED) { s4 = [s4, s5, s6, s7]; s3 = s4; } else { peg$currPos = s3; s3 = peg$c2; } } else { peg$currPos = s3; s3 = peg$c2; } } else { peg$currPos = s3; s3 = peg$c2; } } else { peg$currPos = s3; s3 = peg$c2; } if (s3 !== peg$FAILED) { s3 = input.substring(s2, peg$currPos); } s2 = s3; if (s2 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c60(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c2; } } else { peg$currPos = s0; s0 = peg$c2; } } } } } return s0; } function peg$parsechars() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsechar(); if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsechar(); } } else { s1 = peg$c2; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c61(s1); } s0 = s1; return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail({ type: "end", description: "end of input" }); } throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); } } return { SyntaxError: SyntaxError, parse: parse }; })(); var $$core$$default = $$core$$MessageFormat; // -- MessageFormat -------------------------------------------------------- function $$core$$MessageFormat(message, locales, formats) { // Parse string messages into an AST. var ast = typeof message === 'string' ? $$core$$MessageFormat.__parse(message) : message; if (!(ast && ast.type === 'messageFormatPattern')) { throw new TypeError('A message must be provided as a String or AST.'); } // Creates a new object with the specified `formats` merged with the default // formats. formats = this._mergeFormats($$core$$MessageFormat.formats, formats); // Defined first because it's used to build the format pattern. $$es51$$defineProperty(this, '_locale', {value: this._resolveLocale(locales)}); var pluralFn = $$core$$MessageFormat.__localeData__[this._locale].pluralRuleFunction; // Compile the `ast` to a pattern that is highly optimized for repeated // `format()` invocations. **Note:** This passes the `locales` set provided // to the constructor instead of just the resolved locale. var pattern = this._compilePattern(ast, locales, formats, pluralFn); // "Bind" `format()` method to `this` so it can be passed by reference like // the other `Intl` APIs. var messageFormat = this; this.format = function (values) { return messageFormat._format(pattern, values); }; } // Default format options used as the prototype of the `formats` provided to the // constructor. These are used when constructing the internal Intl.NumberFormat // and Intl.DateTimeFormat instances. $$es51$$defineProperty($$core$$MessageFormat, 'formats', { enumerable: true, value: { number: { 'currency': { style: 'currency' }, 'percent': { style: 'percent' } }, date: { 'short': { month: 'numeric', day : 'numeric', year : '2-digit' }, 'medium': { month: 'short', day : 'numeric', year : 'numeric' }, 'long': { month: 'long', day : 'numeric', year : 'numeric' }, 'full': { weekday: 'long', month : 'long', day : 'numeric', year : 'numeric' } }, time: { 'short': { hour : 'numeric', minute: 'numeric' }, 'medium': { hour : 'numeric', minute: 'numeric', second: 'numeric' }, 'long': { hour : 'numeric', minute : 'numeric', second : 'numeric', timeZoneName: 'short' }, 'full': { hour : 'numeric', minute : 'numeric', second : 'numeric', timeZoneName: 'short' } } } }); // Define internal private properties for dealing with locale data. $$es51$$defineProperty($$core$$MessageFormat, '__localeData__', {value: $$es51$$objCreate(null)}); $$es51$$defineProperty($$core$$MessageFormat, '__addLocaleData', {value: function (data) { if (!(data && data.locale)) { throw new Error( 'Locale data provided to IntlMessageFormat is missing a ' + '`locale` property' ); } if (!data.pluralRuleFunction) { throw new Error( 'Locale data provided to IntlMessageFormat is missing a ' + '`pluralRuleFunction` property' ); } // Message format locale data only requires the first part of the tag. var locale = data.locale.toLowerCase().split('-')[0]; $$core$$MessageFormat.__localeData__[locale] = data; }}); // Defines `__parse()` static method as an exposed private. $$es51$$defineProperty($$core$$MessageFormat, '__parse', {value: intl$messageformat$parser$$default.parse}); // Define public `defaultLocale` property which defaults to English, but can be // set by the developer. $$es51$$defineProperty($$core$$MessageFormat, 'defaultLocale', { enumerable: true, writable : true, value : undefined }); $$core$$MessageFormat.prototype.resolvedOptions = function () { // TODO: Provide anything else? return { locale: this._locale }; }; $$core$$MessageFormat.prototype._compilePattern = function (ast, locales, formats, pluralFn) { var compiler = new $$compiler$$default(locales, formats, pluralFn); return compiler.compile(ast); }; $$core$$MessageFormat.prototype._format = function (pattern, values) { var result = '', i, len, part, id, value; for (i = 0, len = pattern.length; i < len; i += 1) { part = pattern[i]; // Exist early for string parts. if (typeof part === 'string') { result += part; continue; } id = part.id; // Enforce that all required values are provided by the caller. if (!(values && $$utils$$hop.call(values, id))) { throw new Error('A value must be provided for: ' + id); } value = values[id]; // Recursively format plural and select parts' option — which can be a // nested pattern structure. The choosing of the option to use is // abstracted-by and delegated-to the part helper object. if (part.options) { result += this._format(part.getOption(value), values); } else { result += part.format(value); } } return result; }; $$core$$MessageFormat.prototype._mergeFormats = function (defaults, formats) { var mergedFormats = {}, type, mergedType; for (type in defaults) { if (!$$utils$$hop.call(defaults, type)) { continue; } mergedFormats[type] = mergedType = $$es51$$objCreate(defaults[type]); if (formats && $$utils$$hop.call(formats, type)) { $$utils$$extend(mergedType, formats[type]); } } return mergedFormats; }; $$core$$MessageFormat.prototype._resolveLocale = function (locales) { if (!locales) { locales = $$core$$MessageFormat.defaultLocale; } if (typeof locales === 'string') { locales = [locales]; } var localeData = $$core$$MessageFormat.__localeData__; var i, len, locale; for (i = 0, len = locales.length; i < len; i += 1) { // We just need the root part of the langage tag. locale = locales[i].split('-')[0].toLowerCase(); // Validate that the langage tag is structurally valid. if (!/[a-z]{2,3}/.test(locale)) { throw new Error( 'Language tag provided to IntlMessageFormat is not ' + 'structrually valid: ' + locale ); } // Return the first locale for which we have CLDR data registered. if ($$utils$$hop.call(localeData, locale)) { return locale; } } throw new Error( 'No locale data has been added to IntlMessageFormat for: ' + locales.join(', ') ); }; var $$en1$$default = {"locale":"en","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";}}; $$core$$default.__addLocaleData($$en1$$default); $$core$$default.defaultLocale = 'en'; var intl$messageformat$$default = $$core$$default; // Purposely using the same implementation as the Intl.js `Intl` polyfill. // Copyright 2013 Andy Earnshaw, MIT License var $$es52$$hop = Object.prototype.hasOwnProperty; var $$es52$$realDefineProp = (function () { try { return !!Object.defineProperty({}, 'a', {}); } catch (e) { return false; } })(); var $$es52$$es3 = !$$es52$$realDefineProp && !Object.prototype.__defineGetter__; var $$es52$$defineProperty = $$es52$$realDefineProp ? Object.defineProperty : function (obj, name, desc) { if ('get' in desc && obj.__defineGetter__) { obj.__defineGetter__(name, desc.get); } else if (!$$es52$$hop.call(obj, name) || 'value' in desc) { obj[name] = desc.value; } }; var $$es52$$objCreate = Object.create || function (proto, props) { var obj, k; function F() {} F.prototype = proto; obj = new F(); for (k in props) { if ($$es52$$hop.call(props, k)) { $$es52$$defineProperty(obj, k, props[k]); } } return obj; }; var $$es52$$arrIndexOf = Array.prototype.indexOf || function (search, fromIndex) { /*jshint validthis:true */ var arr = this; if (!arr.length) { return -1; } for (var i = fromIndex || 0, max = arr.length; i < max; i++) { if (arr[i] === search) { return i; } } return -1; }; var $$diff$$round = Math.round; function $$diff$$daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } var $$diff$$default = function (dfrom, dto) { // Convert to ms timestamps. dfrom = +dfrom; dto = +dto; var millisecond = $$diff$$round(dto - dfrom), second = $$diff$$round(millisecond / 1000), minute = $$diff$$round(second / 60), hour = $$diff$$round(minute / 60), day = $$diff$$round(hour / 24), week = $$diff$$round(day / 7); var rawYears = $$diff$$daysToYears(day), month = $$diff$$round(rawYears * 12), year = $$diff$$round(rawYears); return { millisecond: millisecond, second : second, minute : minute, hour : hour, day : day, week : week, month : month, year : year }; }; var $$core1$$default = $$core1$$RelativeFormat; // ----------------------------------------------------------------------------- var $$core1$$FIELDS = ['second', 'minute', 'hour', 'day', 'month', 'year']; var $$core1$$STYLES = ['best fit', 'numeric']; var $$core1$$getTime = Date.now ? Date.now : function () { return new Date().getTime(); }; // -- RelativeFormat ----------------------------------------------------------- function $$core1$$RelativeFormat(locales, options) { options = options || {}; $$es52$$defineProperty(this, '_locale', {value: this._resolveLocale(locales)}); $$es52$$defineProperty(this, '_options', {value: { style: this._resolveStyle(options.style), units: this._isValidUnits(options.units) && options.units }}); $$es52$$defineProperty(this, '_messages', {value: $$es52$$objCreate(null)}); // "Bind" `format()` method to `this` so it can be passed by reference like // the other `Intl` APIs. var relativeFormat = this; this.format = function format(date) { return relativeFormat._format(date); }; } // Define internal private properties for dealing with locale data. $$es52$$defineProperty($$core1$$RelativeFormat, '__localeData__', {value: $$es52$$objCreate(null)}); $$es52$$defineProperty($$core1$$RelativeFormat, '__addLocaleData', {value: function (data) { if (!(data && data.locale)) { throw new Error( 'Locale data provided to IntlRelativeFormat is missing a ' + '`locale` property value' ); } if (!data.fields) { throw new Error( 'Locale data provided to IntlRelativeFormat is missing a ' + '`fields` property value' ); } // Add data to IntlMessageFormat. intl$messageformat$$default.__addLocaleData(data); // Relative format locale data only requires the first part of the tag. var locale = data.locale.toLowerCase().split('-')[0]; $$core1$$RelativeFormat.__localeData__[locale] = data; }}); // Define public `defaultLocale` property which can be set by the developer, or // it will be set when the first RelativeFormat instance is created by leveraging // the resolved locale from `Intl`. $$es52$$defineProperty($$core1$$RelativeFormat, 'defaultLocale', { enumerable: true, writable : true, value : undefined }); // Define public `thresholds` property which can be set by the developer, and // defaults to relative time thresholds from moment.js. $$es52$$defineProperty($$core1$$RelativeFormat, 'thresholds', { enumerable: true, value: { second: 45, // seconds to minute minute: 45, // minutes to hour hour : 22, // hours to day day : 26, // days to month month : 11 // months to year } }); $$core1$$RelativeFormat.prototype.resolvedOptions = function () { return { locale: this._locale, style : this._options.style, units : this._options.units }; }; $$core1$$RelativeFormat.prototype._format = function (date) { var now = $$core1$$getTime(); if (date === undefined) { date = now; } // Determine if the `date` is valid, and throw a similar error to what // `Intl.DateTimeFormat#format()` would throw. if (!isFinite(date)) { throw new RangeError( 'The date value provided to IntlRelativeFormat#format() is not ' + 'in valid range.' ); } var diffReport = $$diff$$default(now, date); var units = this._options.units || this._selectUnits(diffReport); var diffInUnits = diffReport[units]; if (this._options.style !== 'numeric') { var relativeUnits = this._resolveRelativeUnits(diffInUnits, units); if (relativeUnits) { return relativeUnits; } } return this._resolveMessage(units).format({ '0' : Math.abs(diffInUnits), when: diffInUnits < 0 ? 'past' : 'future' }); }; $$core1$$RelativeFormat.prototype._isValidUnits = function (units) { if (!units || $$es52$$arrIndexOf.call($$core1$$FIELDS, units) >= 0) { return true; } if (typeof units === 'string') { var suggestion = /s$/.test(units) && units.substr(0, units.length - 1); if (suggestion && $$es52$$arrIndexOf.call($$core1$$FIELDS, suggestion) >= 0) { throw new Error( '"' + units + '" is not a valid IntlRelativeFormat `units` ' + 'value, did you mean: ' + suggestion ); } } throw new Error( '"' + units + '" is not a valid IntlRelativeFormat `units` value, it ' + 'must be one of: "' + $$core1$$FIELDS.join('", "') + '"' ); }; $$core1$$RelativeFormat.prototype._resolveLocale = function (locales) { if (!locales) { locales = $$core1$$RelativeFormat.defaultLocale; } if (typeof locales === 'string') { locales = [locales]; } var hop = Object.prototype.hasOwnProperty; var localeData = $$core1$$RelativeFormat.__localeData__; var i, len, locale; for (i = 0, len = locales.length; i < len; i += 1) { // We just need the root part of the langage tag. locale = locales[i].split('-')[0].toLowerCase(); // Validate that the langage tag is structurally valid. if (!/[a-z]{2,3}/.test(locale)) { throw new Error( 'Language tag provided to IntlRelativeFormat is not ' + 'structrually valid: ' + locale ); } // Return the first locale for which we have CLDR data registered. if (hop.call(localeData, locale)) { return locale; } } throw new Error( 'No locale data has been added to IntlRelativeFormat for: ' + locales.join(', ') ); }; $$core1$$RelativeFormat.prototype._resolveMessage = function (units) { var messages = this._messages; var field, relativeTime, i, future, past, message; // Create a new synthetic message based on the locale data from CLDR. if (!messages[units]) { field = $$core1$$RelativeFormat.__localeData__[this._locale].fields[units]; relativeTime = field.relativeTime; future = ''; past = ''; for (i in relativeTime.future) { if (relativeTime.future.hasOwnProperty(i)) { future += ' ' + i + ' {' + relativeTime.future[i].replace('{0}', '#') + '}'; } } for (i in relativeTime.past) { if (relativeTime.past.hasOwnProperty(i)) { past += ' ' + i + ' {' + relativeTime.past[i].replace('{0}', '#') + '}'; } } message = '{when, select, future {{0, plural, ' + future + '}}' + 'past {{0, plural, ' + past + '}}}'; messages[units] = new intl$messageformat$$default(message, this._locale); } return messages[units]; }; $$core1$$RelativeFormat.prototype._resolveRelativeUnits = function (diff, units) { var field = $$core1$$RelativeFormat.__localeData__[this._locale].fields[units]; if (field.relative) { return field.relative[diff]; } }; $$core1$$RelativeFormat.prototype._resolveStyle = function (style) { // Default to "best fit" style. if (!style) { return $$core1$$STYLES[0]; } if ($$es52$$arrIndexOf.call($$core1$$STYLES, style) >= 0) { return style; } throw new Error( '"' + style + '" is not a valid IntlRelativeFormat `style` value, it ' + 'must be one of: "' + $$core1$$STYLES.join('", "') + '"' ); }; $$core1$$RelativeFormat.prototype._selectUnits = function (diffReport) { var i, l, units; for (i = 0, l = $$core1$$FIELDS.length; i < l; i += 1) { units = $$core1$$FIELDS[i]; if (Math.abs(diffReport[units]) < $$core1$$RelativeFormat.thresholds[units]) { break; } } return units; }; var $$en2$$default = {"locale":"en","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"one":"in {0} second","other":"in {0} seconds"},"past":{"one":"{0} second ago","other":"{0} seconds ago"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"one":"in {0} minute","other":"in {0} minutes"},"past":{"one":"{0} minute ago","other":"{0} minutes ago"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"one":"in {0} hour","other":"in {0} hours"},"past":{"one":"{0} hour ago","other":"{0} hours ago"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"one":"in {0} day","other":"in {0} days"},"past":{"one":"{0} day ago","other":"{0} days ago"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"in {0} month","other":"in {0} months"},"past":{"one":"{0} month ago","other":"{0} months ago"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"in {0} year","other":"in {0} years"},"past":{"one":"{0} year ago","other":"{0} years ago"}}}}}; $$core1$$default.__addLocaleData($$en2$$default); $$core1$$default.defaultLocale = 'en'; var intl$relativeformat$$default = $$core1$$default; // Purposely using the same implementation as the Intl.js `Intl` polyfill. // Copyright 2013 Andy Earnshaw, MIT License var $$es5$$hop = Object.prototype.hasOwnProperty; var $$es5$$realDefineProp = (function () { try { return !!Object.defineProperty({}, 'a', {}); } catch (e) { return false; } })(); var $$es5$$es3 = !$$es5$$realDefineProp && !Object.prototype.__defineGetter__; var $$es5$$defineProperty = $$es5$$realDefineProp ? Object.defineProperty : function (obj, name, desc) { if ('get' in desc && obj.__defineGetter__) { obj.__defineGetter__(name, desc.get); } else if (!$$es5$$hop.call(obj, name) || 'value' in desc) { obj[name] = desc.value; } }; var $$es5$$objCreate = Object.create || function (proto, props) { var obj, k; function F() {} F.prototype = proto; obj = new F(); for (k in props) { if ($$es5$$hop.call(props, k)) { $$es5$$defineProperty(obj, k, props[k]); } } return obj; }; var intl$format$cache$$default = intl$format$cache$$createFormatCache; // ----------------------------------------------------------------------------- function intl$format$cache$$createFormatCache(FormatConstructor) { var cache = $$es5$$objCreate(null); return function () { var args = Array.prototype.slice.call(arguments); var cacheId = intl$format$cache$$getCacheId(args); var format = cacheId && cache[cacheId]; if (!format) { format = $$es5$$objCreate(FormatConstructor.prototype); FormatConstructor.apply(format, args); if (cacheId) { cache[cacheId] = format; } } return format; }; } // -- Utilities ---------------------------------------------------------------- function intl$format$cache$$getCacheId(inputs) { // When JSON is not available in the runtime, we will not create a cache id. if (typeof JSON === 'undefined') { return; } var cacheId = []; var i, len, input; for (i = 0, len = inputs.length; i < len; i += 1) { input = inputs[i]; if (input && typeof input === 'object') { cacheId.push(intl$format$cache$$orderedProps(input)); } else { cacheId.push(input); } } return JSON.stringify(cacheId); } function intl$format$cache$$orderedProps(obj) { var props = [], keys = []; var key, i, len, prop; for (key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } var orderedKeys = keys.sort(); for (i = 0, len = orderedKeys.length; i < len; i += 1) { key = orderedKeys[i]; prop = {}; prop[key] = obj[key]; props[i] = prop; } return props; } // ----------------------------------------------------------------------------- var $$mixin$$typesSpec = { locales: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.array ]), formats : React.PropTypes.object, messages: React.PropTypes.object }; function $$mixin$$assertIsDate(date, errMsg) { // Determine if the `date` is valid by checking if it is finite, which is // the same way that `Intl.DateTimeFormat#format()` checks. if (!isFinite(date)) { throw new TypeError(errMsg); } } function $$mixin$$assertIsNumber(num, errMsg) { if (typeof num !== 'number') { throw new TypeError(errMsg); } } var $$mixin$$default = { propsTypes : $$mixin$$typesSpec, contextTypes : $$mixin$$typesSpec, childContextTypes: $$mixin$$typesSpec, getNumberFormat : intl$format$cache$$default(Intl.NumberFormat), getDateTimeFormat: intl$format$cache$$default(Intl.DateTimeFormat), getMessageFormat : intl$format$cache$$default(intl$messageformat$$default), getRelativeFormat: intl$format$cache$$default(intl$relativeformat$$default), getChildContext: function () { var context = this.context; var props = this.props; return { locales: props.locales || context.locales, formats: props.formats || context.formats, messages: props.messages || context.messages }; }, formatDate: function (date, options) { date = new Date(date); $$mixin$$assertIsDate(date, 'A date or timestamp must be provided to formatDate()'); return this._format('date', date, options); }, formatTime: function (date, options) { date = new Date(date); $$mixin$$assertIsDate(date, 'A date or timestamp must be provided to formatTime()'); return this._format('time', date, options); }, formatRelative: function (date, options) { date = new Date(date); $$mixin$$assertIsDate(date, 'A date or timestamp must be provided to formatRelative()'); return this._format('relative', date, options); }, formatNumber: function (num, options) { $$mixin$$assertIsNumber(num, 'A number must be provided to formatNumber()'); return this._format('number', num, options); }, formatMessage: function (message, values) { var locales = this.props.locales || this.context.locales; var formats = this.props.formats || this.context.formats; // When `message` is a function, assume it's an IntlMessageFormat // instance's `format()` method passed by reference, and call it. This // is possible because its `this` will be pre-bound to the instance. if (typeof message === 'function') { return message(values); } if (typeof message === 'string') { message = this.getMessageFormat(message, locales, formats); } return message.format(values); }, getIntlMessage: function (path) { var messages = this.props.messages || this.context.messages; var pathParts = path.split('.'); var message; try { message = pathParts.reduce(function (obj, pathPart) { return obj[pathPart]; }, messages); } finally { if (message === undefined) { throw new ReferenceError('Could not find Intl message: ' + path); } } return message; }, _format: function (type, value, options) { var locales = this.props.locales || this.context.locales; var formats = this.props.formats || this.context.formats; if (options && typeof options === 'string') { try { options = formats[type][options]; } catch (e) { options = undefined; } finally { if (options === undefined) { throw new ReferenceError( 'No ' + type + ' format named: ' + options ); } } } switch(type) { case 'date': case 'time': return this.getDateTimeFormat(locales, options).format(value); case 'number': return this.getNumberFormat(locales, options).format(value); case 'relative': return this.getRelativeFormat(locales, options).format(value); default: throw new Error('Unrecognized format type: ' + type); } }, __addLocaleData: function (data) { intl$messageformat$$default.__addLocaleData(data); intl$relativeformat$$default.__addLocaleData(data); } }; var $$en$$default = {"locale":"en","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"one":"in {0} second","other":"in {0} seconds"},"past":{"one":"{0} second ago","other":"{0} seconds ago"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"one":"in {0} minute","other":"in {0} minutes"},"past":{"one":"{0} minute ago","other":"{0} minutes ago"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"one":"in {0} hour","other":"in {0} hours"},"past":{"one":"{0} hour ago","other":"{0} hours ago"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"one":"in {0} day","other":"in {0} days"},"past":{"one":"{0} day ago","other":"{0} days ago"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"in {0} month","other":"in {0} months"},"past":{"one":"{0} month ago","other":"{0} months ago"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"in {0} year","other":"in {0} years"},"past":{"one":"{0} year ago","other":"{0} years ago"}}}}}; $$mixin$$default.__addLocaleData($$en$$default); var src$main$$default = $$mixin$$default; this['ReactIntlMixin'] = src$main$$default; }).call(this); //# sourceMappingURL=react-intl.js.map ReactIntlMixin.__addLocaleData({"locale":"af","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekonde","relative":{"0":"nou"},"relativeTime":{"future":{"one":"Oor {0} sekonde","other":"Oor {0} sekondes"},"past":{"one":"{0} sekonde gelede","other":"{0} sekondes gelede"}}},"minute":{"displayName":"Minuut","relativeTime":{"future":{"one":"Oor {0} minuut","other":"Oor {0} minute"},"past":{"one":"{0} minuut gelede","other":"{0} minute gelede"}}},"hour":{"displayName":"Uur","relativeTime":{"future":{"one":"Oor {0} uur","other":"Oor {0} uur"},"past":{"one":"{0} uur gelede","other":"{0} uur gelede"}}},"day":{"displayName":"Dag","relative":{"0":"vandag","1":"môre","2":"Die dag na môre","-2":"Die dag voor gister","-1":"gister"},"relativeTime":{"future":{"one":"Oor {0} dag","other":"Oor {0} dae"},"past":{"one":"{0} dag gelede","other":"{0} dae gelede"}}},"month":{"displayName":"Maand","relative":{"0":"vandeesmaand","1":"volgende maand","-1":"verlede maand"},"relativeTime":{"future":{"one":"Oor {0} maand","other":"Oor {0} maande"},"past":{"one":"{0} maand gelede","other":"{0} maande gelede"}}},"year":{"displayName":"Jaar","relative":{"0":"hierdie jaar","1":"volgende jaar","-1":"verlede jaar"},"relativeTime":{"future":{"one":"Oor {0} jaar","other":"Oor {0} jaar"},"past":{"one":"{0} jaar gelede","other":"{0} jaar gelede"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ak","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===Math.floor(n)&&n>=0&&n<=1)return"one";return"other";},"fields":{"second":{"displayName":"Sɛkɛnd","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Sema","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Dɔnhwer","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Da","relative":{"0":"Ndɛ","1":"Ɔkyena","-1":"Ndeda"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Bosome","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Afe","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"am","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"ሰከንድ","relative":{"0":"አሁን"},"relativeTime":{"future":{"one":"በ{0} ሰከንድ ውስጥ","other":"በ{0} ሰከንዶች ውስጥ"},"past":{"one":"ከ{0} ሰከንድ በፊት","other":"ከ{0} ሰከንዶች በፊት"}}},"minute":{"displayName":"ደቂቃ","relativeTime":{"future":{"one":"በ{0} ደቂቃ ውስጥ","other":"በ{0} ደቂቃዎች ውስጥ"},"past":{"one":"ከ{0} ደቂቃ በፊት","other":"ከ{0} ደቂቃዎች በፊት"}}},"hour":{"displayName":"ሰዓት","relativeTime":{"future":{"one":"በ{0} ሰዓት ውስጥ","other":"በ{0} ሰዓቶች ውስጥ"},"past":{"one":"ከ{0} ሰዓት በፊት","other":"ከ{0} ሰዓቶች በፊት"}}},"day":{"displayName":"ቀን","relative":{"0":"ዛሬ","1":"ነገ","2":"ከነገ ወዲያ","-2":"ከትናንት ወዲያ","-1":"ትናንት"},"relativeTime":{"future":{"one":"በ{0} ቀን ውስጥ","other":"በ{0} ቀናት ውስጥ"},"past":{"one":"ከ{0} ቀን በፊት","other":"ከ{0} ቀናት በፊት"}}},"month":{"displayName":"ወር","relative":{"0":"በዚህ ወር","1":"የሚቀጥለው ወር","-1":"ያለፈው ወር"},"relativeTime":{"future":{"one":"በ{0} ወር ውስጥ","other":"በ{0} ወራት ውስጥ"},"past":{"one":"ከ{0} ወር በፊት","other":"ከ{0} ወራት በፊት"}}},"year":{"displayName":"ዓመት","relative":{"0":"በዚህ ዓመት","1":"የሚቀጥለው ዓመት","-1":"ያለፈው ዓመት"},"relativeTime":{"future":{"one":"በ{0} ዓመታት ውስጥ","other":"በ{0} ዓመታት ውስጥ"},"past":{"one":"ከ{0} ዓመት በፊት","other":"ከ{0} ዓመታት በፊት"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ar","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===0)return"zero";if(n===1)return"one";if(n===2)return"two";if(n%100===Math.floor(n%100)&&n%100>=3&&n%100<=10)return"few";if(n%100===Math.floor(n%100)&&n%100>=11&&n%100<=99)return"many";return"other";},"fields":{"second":{"displayName":"الثواني","relative":{"0":"الآن"},"relativeTime":{"future":{"zero":"خلال {0} من الثواني","one":"خلال {0} من الثواني","two":"خلال ثانيتين","few":"خلال {0} ثوانِ","many":"خلال {0} ثانية","other":"خلال {0} من الثواني"},"past":{"zero":"قبل {0} من الثواني","one":"قبل {0} من الثواني","two":"قبل ثانيتين","few":"قبل {0} ثوانِ","many":"قبل {0} ثانية","other":"قبل {0} من الثواني"}}},"minute":{"displayName":"الدقائق","relativeTime":{"future":{"zero":"خلال {0} من الدقائق","one":"خلال {0} من الدقائق","two":"خلال دقيقتين","few":"خلال {0} دقائق","many":"خلال {0} دقيقة","other":"خلال {0} من الدقائق"},"past":{"zero":"قبل {0} من الدقائق","one":"قبل {0} من الدقائق","two":"قبل دقيقتين","few":"قبل {0} دقائق","many":"قبل {0} دقيقة","other":"قبل {0} من الدقائق"}}},"hour":{"displayName":"الساعات","relativeTime":{"future":{"zero":"خلال {0} من الساعات","one":"خلال {0} من الساعات","two":"خلال ساعتين","few":"خلال {0} ساعات","many":"خلال {0} ساعة","other":"خلال {0} من الساعات"},"past":{"zero":"قبل {0} من الساعات","one":"قبل {0} من الساعات","two":"قبل ساعتين","few":"قبل {0} ساعات","many":"قبل {0} ساعة","other":"قبل {0} من الساعات"}}},"day":{"displayName":"يوم","relative":{"0":"اليوم","1":"غدًا","2":"بعد الغد","-2":"أول أمس","-1":"أمس"},"relativeTime":{"future":{"zero":"خلال {0} من الأيام","one":"خلال {0} من الأيام","two":"خلال يومين","few":"خلال {0} أيام","many":"خلال {0} يومًا","other":"خلال {0} من الأيام"},"past":{"zero":"قبل {0} من الأيام","one":"قبل {0} من الأيام","two":"قبل يومين","few":"قبل {0} أيام","many":"قبل {0} يومًا","other":"قبل {0} من الأيام"}}},"month":{"displayName":"الشهر","relative":{"0":"هذا الشهر","1":"الشهر التالي","-1":"الشهر الماضي"},"relativeTime":{"future":{"zero":"خلال {0} من الشهور","one":"خلال {0} من الشهور","two":"خلال شهرين","few":"خلال {0} شهور","many":"خلال {0} شهرًا","other":"خلال {0} من الشهور"},"past":{"zero":"قبل {0} من الشهور","one":"قبل {0} من الشهور","two":"قبل شهرين","few":"قبل {0} أشهر","many":"قبل {0} شهرًا","other":"قبل {0} من الشهور"}}},"year":{"displayName":"السنة","relative":{"0":"هذه السنة","1":"السنة التالية","-1":"السنة الماضية"},"relativeTime":{"future":{"zero":"خلال {0} من السنوات","one":"خلال {0} من السنوات","two":"خلال سنتين","few":"خلال {0} سنوات","many":"خلال {0} سنة","other":"خلال {0} من السنوات"},"past":{"zero":"قبل {0} من السنوات","one":"قبل {0} من السنوات","two":"قبل سنتين","few":"قبل {0} سنوات","many":"قبل {0} سنة","other":"قبل {0} من السنوات"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"as","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"ছেকেণ্ড","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"মিনিট","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"ঘণ্টা","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"দিন","relative":{"0":"today","1":"কাইলৈ","2":"পৰহিলৈ","-2":"পৰহি","-1":"কালি"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"মাহ","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"বছৰ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"asa","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Thekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Thaa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Thiku","relative":{"0":"Iyoo","1":"Yavo","-1":"Ighuo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mweji","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Mwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ast","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"segundu","relative":{"0":"now"},"relativeTime":{"future":{"one":"En {0} segundu","other":"En {0} segundos"},"past":{"one":"Hai {0} segundu","other":"Hai {0} segundos"}}},"minute":{"displayName":"minutu","relativeTime":{"future":{"one":"En {0} minutu","other":"En {0} minutos"},"past":{"one":"Hai {0} minutu","other":"Hai {0} minutos"}}},"hour":{"displayName":"hora","relativeTime":{"future":{"one":"En {0} hora","other":"En {0} hores"},"past":{"one":"Hai {0} hora","other":"Hai {0} hores"}}},"day":{"displayName":"día","relative":{"0":"güei","1":"mañana","2":"pasao mañana","-3":"antantayeri","-2":"antayeri","-1":"ayeri"},"relativeTime":{"future":{"one":"En {0} dia","other":"En {0} díes"},"past":{"one":"Hai {0} dia","other":"Hai {0} díes"}}},"month":{"displayName":"mes","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"En {0} mes","other":"En {0} meses"},"past":{"one":"Hai {0} mes","other":"Hai {0} meses"}}},"year":{"displayName":"añu","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"En {0} añu","other":"En {0} años"},"past":{"one":"Hai {0} añu","other":"Hai {0} años"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"az","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"saniyə","relative":{"0":"indi"},"relativeTime":{"future":{"one":"{0} saniyə ərzində","other":"{0} saniyə ərzində"},"past":{"one":"{0} saniyə öncə","other":"{0} saniyə öncə"}}},"minute":{"displayName":"dəqiqə","relativeTime":{"future":{"one":"{0} dəqiqə ərzində","other":"{0} dəqiqə ərzində"},"past":{"one":"{0} dəqiqə öncə","other":"{0} dəqiqə öncə"}}},"hour":{"displayName":"saat","relativeTime":{"future":{"one":"{0} saat ərzində","other":"{0} saat ərzində"},"past":{"one":"{0} saat öncə","other":"{0} saat öncə"}}},"day":{"displayName":"bu gün","relative":{"0":"bu gün","1":"sabah","-1":"dünən"},"relativeTime":{"future":{"one":"{0} gün ərində","other":"{0} gün ərində"},"past":{"one":"{0} gün öncə","other":"{0} gün öncə"}}},"month":{"displayName":"ay","relative":{"0":"bu ay","1":"gələn ay","-1":"keçən ay"},"relativeTime":{"future":{"one":"{0} ay ərzində","other":"{0} ay ərzində"},"past":{"one":"{0} ay öncə","other":"{0} ay öncə"}}},"year":{"displayName":"il","relative":{"0":"bu il","1":"gələn il","-1":"keçən il"},"relativeTime":{"future":{"one":"{0} il ərzində","other":"{0} il ərzində"},"past":{"one":"{0} il öncə","other":"{0} il öncə"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"be","pluralRuleFunction":function (n) {n=Math.floor(n);if(n%10===1&&(n%100!==11))return"one";if(n%10===Math.floor(n%10)&&n%10>=2&&n%10<=4&&!(n%100>=12&&n%100<=14))return"few";if(n%10===0||n%10===Math.floor(n%10)&&n%10>=5&&n%10<=9||n%100===Math.floor(n%100)&&n%100>=11&&n%100<=14)return"many";return"other";},"fields":{"second":{"displayName":"секунда","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"хвіліна","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"гадзіна","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"дзень","relative":{"0":"сёння","1":"заўтра","2":"паслязаўтра","-2":"пазаўчора","-1":"учора"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"месяц","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"год","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"bem","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekondi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Mineti","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Insa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ubushiku","relative":{"0":"Lelo","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Umweshi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Umwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"bez","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Sihu","relative":{"0":"Neng'u ni","1":"Hilawu","-1":"Igolo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mwedzi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Mwaha","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"bg","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"секунда","relative":{"0":"сега"},"relativeTime":{"future":{"one":"след {0} секунда","other":"след {0} секунди"},"past":{"one":"преди {0} секунда","other":"преди {0} секунди"}}},"minute":{"displayName":"минута","relativeTime":{"future":{"one":"след {0} минута","other":"след {0} минути"},"past":{"one":"преди {0} минута","other":"преди {0} минути"}}},"hour":{"displayName":"час","relativeTime":{"future":{"one":"след {0} час","other":"след {0} часа"},"past":{"one":"преди {0} час","other":"преди {0} часа"}}},"day":{"displayName":"ден","relative":{"0":"днес","1":"утре","2":"вдругиден","-2":"онзи ден","-1":"вчера"},"relativeTime":{"future":{"one":"след {0} дни","other":"след {0} дни"},"past":{"one":"преди {0} ден","other":"преди {0} дни"}}},"month":{"displayName":"месец","relative":{"0":"този месец","1":"следващият месец","-1":"миналият месец"},"relativeTime":{"future":{"one":"след {0} месец","other":"след {0} месеца"},"past":{"one":"преди {0} месец","other":"преди {0} месеца"}}},"year":{"displayName":"година","relative":{"0":"тази година","1":"следващата година","-1":"миналата година"},"relativeTime":{"future":{"one":"след {0} година","other":"след {0} години"},"past":{"one":"преди {0} година","other":"преди {0} години"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"bm","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"sekondi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"miniti","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"lɛrɛ","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"don","relative":{"0":"bi","1":"sini","-1":"kunu"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"kalo","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"san","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"bn","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"সেকেন্ড","relative":{"0":"এখন"},"relativeTime":{"future":{"one":"{0} সেকেন্ডে","other":"{0} সেকেন্ডে"},"past":{"one":"{0} সেকেন্ড পূর্বে","other":"{0} সেকেন্ড পূর্বে"}}},"minute":{"displayName":"মিনিট","relativeTime":{"future":{"one":"{0} মিনিটে","other":"{0} মিনিটে"},"past":{"one":"{0} মিনিট পূর্বে","other":"{0} মিনিট পূর্বে"}}},"hour":{"displayName":"ঘন্টা","relativeTime":{"future":{"one":"{0} ঘন্টায়","other":"{0} ঘন্টায়"},"past":{"one":"{0} ঘন্টা আগে","other":"{0} ঘন্টা আগে"}}},"day":{"displayName":"দিন","relative":{"0":"আজ","1":"আগামীকাল","2":"আগামী পরশু","-2":"গত পরশু","-1":"গতকাল"},"relativeTime":{"future":{"one":"{0} দিনের মধ্যে","other":"{0} দিনের মধ্যে"},"past":{"one":"{0} দিন পূর্বে","other":"{0} দিন পূর্বে"}}},"month":{"displayName":"মাস","relative":{"0":"এই মাস","1":"পরের মাস","-1":"গত মাস"},"relativeTime":{"future":{"one":"{0} মাসে","other":"{0} মাসে"},"past":{"one":"{0} মাস পূর্বে","other":"{0} মাস পূর্বে"}}},"year":{"displayName":"বছর","relative":{"0":"এই বছর","1":"পরের বছর","-1":"গত বছর"},"relativeTime":{"future":{"one":"{0} বছরে","other":"{0} বছরে"},"past":{"one":"{0} বছর পূর্বে","other":"{0} বছর পূর্বে"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"bo","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"སྐར་ཆ།","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"སྐར་མ།","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"ཆུ་ཙོ་","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"ཉིན།","relative":{"0":"དེ་རིང་","1":"སང་ཉིན་","2":"གནངས་ཉིན་ཀ་","-2":"ཁས་ཉིན་ཀ་","-1":"ཁས་ས་"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"ཟླ་བ་","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"ལོ།","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"br","pluralRuleFunction":function (n) {n=Math.floor(n);if(n%10===1&&!(n%100===11||n%100===71||n%100===91))return"one";if(n%10===2&&!(n%100===12||n%100===72||n%100===92))return"two";if(n%10===Math.floor(n%10)&&(n%10>=3&&n%10<=4||n%10===9)&&!(n%100>=10&&n%100<=19||n%100>=70&&n%100<=79||n%100>=90&&n%100<=99))return"few";if((n!==0)&&n%1e6===0)return"many";return"other";},"fields":{"second":{"displayName":"eilenn","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"munut","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"eur","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"hiziv","1":"warcʼhoazh","-2":"dercʼhent-decʼh","-1":"decʼh"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"miz","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"brx","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"सेखेन्द","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"मिनिथ","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"रिंगा","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"सान","relative":{"0":"दिनै","1":"गाबोन","-1":"मैया"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"दान","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"बोसोर","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"bs","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length,f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(v===0&&i%10===1&&((i%100!==11)||f%10===1&&(f%100!==11)))return"one";if(v===0&&i%10===Math.floor(i%10)&&i%10>=2&&i%10<=4&&(!(i%100>=12&&i%100<=14)||f%10===Math.floor(f%10)&&f%10>=2&&f%10<=4&&!(f%100>=12&&f%100<=14)))return"few";return"other";},"fields":{"second":{"displayName":"sekund","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"minut","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"čas","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"dan","relative":{"0":"danas","1":"sutra","2":"prekosutra","-2":"prekjuče","-1":"juče"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"mesec","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"godina","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ca","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"segon","relative":{"0":"ara"},"relativeTime":{"future":{"one":"D'aquí a {0} segon","other":"D'aquí a {0} segons"},"past":{"one":"Fa {0} segon","other":"Fa {0} segons"}}},"minute":{"displayName":"minut","relativeTime":{"future":{"one":"D'aquí a {0} minut","other":"D'aquí a {0} minuts"},"past":{"one":"Fa {0} minut","other":"Fa {0} minuts"}}},"hour":{"displayName":"hora","relativeTime":{"future":{"one":"D'aquí a {0} hora","other":"D'aquí a {0} hores"},"past":{"one":"Fa {0} hora","other":"Fa {0} hores"}}},"day":{"displayName":"dia","relative":{"0":"avui","1":"demà","2":"demà passat","-2":"abans-d'ahir","-1":"ahir"},"relativeTime":{"future":{"one":"D'aquí a {0} dia","other":"D'aquí a {0} dies"},"past":{"one":"Fa {0} dia","other":"Fa {0} dies"}}},"month":{"displayName":"mes","relative":{"0":"aquest mes","1":"el mes que ve","-1":"el mes passat"},"relativeTime":{"future":{"one":"D'aquí a {0} mes","other":"D'aquí a {0} mesos"},"past":{"one":"Fa {0} mes","other":"Fa {0} mesos"}}},"year":{"displayName":"any","relative":{"0":"enguany","1":"l'any que ve","-1":"l'any passat"},"relativeTime":{"future":{"one":"D'aquí a {0} any","other":"D'aquí a {0} anys"},"past":{"one":"Fa {0} any","other":"Fa {0} anys"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"cgg","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Obucweka\u002FEsekendi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Edakiika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Shaaha","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Eizooba","relative":{"0":"Erizooba","1":"Nyenkyakare","-1":"Nyomwabazyo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Omwezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Omwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"chr","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"ᎠᏎᏢ","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"ᎢᏯᏔᏬᏍᏔᏅ","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"ᏑᏣᎶᏓ","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"ᏏᎦ","relative":{"0":"ᎪᎯ ᎢᎦ","1":"ᏌᎾᎴᎢ","-1":"ᏒᎯ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"ᏏᏅᏓ","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"ᏑᏕᏘᏴᏓ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"cs","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";if(i===Math.floor(i)&&i>=2&&i<=4&&v===0)return"few";if((v!==0))return"many";return"other";},"fields":{"second":{"displayName":"Sekunda","relative":{"0":"nyní"},"relativeTime":{"future":{"one":"za {0} sekundu","few":"za {0} sekundy","many":"za {0} sekundy","other":"za {0} sekund"},"past":{"one":"před {0} sekundou","few":"před {0} sekundami","many":"před {0} sekundou","other":"před {0} sekundami"}}},"minute":{"displayName":"Minuta","relativeTime":{"future":{"one":"za {0} minutu","few":"za {0} minuty","many":"za {0} minuty","other":"za {0} minut"},"past":{"one":"před {0} minutou","few":"před {0} minutami","many":"před {0} minutou","other":"před {0} minutami"}}},"hour":{"displayName":"Hodina","relativeTime":{"future":{"one":"za {0} hodinu","few":"za {0} hodiny","many":"za {0} hodiny","other":"za {0} hodin"},"past":{"one":"před {0} hodinou","few":"před {0} hodinami","many":"před {0} hodinou","other":"před {0} hodinami"}}},"day":{"displayName":"Den","relative":{"0":"dnes","1":"zítra","2":"pozítří","-2":"předevčírem","-1":"včera"},"relativeTime":{"future":{"one":"za {0} den","few":"za {0} dny","many":"za {0} dne","other":"za {0} dní"},"past":{"one":"před {0} dnem","few":"před {0} dny","many":"před {0} dnem","other":"před {0} dny"}}},"month":{"displayName":"Měsíc","relative":{"0":"tento měsíc","1":"příští měsíc","-1":"minulý měsíc"},"relativeTime":{"future":{"one":"za {0} měsíc","few":"za {0} měsíce","many":"za {0} měsíce","other":"za {0} měsíců"},"past":{"one":"před {0} měsícem","few":"před {0} měsíci","many":"před {0} měsícem","other":"před {0} měsíci"}}},"year":{"displayName":"Rok","relative":{"0":"tento rok","1":"příští rok","-1":"minulý rok"},"relativeTime":{"future":{"one":"za {0} rok","few":"za {0} roky","many":"za {0} roku","other":"za {0} let"},"past":{"one":"před {0} rokem","few":"před {0} lety","many":"před {0} rokem","other":"před {0} lety"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"cy","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===0)return"zero";if(n===1)return"one";if(n===2)return"two";if(n===3)return"few";if(n===6)return"many";return"other";},"fields":{"second":{"displayName":"Eiliad","relative":{"0":"nawr"},"relativeTime":{"future":{"zero":"Ymhen {0} eiliad","one":"Ymhen eiliad","two":"Ymhen {0} eiliad","few":"Ymhen {0} eiliad","many":"Ymhen {0} eiliad","other":"Ymhen {0} eiliad"},"past":{"zero":"{0} eiliad yn ôl","one":"eiliad yn ôl","two":"{0} eiliad yn ôl","few":"{0} eiliad yn ôl","many":"{0} eiliad yn ôl","other":"{0} eiliad yn ôl"}}},"minute":{"displayName":"Munud","relativeTime":{"future":{"zero":"Ymhen {0} munud","one":"Ymhen munud","two":"Ymhen {0} funud","few":"Ymhen {0} munud","many":"Ymhen {0} munud","other":"Ymhen {0} munud"},"past":{"zero":"{0} munud yn ôl","one":"{0} munud yn ôl","two":"{0} funud yn ôl","few":"{0} munud yn ôl","many":"{0} munud yn ôl","other":"{0} munud yn ôl"}}},"hour":{"displayName":"Awr","relativeTime":{"future":{"zero":"Ymhen {0} awr","one":"Ymhen {0} awr","two":"Ymhen {0} awr","few":"Ymhen {0} awr","many":"Ymhen {0} awr","other":"Ymhen {0} awr"},"past":{"zero":"{0} awr yn ôl","one":"awr yn ôl","two":"{0} awr yn ôl","few":"{0} awr yn ôl","many":"{0} awr yn ôl","other":"{0} awr yn ôl"}}},"day":{"displayName":"Dydd","relative":{"0":"heddiw","1":"yfory","2":"drennydd","-2":"echdoe","-1":"ddoe"},"relativeTime":{"future":{"zero":"Ymhen {0} diwrnod","one":"Ymhen diwrnod","two":"Ymhen deuddydd","few":"Ymhen tridiau","many":"Ymhen {0} diwrnod","other":"Ymhen {0} diwrnod"},"past":{"zero":"{0} diwrnod yn ôl","one":"{0} diwrnod yn ôl","two":"{0} ddiwrnod yn ôl","few":"{0} diwrnod yn ôl","many":"{0} diwrnod yn ôl","other":"{0} diwrnod yn ôl"}}},"month":{"displayName":"Mis","relative":{"0":"y mis hwn","1":"mis nesaf","-1":"mis diwethaf"},"relativeTime":{"future":{"zero":"Ymhen {0} mis","one":"Ymhen mis","two":"Ymhen deufis","few":"Ymhen {0} mis","many":"Ymhen {0} mis","other":"Ymhen {0} mis"},"past":{"zero":"{0} mis yn ôl","one":"{0} mis yn ôl","two":"{0} fis yn ôl","few":"{0} mis yn ôl","many":"{0} mis yn ôl","other":"{0} mis yn ôl"}}},"year":{"displayName":"Blwyddyn","relative":{"0":"eleni","1":"blwyddyn nesaf","-1":"llynedd"},"relativeTime":{"future":{"zero":"Ymhen {0} mlynedd","one":"Ymhen blwyddyn","two":"Ymhen {0} flynedd","few":"Ymhen {0} blynedd","many":"Ymhen {0} blynedd","other":"Ymhen {0} mlynedd"},"past":{"zero":"{0} o flynyddoedd yn ôl","one":"blwyddyn yn ôl","two":"{0} flynedd yn ôl","few":"{0} blynedd yn ôl","many":"{0} blynedd yn ôl","other":"{0} o flynyddoedd yn ôl"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"da","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),t=parseInt(n.toString().replace(/^[^.]*\.?|0+$/g,""),10);n=Math.floor(n);if(n===1||(t!==0)&&(i===0||i===1))return"one";return"other";},"fields":{"second":{"displayName":"Sekund","relative":{"0":"nu"},"relativeTime":{"future":{"one":"om {0} sekund","other":"om {0} sekunder"},"past":{"one":"for {0} sekund siden","other":"for {0} sekunder siden"}}},"minute":{"displayName":"Minut","relativeTime":{"future":{"one":"om {0} minut","other":"om {0} minutter"},"past":{"one":"for {0} minut siden","other":"for {0} minutter siden"}}},"hour":{"displayName":"Time","relativeTime":{"future":{"one":"om {0} time","other":"om {0} timer"},"past":{"one":"for {0} time siden","other":"for {0} timer siden"}}},"day":{"displayName":"Dag","relative":{"0":"i dag","1":"i morgen","2":"i overmorgen","-2":"i forgårs","-1":"i går"},"relativeTime":{"future":{"one":"om {0} døgn","other":"om {0} døgn"},"past":{"one":"for {0} døgn siden","other":"for {0} døgn siden"}}},"month":{"displayName":"Måned","relative":{"0":"denne måned","1":"næste måned","-1":"sidste måned"},"relativeTime":{"future":{"one":"om {0} måned","other":"om {0} måneder"},"past":{"one":"for {0} måned siden","other":"for {0} måneder siden"}}},"year":{"displayName":"År","relative":{"0":"i år","1":"næste år","-1":"sidste år"},"relativeTime":{"future":{"one":"om {0} år","other":"om {0} år"},"past":{"one":"for {0} år siden","other":"for {0} år siden"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"de","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"jetzt"},"relativeTime":{"future":{"one":"In {0} Sekunde","other":"In {0} Sekunden"},"past":{"one":"Vor {0} Sekunde","other":"Vor {0} Sekunden"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"one":"In {0} Minute","other":"In {0} Minuten"},"past":{"one":"Vor {0} Minute","other":"Vor {0} Minuten"}}},"hour":{"displayName":"Stunde","relativeTime":{"future":{"one":"In {0} Stunde","other":"In {0} Stunden"},"past":{"one":"Vor {0} Stunde","other":"Vor {0} Stunden"}}},"day":{"displayName":"Tag","relative":{"0":"Heute","1":"Morgen","2":"Übermorgen","-2":"Vorgestern","-1":"Gestern"},"relativeTime":{"future":{"one":"In {0} Tag","other":"In {0} Tagen"},"past":{"one":"Vor {0} Tag","other":"Vor {0} Tagen"}}},"month":{"displayName":"Monat","relative":{"0":"Dieser Monat","1":"Nächster Monat","-1":"Letzter Monat"},"relativeTime":{"future":{"one":"In {0} Monat","other":"In {0} Monaten"},"past":{"one":"Vor {0} Monat","other":"Vor {0} Monaten"}}},"year":{"displayName":"Jahr","relative":{"0":"Dieses Jahr","1":"Nächstes Jahr","-1":"Letztes Jahr"},"relativeTime":{"future":{"one":"In {0} Jahr","other":"In {0} Jahren"},"past":{"one":"Vor {0} Jahr","other":"Vor {0} Jahren"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"dz","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"སྐར་ཆཱ་","relative":{"0":"now"},"relativeTime":{"future":{"other":"སྐར་ཆ་ {0} ནང་"},"past":{"other":"སྐར་ཆ་ {0} ཧེ་མ་"}}},"minute":{"displayName":"སྐར་མ","relativeTime":{"future":{"other":"སྐར་མ་ {0} ནང་"},"past":{"other":"སྐར་མ་ {0} ཧེ་མ་"}}},"hour":{"displayName":"ཆུ་ཚོད","relativeTime":{"future":{"other":"ཆུ་ཚོད་ {0} ནང་"},"past":{"other":"ཆུ་ཚོད་ {0} ཧེ་མ་"}}},"day":{"displayName":"ཚེས་","relative":{"0":"ད་རིས་","1":"ནངས་པ་","2":"གནངས་ཚེ","-2":"ཁ་ཉིམ","-1":"ཁ་ཙ་"},"relativeTime":{"future":{"other":"ཉིནམ་ {0} ནང་"},"past":{"other":"ཉིནམ་ {0} ཧེ་མ་"}}},"month":{"displayName":"ཟླ་ཝ་","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"ཟླཝ་ {0} ནང་"},"past":{"other":"ཟླཝ་ {0} ཧེ་མ་"}}},"year":{"displayName":"ལོ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"ལོ་འཁོར་ {0} ནང་"},"past":{"other":"ལོ་འཁོར་ {0} ཧེ་མ་"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ee","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"sekend","relative":{"0":"fifi"},"relativeTime":{"future":{"one":"le sekend {0} me","other":"le sekend {0} wo me"},"past":{"one":"sekend {0} si va yi","other":"sekend {0} si wo va yi"}}},"minute":{"displayName":"aɖabaƒoƒo","relativeTime":{"future":{"one":"le aɖabaƒoƒo {0} me","other":"le aɖabaƒoƒo {0} wo me"},"past":{"one":"aɖabaƒoƒo {0} si va yi","other":"aɖabaƒoƒo {0} si wo va yi"}}},"hour":{"displayName":"gaƒoƒo","relativeTime":{"future":{"one":"le gaƒoƒo {0} me","other":"le gaƒoƒo {0} wo me"},"past":{"one":"gaƒoƒo {0} si va yi","other":"gaƒoƒo {0} si wo va yi"}}},"day":{"displayName":"ŋkeke","relative":{"0":"egbe","1":"etsɔ si gbɔna","2":"nyitsɔ si gbɔna","-2":"nyitsɔ si va yi","-1":"etsɔ si va yi"},"relativeTime":{"future":{"one":"le ŋkeke {0} me","other":"le ŋkeke {0} wo me"},"past":{"one":"ŋkeke {0} si va yi","other":"ŋkeke {0} si wo va yi"}}},"month":{"displayName":"ɣleti","relative":{"0":"ɣleti sia","1":"ɣleti si gbɔ na","-1":"ɣleti si va yi"},"relativeTime":{"future":{"one":"le ɣleti {0} me","other":"le ɣleti {0} wo me"},"past":{"one":"ɣleti {0} si va yi","other":"ɣleti {0} si wo va yi"}}},"year":{"displayName":"ƒe","relative":{"0":"ƒe sia","1":"ƒe si gbɔ na","-1":"ƒe si va yi"},"relativeTime":{"future":{"one":"le ƒe {0} me","other":"le ƒe {0} wo me"},"past":{"one":"ƒe {0} si va yi","other":"ƒe {0} si wo va yi"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"el","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Δευτερόλεπτο","relative":{"0":"τώρα"},"relativeTime":{"future":{"one":"Σε {0} δευτερόλεπτο","other":"Σε {0} δευτερόλεπτα"},"past":{"one":"Πριν από {0} δευτερόλεπτο","other":"Πριν από {0} δευτερόλεπτα"}}},"minute":{"displayName":"Λεπτό","relativeTime":{"future":{"one":"Σε {0} λεπτό","other":"Σε {0} λεπτά"},"past":{"one":"Πριν από {0} λεπτό","other":"Πριν από {0} λεπτά"}}},"hour":{"displayName":"Ώρα","relativeTime":{"future":{"one":"Σε {0} ώρα","other":"Σε {0} ώρες"},"past":{"one":"Πριν από {0} ώρα","other":"Πριν από {0} ώρες"}}},"day":{"displayName":"Ημέρα","relative":{"0":"σήμερα","1":"αύριο","2":"μεθαύριο","-2":"προχθές","-1":"χθες"},"relativeTime":{"future":{"one":"Σε {0} ημέρα","other":"Σε {0} ημέρες"},"past":{"one":"Πριν από {0} ημέρα","other":"Πριν από {0} ημέρες"}}},"month":{"displayName":"Μήνας","relative":{"0":"τρέχων μήνας","1":"επόμενος μήνας","-1":"προηγούμενος μήνας"},"relativeTime":{"future":{"one":"Σε {0} μήνα","other":"Σε {0} μήνες"},"past":{"one":"Πριν από {0} μήνα","other":"Πριν από {0} μήνες"}}},"year":{"displayName":"Έτος","relative":{"0":"φέτος","1":"επόμενο έτος","-1":"προηγούμενο έτος"},"relativeTime":{"future":{"one":"Σε {0} έτος","other":"Σε {0} έτη"},"past":{"one":"Πριν από {0} έτος","other":"Πριν από {0} έτη"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"en","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"one":"in {0} second","other":"in {0} seconds"},"past":{"one":"{0} second ago","other":"{0} seconds ago"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"one":"in {0} minute","other":"in {0} minutes"},"past":{"one":"{0} minute ago","other":"{0} minutes ago"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"one":"in {0} hour","other":"in {0} hours"},"past":{"one":"{0} hour ago","other":"{0} hours ago"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"one":"in {0} day","other":"in {0} days"},"past":{"one":"{0} day ago","other":"{0} days ago"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"in {0} month","other":"in {0} months"},"past":{"one":"{0} month ago","other":"{0} months ago"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"in {0} year","other":"in {0} years"},"past":{"one":"{0} year ago","other":"{0} years ago"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"eo","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"es","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"segundo","relative":{"0":"ahora"},"relativeTime":{"future":{"one":"dentro de {0} segundo","other":"dentro de {0} segundos"},"past":{"one":"hace {0} segundo","other":"hace {0} segundos"}}},"minute":{"displayName":"minuto","relativeTime":{"future":{"one":"dentro de {0} minuto","other":"dentro de {0} minutos"},"past":{"one":"hace {0} minuto","other":"hace {0} minutos"}}},"hour":{"displayName":"hora","relativeTime":{"future":{"one":"dentro de {0} hora","other":"dentro de {0} horas"},"past":{"one":"hace {0} hora","other":"hace {0} horas"}}},"day":{"displayName":"día","relative":{"0":"hoy","1":"mañana","2":"pasado mañana","-2":"antes de ayer","-1":"ayer"},"relativeTime":{"future":{"one":"dentro de {0} día","other":"dentro de {0} días"},"past":{"one":"hace {0} día","other":"hace {0} días"}}},"month":{"displayName":"mes","relative":{"0":"este mes","1":"el próximo mes","-1":"el mes pasado"},"relativeTime":{"future":{"one":"dentro de {0} mes","other":"dentro de {0} meses"},"past":{"one":"hace {0} mes","other":"hace {0} meses"}}},"year":{"displayName":"año","relative":{"0":"este año","1":"el próximo año","-1":"el año pasado"},"relativeTime":{"future":{"one":"dentro de {0} año","other":"dentro de {0} años"},"past":{"one":"hace {0} año","other":"hace {0} años"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"et","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"sekund","relative":{"0":"nüüd"},"relativeTime":{"future":{"one":"{0} sekundi pärast","other":"{0} sekundi pärast"},"past":{"one":"{0} sekundi eest","other":"{0} sekundi eest"}}},"minute":{"displayName":"minut","relativeTime":{"future":{"one":"{0} minuti pärast","other":"{0} minuti pärast"},"past":{"one":"{0} minuti eest","other":"{0} minuti eest"}}},"hour":{"displayName":"tund","relativeTime":{"future":{"one":"{0} tunni pärast","other":"{0} tunni pärast"},"past":{"one":"{0} tunni eest","other":"{0} tunni eest"}}},"day":{"displayName":"päev","relative":{"0":"täna","1":"homme","2":"ülehomme","-2":"üleeile","-1":"eile"},"relativeTime":{"future":{"one":"{0} päeva pärast","other":"{0} päeva pärast"},"past":{"one":"{0} päeva eest","other":"{0} päeva eest"}}},"month":{"displayName":"kuu","relative":{"0":"käesolev kuu","1":"järgmine kuu","-1":"eelmine kuu"},"relativeTime":{"future":{"one":"{0} kuu pärast","other":"{0} kuu pärast"},"past":{"one":"{0} kuu eest","other":"{0} kuu eest"}}},"year":{"displayName":"aasta","relative":{"0":"käesolev aasta","1":"järgmine aasta","-1":"eelmine aasta"},"relativeTime":{"future":{"one":"{0} aasta pärast","other":"{0} aasta pärast"},"past":{"one":"{0} aasta eest","other":"{0} aasta eest"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"eu","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Segundoa","relative":{"0":"orain"},"relativeTime":{"future":{"one":"{0} segundo barru","other":"{0} segundo barru"},"past":{"one":"Duela {0} segundo","other":"Duela {0} segundo"}}},"minute":{"displayName":"Minutua","relativeTime":{"future":{"one":"{0} minutu barru","other":"{0} minutu barru"},"past":{"one":"Duela {0} minutu","other":"Duela {0} minutu"}}},"hour":{"displayName":"Ordua","relativeTime":{"future":{"one":"{0} ordu barru","other":"{0} ordu barru"},"past":{"one":"Duela {0} ordu","other":"Duela {0} ordu"}}},"day":{"displayName":"Eguna","relative":{"0":"gaur","1":"bihar","2":"etzi","-2":"herenegun","-1":"atzo"},"relativeTime":{"future":{"one":"{0} egun barru","other":"{0} egun barru"},"past":{"one":"Duela {0} egun","other":"Duela {0} egun"}}},"month":{"displayName":"Hilabetea","relative":{"0":"hilabete hau","1":"hurrengo hilabetea","-1":"aurreko hilabetea"},"relativeTime":{"future":{"one":"{0} hilabete barru","other":"{0} hilabete barru"},"past":{"one":"Duela {0} hilabete","other":"Duela {0} hilabete"}}},"year":{"displayName":"Urtea","relative":{"0":"aurten","1":"hurrengo urtea","-1":"aurreko urtea"},"relativeTime":{"future":{"one":"{0} urte barru","other":"{0} urte barru"},"past":{"one":"Duela {0} urte","other":"Duela {0} urte"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"fa","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"ثانیه","relative":{"0":"اکنون"},"relativeTime":{"future":{"one":"{0} ثانیه بعد","other":"{0} ثانیه بعد"},"past":{"one":"{0} ثانیه پیش","other":"{0} ثانیه پیش"}}},"minute":{"displayName":"دقیقه","relativeTime":{"future":{"one":"{0} دقیقه بعد","other":"{0} دقیقه بعد"},"past":{"one":"{0} دقیقه پیش","other":"{0} دقیقه پیش"}}},"hour":{"displayName":"ساعت","relativeTime":{"future":{"one":"{0} ساعت بعد","other":"{0} ساعت بعد"},"past":{"one":"{0} ساعت پیش","other":"{0} ساعت پیش"}}},"day":{"displayName":"روز","relative":{"0":"امروز","1":"فردا","2":"پس‌فردا","-2":"پریروز","-1":"دیروز"},"relativeTime":{"future":{"one":"{0} روز بعد","other":"{0} روز بعد"},"past":{"one":"{0} روز پیش","other":"{0} روز پیش"}}},"month":{"displayName":"ماه","relative":{"0":"این ماه","1":"ماه آینده","-1":"ماه گذشته"},"relativeTime":{"future":{"one":"{0} ماه بعد","other":"{0} ماه بعد"},"past":{"one":"{0} ماه پیش","other":"{0} ماه پیش"}}},"year":{"displayName":"سال","relative":{"0":"امسال","1":"سال آینده","-1":"سال گذشته"},"relativeTime":{"future":{"one":"{0} سال بعد","other":"{0} سال بعد"},"past":{"one":"{0} سال پیش","other":"{0} سال پیش"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ff","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||i===1)return"one";return"other";},"fields":{"second":{"displayName":"Majaango","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Hoƴom","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Waktu","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ñalnde","relative":{"0":"Hannde","1":"Jaŋngo","-1":"Haŋki"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Lewru","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Hitaande","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"fi","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"sekunti","relative":{"0":"nyt"},"relativeTime":{"future":{"one":"{0} sekunnin päästä","other":"{0} sekunnin päästä"},"past":{"one":"{0} sekunti sitten","other":"{0} sekuntia sitten"}}},"minute":{"displayName":"minuutti","relativeTime":{"future":{"one":"{0} minuutin päästä","other":"{0} minuutin päästä"},"past":{"one":"{0} minuutti sitten","other":"{0} minuuttia sitten"}}},"hour":{"displayName":"tunti","relativeTime":{"future":{"one":"{0} tunnin päästä","other":"{0} tunnin päästä"},"past":{"one":"{0} tunti sitten","other":"{0} tuntia sitten"}}},"day":{"displayName":"päivä","relative":{"0":"tänään","1":"huomenna","2":"ylihuomenna","-2":"toissapäivänä","-1":"eilen"},"relativeTime":{"future":{"one":"{0} päivän päästä","other":"{0} päivän päästä"},"past":{"one":"{0} päivä sitten","other":"{0} päivää sitten"}}},"month":{"displayName":"kuukausi","relative":{"0":"tässä kuussa","1":"ensi kuussa","-1":"viime kuussa"},"relativeTime":{"future":{"one":"{0} kuukauden päästä","other":"{0} kuukauden päästä"},"past":{"one":"{0} kuukausi sitten","other":"{0} kuukautta sitten"}}},"year":{"displayName":"vuosi","relative":{"0":"tänä vuonna","1":"ensi vuonna","-1":"viime vuonna"},"relativeTime":{"future":{"one":"{0} vuoden päästä","other":"{0} vuoden päästä"},"past":{"one":"{0} vuosi sitten","other":"{0} vuotta sitten"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"fil","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length,f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(v===0&&(i===1||i===2||i===3||v===0&&(!(i%10===4||i%10===6||i%10===9)||(v!==0)&&!(f%10===4||f%10===6||f%10===9))))return"one";return"other";},"fields":{"second":{"displayName":"Segundo","relative":{"0":"ngayon"},"relativeTime":{"future":{"one":"Sa loob ng {0} segundo","other":"Sa loob ng {0} segundo"},"past":{"one":"{0} segundo ang nakalipas","other":"{0} segundo ang nakalipas"}}},"minute":{"displayName":"Minuto","relativeTime":{"future":{"one":"Sa loob ng {0} minuto","other":"Sa loob ng {0} minuto"},"past":{"one":"{0} minuto ang nakalipas","other":"{0} minuto ang nakalipas"}}},"hour":{"displayName":"Oras","relativeTime":{"future":{"one":"Sa loob ng {0} oras","other":"Sa loob ng {0} oras"},"past":{"one":"{0} oras ang nakalipas","other":"{0} oras ang nakalipas"}}},"day":{"displayName":"Araw","relative":{"0":"Ngayon","1":"Bukas","2":"Samakalawa","-2":"Araw bago ang kahapon","-1":"Kahapon"},"relativeTime":{"future":{"one":"Sa loob ng {0} araw","other":"Sa loob ng {0} araw"},"past":{"one":"{0} araw ang nakalipas","other":"{0} araw ang nakalipas"}}},"month":{"displayName":"Buwan","relative":{"0":"ngayong buwan","1":"susunod na buwan","-1":"nakaraang buwan"},"relativeTime":{"future":{"one":"Sa loob ng {0} buwan","other":"Sa loob ng {0} buwan"},"past":{"one":"{0} buwan ang nakalipas","other":"{0} buwan ang nakalipas"}}},"year":{"displayName":"Taon","relative":{"0":"ngayong taon","1":"susunod na taon","-1":"nakaraang taon"},"relativeTime":{"future":{"one":"Sa loob ng {0} taon","other":"Sa loob ng {0} taon"},"past":{"one":"{0} taon ang nakalipas","other":"{0} taon ang nakalipas"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"fo","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"sekund","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"mínúta","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"klukkustund","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"dagur","relative":{"0":"í dag","1":"á morgunn","2":"á yfirmorgunn","-2":"í fyrradag","-1":"í gær"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"mánuður","relative":{"0":"henda mánuður","1":"næstu mánuður","-1":"síðstu mánuður"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"ár","relative":{"0":"hetta ár","1":"næstu ár","-1":"síðstu ár"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"fr","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||i===1)return"one";return"other";},"fields":{"second":{"displayName":"seconde","relative":{"0":"maintenant"},"relativeTime":{"future":{"one":"dans {0} seconde","other":"dans {0} secondes"},"past":{"one":"il y a {0} seconde","other":"il y a {0} secondes"}}},"minute":{"displayName":"minute","relativeTime":{"future":{"one":"dans {0} minute","other":"dans {0} minutes"},"past":{"one":"il y a {0} minute","other":"il y a {0} minutes"}}},"hour":{"displayName":"heure","relativeTime":{"future":{"one":"dans {0} heure","other":"dans {0} heures"},"past":{"one":"il y a {0} heure","other":"il y a {0} heures"}}},"day":{"displayName":"jour","relative":{"0":"aujourd’hui","1":"demain","2":"après-demain","-2":"avant-hier","-1":"hier"},"relativeTime":{"future":{"one":"dans {0} jour","other":"dans {0} jours"},"past":{"one":"il y a {0} jour","other":"il y a {0} jours"}}},"month":{"displayName":"mois","relative":{"0":"ce mois-ci","1":"le mois prochain","-1":"le mois dernier"},"relativeTime":{"future":{"one":"dans {0} mois","other":"dans {0} mois"},"past":{"one":"il y a {0} mois","other":"il y a {0} mois"}}},"year":{"displayName":"année","relative":{"0":"cette année","1":"l’année prochaine","-1":"l’année dernière"},"relativeTime":{"future":{"one":"dans {0} an","other":"dans {0} ans"},"past":{"one":"il y a {0} an","other":"il y a {0} ans"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"fur","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"secont","relative":{"0":"now"},"relativeTime":{"future":{"one":"ca di {0} secont","other":"ca di {0} seconts"},"past":{"one":"{0} secont indaûr","other":"{0} seconts indaûr"}}},"minute":{"displayName":"minût","relativeTime":{"future":{"one":"ca di {0} minût","other":"ca di {0} minûts"},"past":{"one":"{0} minût indaûr","other":"{0} minûts indaûr"}}},"hour":{"displayName":"ore","relativeTime":{"future":{"one":"ca di {0} ore","other":"ca di {0} oris"},"past":{"one":"{0} ore indaûr","other":"{0} oris indaûr"}}},"day":{"displayName":"dì","relative":{"0":"vuê","1":"doman","2":"passantdoman","-2":"îr l'altri","-1":"îr"},"relativeTime":{"future":{"one":"ca di {0} zornade","other":"ca di {0} zornadis"},"past":{"one":"{0} zornade indaûr","other":"{0} zornadis indaûr"}}},"month":{"displayName":"mês","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"ca di {0} mês","other":"ca di {0} mês"},"past":{"one":"{0} mês indaûr","other":"{0} mês indaûr"}}},"year":{"displayName":"an","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"ca di {0} an","other":"ca di {0} agns"},"past":{"one":"{0} an indaûr","other":"{0} agns indaûr"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"fy","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Sekonde","relative":{"0":"nu"},"relativeTime":{"future":{"one":"Oer {0} sekonde","other":"Oer {0} sekonden"},"past":{"one":"{0} sekonde lyn","other":"{0} sekonden lyn"}}},"minute":{"displayName":"Minút","relativeTime":{"future":{"one":"Oer {0} minút","other":"Oer {0} minuten"},"past":{"one":"{0} minút lyn","other":"{0} minuten lyn"}}},"hour":{"displayName":"oere","relativeTime":{"future":{"one":"Oer {0} oere","other":"Oer {0} oere"},"past":{"one":"{0} oere lyn","other":"{0} oere lyn"}}},"day":{"displayName":"dei","relative":{"0":"vandaag","1":"morgen","2":"Oermorgen","-2":"eergisteren","-1":"gisteren"},"relativeTime":{"future":{"one":"Oer {0} dei","other":"Oer {0} deien"},"past":{"one":"{0} dei lyn","other":"{0} deien lyn"}}},"month":{"displayName":"Moanne","relative":{"0":"dizze moanne","1":"folgjende moanne","-1":"foarige moanne"},"relativeTime":{"future":{"one":"Oer {0} moanne","other":"Oer {0} moannen"},"past":{"one":"{0} moanne lyn","other":"{0} moannen lyn"}}},"year":{"displayName":"Jier","relative":{"0":"dit jier","1":"folgjend jier","-1":"foarich jier"},"relativeTime":{"future":{"one":"Oer {0} jier","other":"Oer {0} jier"},"past":{"one":"{0} jier lyn","other":"{0} jier lyn"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ga","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";if(n===2)return"two";if(n===Math.floor(n)&&n>=3&&n<=6)return"few";if(n===Math.floor(n)&&n>=7&&n<=10)return"many";return"other";},"fields":{"second":{"displayName":"Soicind","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Nóiméad","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Uair","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Lá","relative":{"0":"Inniu","1":"Amárach","2":"Arú amárach","-2":"Arú inné","-1":"Inné"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mí","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Bliain","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"gd","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1||n===11)return"one";if(n===2||n===12)return"two";if(n===Math.floor(n)&&(n>=3&&n<=10||n>=13&&n<=19))return"few";return"other";},"fields":{"second":{"displayName":"Diog","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Mionaid","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Uair a thìde","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Latha","relative":{"0":"An-diugh","1":"A-màireach","2":"An-earar","-2":"A-bhòin-dè","-1":"An-dè"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mìos","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Bliadhna","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"gl","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Segundo","relative":{"0":"agora"},"relativeTime":{"future":{"one":"En {0} segundo","other":"En {0} segundos"},"past":{"one":"Hai {0} segundo","other":"Hai {0} segundos"}}},"minute":{"displayName":"Minuto","relativeTime":{"future":{"one":"En {0} minuto","other":"En {0} minutos"},"past":{"one":"Hai {0} minuto","other":"Hai {0} minutos"}}},"hour":{"displayName":"Hora","relativeTime":{"future":{"one":"En {0} hora","other":"En {0} horas"},"past":{"one":"Hai {0} hora","other":"Hai {0} horas"}}},"day":{"displayName":"Día","relative":{"0":"hoxe","1":"mañá","2":"pasadomañá","-2":"antonte","-1":"onte"},"relativeTime":{"future":{"one":"En {0} día","other":"En {0} días"},"past":{"one":"Hai {0} día","other":"Hai {0} días"}}},"month":{"displayName":"Mes","relative":{"0":"este mes","1":"mes seguinte","-1":"mes pasado"},"relativeTime":{"future":{"one":"En {0} mes","other":"En {0} meses"},"past":{"one":"Hai {0} mes","other":"Hai {0} meses"}}},"year":{"displayName":"Ano","relative":{"0":"este ano","1":"seguinte ano","-1":"ano pasado"},"relativeTime":{"future":{"one":"En {0} ano","other":"En {0} anos"},"past":{"one":"Hai {0} ano","other":"Hai {0} anos"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"gsw","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minuute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Schtund","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Tag","relative":{"0":"hüt","1":"moorn","2":"übermoorn","-2":"vorgeschter","-1":"geschter"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Monet","relative":{"0":"diese Monet","1":"nächste Monet","-1":"letzte Monet"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Jaar","relative":{"0":"diese Jaar","1":"nächste Jaar","-1":"letzte Jaar"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"gu","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"સેકન્ડ","relative":{"0":"હમણાં"},"relativeTime":{"future":{"one":"{0} સેકંડમાં","other":"{0} સેકંડમાં"},"past":{"one":"{0} સેકંડ પહેલા","other":"{0} સેકંડ પહેલા"}}},"minute":{"displayName":"મિનિટ","relativeTime":{"future":{"one":"{0} મિનિટમાં","other":"{0} મિનિટમાં"},"past":{"one":"{0} મિનિટ પહેલા","other":"{0} મિનિટ પહેલા"}}},"hour":{"displayName":"કલાક","relativeTime":{"future":{"one":"{0} કલાકમાં","other":"{0} કલાકમાં"},"past":{"one":"{0} કલાક પહેલા","other":"{0} કલાક પહેલા"}}},"day":{"displayName":"દિવસ","relative":{"0":"આજે","1":"આવતીકાલે","2":"પરમદિવસે","-2":"ગયા પરમદિવસે","-1":"ગઈકાલે"},"relativeTime":{"future":{"one":"{0} દિવસમાં","other":"{0} દિવસમાં"},"past":{"one":"{0} દિવસ પહેલા","other":"{0} દિવસ પહેલા"}}},"month":{"displayName":"મહિનો","relative":{"0":"આ મહિને","1":"આવતા મહિને","-1":"ગયા મહિને"},"relativeTime":{"future":{"one":"{0} મહિનામાં","other":"{0} મહિનામાં"},"past":{"one":"{0} મહિના પહેલા","other":"{0} મહિના પહેલા"}}},"year":{"displayName":"વર્ષ","relative":{"0":"આ વર્ષે","1":"આવતા વર્ષે","-1":"ગયા વર્ષે"},"relativeTime":{"future":{"one":"{0} વર્ષમાં","other":"{0} વર્ષમાં"},"past":{"one":"{0} વર્ષ પહેલા","other":"{0} વર્ષ પહેલા"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"gv","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(v===0&&i%10===1)return"one";if(v===0&&i%10===2)return"two";if(v===0&&(i%100===0||i%100===20||i%100===40||i%100===60||i%100===80))return"few";if((v!==0))return"many";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ha","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Daƙiƙa","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minti","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Awa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Kwana","relative":{"0":"Yau","1":"Gobe","-1":"Jiya"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Wata","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Shekara","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"haw","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"he","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";if(i===2&&v===0)return"two";if(v===0&&!(n>=0&&n<=10)&&n%10===0)return"many";return"other";},"fields":{"second":{"displayName":"שנייה","relative":{"0":"עכשיו"},"relativeTime":{"future":{"one":"בעוד שנייה {0}","two":"בעוד {0} שניות","many":"בעוד {0} שניות","other":"בעוד {0} שניות"},"past":{"one":"לפני שנייה {0}","two":"לפני {0} שניות","many":"לפני {0} שניות","other":"לפני {0} שניות"}}},"minute":{"displayName":"דקה","relativeTime":{"future":{"one":"בעוד דקה {0}","two":"בעוד {0} דקות","many":"בעוד {0} דקות","other":"בעוד {0} דקות"},"past":{"one":"לפני דקה {0}","two":"לפני {0} דקות","many":"לפני {0} דקות","other":"לפני {0} דקות"}}},"hour":{"displayName":"שעה","relativeTime":{"future":{"one":"בעוד שעה {0}","two":"בעוד {0} שעות","many":"בעוד {0} שעות","other":"בעוד {0} שעות"},"past":{"one":"לפני שעה {0}","two":"לפני {0} שעות","many":"לפני {0} שעות","other":"לפני {0} שעות"}}},"day":{"displayName":"יום","relative":{"0":"היום","1":"מחר","2":"מחרתיים","-2":"שלשום","-1":"אתמול"},"relativeTime":{"future":{"one":"בעוד יום {0}","two":"בעוד {0} ימים","many":"בעוד {0} ימים","other":"בעוד {0} ימים"},"past":{"one":"לפני יום {0}","two":"לפני {0} ימים","many":"לפני {0} ימים","other":"לפני {0} ימים"}}},"month":{"displayName":"חודש","relative":{"0":"החודש","1":"החודש הבא","-1":"החודש שעבר"},"relativeTime":{"future":{"one":"בעוד חודש {0}","two":"בעוד {0} חודשים","many":"בעוד {0} חודשים","other":"בעוד {0} חודשים"},"past":{"one":"לפני חודש {0}","two":"לפני {0} חודשים","many":"לפני {0} חודשים","other":"לפני {0} חודשים"}}},"year":{"displayName":"שנה","relative":{"0":"השנה","1":"השנה הבאה","-1":"השנה שעברה"},"relativeTime":{"future":{"one":"בעוד שנה {0}","two":"בעוד {0} שנים","many":"בעוד {0} שנים","other":"בעוד {0} שנים"},"past":{"one":"לפני שנה {0}","two":"לפני {0} שנים","many":"לפני {0} שנים","other":"לפני {0} שנים"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"hi","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"सेकंड","relative":{"0":"अब"},"relativeTime":{"future":{"one":"{0} सेकंड में","other":"{0} सेकंड में"},"past":{"one":"{0} सेकंड पहले","other":"{0} सेकंड पहले"}}},"minute":{"displayName":"मिनट","relativeTime":{"future":{"one":"{0} मिनट में","other":"{0} मिनट में"},"past":{"one":"{0} मिनट पहले","other":"{0} मिनट पहले"}}},"hour":{"displayName":"घंटा","relativeTime":{"future":{"one":"{0} घंटे में","other":"{0} घंटे में"},"past":{"one":"{0} घंटे पहले","other":"{0} घंटे पहले"}}},"day":{"displayName":"दिन","relative":{"0":"आज","1":"आने वाला कल","2":"परसों","-2":"बीता परसों","-1":"बीता कल"},"relativeTime":{"future":{"one":"{0} दिन में","other":"{0} दिन में"},"past":{"one":"{0} दिन पहले","other":"{0} दिन पहले"}}},"month":{"displayName":"माह","relative":{"0":"यह माह","1":"अगला माह","-1":"पिछला माह"},"relativeTime":{"future":{"one":"{0} माह में","other":"{0} माह में"},"past":{"one":"{0} माह पहले","other":"{0} माह पहले"}}},"year":{"displayName":"वर्ष","relative":{"0":"यह वर्ष","1":"अगला वर्ष","-1":"पिछला वर्ष"},"relativeTime":{"future":{"one":"{0} वर्ष में","other":"{0} वर्ष में"},"past":{"one":"{0} वर्ष पहले","other":"{0} वर्ष पहले"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"hr","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length,f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(v===0&&i%10===1&&((i%100!==11)||f%10===1&&(f%100!==11)))return"one";if(v===0&&i%10===Math.floor(i%10)&&i%10>=2&&i%10<=4&&(!(i%100>=12&&i%100<=14)||f%10===Math.floor(f%10)&&f%10>=2&&f%10<=4&&!(f%100>=12&&f%100<=14)))return"few";return"other";},"fields":{"second":{"displayName":"Sekunda","relative":{"0":"sada"},"relativeTime":{"future":{"one":"za {0} sekundu","few":"za {0} sekunde","other":"za {0} sekundi"},"past":{"one":"prije {0} sekundu","few":"prije {0} sekunde","other":"prije {0} sekundi"}}},"minute":{"displayName":"Minuta","relativeTime":{"future":{"one":"za {0} minutu","few":"za {0} minute","other":"za {0} minuta"},"past":{"one":"prije {0} minutu","few":"prije {0} minute","other":"prije {0} minuta"}}},"hour":{"displayName":"Sat","relativeTime":{"future":{"one":"za {0} sat","few":"za {0} sata","other":"za {0} sati"},"past":{"one":"prije {0} sat","few":"prije {0} sata","other":"prije {0} sati"}}},"day":{"displayName":"Dan","relative":{"0":"danas","1":"sutra","2":"prekosutra","-2":"prekjučer","-1":"jučer"},"relativeTime":{"future":{"one":"za {0} dan","few":"za {0} dana","other":"za {0} dana"},"past":{"one":"prije {0} dan","few":"prije {0} dana","other":"prije {0} dana"}}},"month":{"displayName":"Mjesec","relative":{"0":"ovaj mjesec","1":"sljedeći mjesec","-1":"prošli mjesec"},"relativeTime":{"future":{"one":"za {0} mjesec","few":"za {0} mjeseca","other":"za {0} mjeseci"},"past":{"one":"prije {0} mjesec","few":"prije {0} mjeseca","other":"prije {0} mjeseci"}}},"year":{"displayName":"Godina","relative":{"0":"ove godine","1":"sljedeće godine","-1":"prošle godine"},"relativeTime":{"future":{"one":"za {0} godinu","few":"za {0} godine","other":"za {0} godina"},"past":{"one":"prije {0} godinu","few":"prije {0} godine","other":"prije {0} godina"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"hu","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"másodperc","relative":{"0":"most"},"relativeTime":{"future":{"one":"{0} másodperc múlva","other":"{0} másodperc múlva"},"past":{"one":"{0} másodperccel ezelőtt","other":"{0} másodperccel ezelőtt"}}},"minute":{"displayName":"perc","relativeTime":{"future":{"one":"{0} perc múlva","other":"{0} perc múlva"},"past":{"one":"{0} perccel ezelőtt","other":"{0} perccel ezelőtt"}}},"hour":{"displayName":"óra","relativeTime":{"future":{"one":"{0} óra múlva","other":"{0} óra múlva"},"past":{"one":"{0} órával ezelőtt","other":"{0} órával ezelőtt"}}},"day":{"displayName":"nap","relative":{"0":"ma","1":"holnap","2":"holnapután","-2":"tegnapelőtt","-1":"tegnap"},"relativeTime":{"future":{"one":"{0} nap múlva","other":"{0} nap múlva"},"past":{"one":"{0} nappal ezelőtt","other":"{0} nappal ezelőtt"}}},"month":{"displayName":"hónap","relative":{"0":"ez a hónap","1":"következő hónap","-1":"előző hónap"},"relativeTime":{"future":{"one":"{0} hónap múlva","other":"{0} hónap múlva"},"past":{"one":"{0} hónappal ezelőtt","other":"{0} hónappal ezelőtt"}}},"year":{"displayName":"év","relative":{"0":"ez az év","1":"következő év","-1":"előző év"},"relativeTime":{"future":{"one":"{0} év múlva","other":"{0} év múlva"},"past":{"one":"{0} évvel ezelőtt","other":"{0} évvel ezelőtt"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"hy","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||i===1)return"one";return"other";},"fields":{"second":{"displayName":"Վայրկյան","relative":{"0":"այժմ"},"relativeTime":{"future":{"one":"{0} վայրկյան անց","other":"{0} վայրկյան անց"},"past":{"one":"{0} վայրկյան առաջ","other":"{0} վայրկյան առաջ"}}},"minute":{"displayName":"Րոպե","relativeTime":{"future":{"one":"{0} րոպե անց","other":"{0} րոպե անց"},"past":{"one":"{0} րոպե առաջ","other":"{0} րոպե առաջ"}}},"hour":{"displayName":"Ժամ","relativeTime":{"future":{"one":"{0} ժամ անց","other":"{0} ժամ անց"},"past":{"one":"{0} ժամ առաջ","other":"{0} ժամ առաջ"}}},"day":{"displayName":"Օր","relative":{"0":"այսօր","1":"վաղը","2":"վաղը չէ մյուս օրը","-2":"երեկ չէ առաջի օրը","-1":"երեկ"},"relativeTime":{"future":{"one":"{0} օր անց","other":"{0} օր անց"},"past":{"one":"{0} օր առաջ","other":"{0} օր առաջ"}}},"month":{"displayName":"Ամիս","relative":{"0":"այս ամիս","1":"հաջորդ ամիս","-1":"անցյալ ամիս"},"relativeTime":{"future":{"one":"{0} ամիս անց","other":"{0} ամիս անց"},"past":{"one":"{0} ամիս առաջ","other":"{0} ամիս առաջ"}}},"year":{"displayName":"Տարի","relative":{"0":"այս տարի","1":"հաջորդ տարի","-1":"անցյալ տարի"},"relativeTime":{"future":{"one":"{0} տարի անց","other":"{0} տարի անց"},"past":{"one":"{0} տարի առաջ","other":"{0} տարի առաջ"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"id","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Detik","relative":{"0":"sekarang"},"relativeTime":{"future":{"other":"Dalam {0} detik"},"past":{"other":"{0} detik yang lalu"}}},"minute":{"displayName":"Menit","relativeTime":{"future":{"other":"Dalam {0} menit"},"past":{"other":"{0} menit yang lalu"}}},"hour":{"displayName":"Jam","relativeTime":{"future":{"other":"Dalam {0} jam"},"past":{"other":"{0} jam yang lalu"}}},"day":{"displayName":"Hari","relative":{"0":"hari ini","1":"besok","2":"lusa","-2":"kemarin lusa","-1":"kemarin"},"relativeTime":{"future":{"other":"Dalam {0} hari"},"past":{"other":"{0} hari yang lalu"}}},"month":{"displayName":"Bulan","relative":{"0":"bulan ini","1":"Bulan berikutnya","-1":"bulan lalu"},"relativeTime":{"future":{"other":"Dalam {0} bulan"},"past":{"other":"{0} bulan yang lalu"}}},"year":{"displayName":"Tahun","relative":{"0":"tahun ini","1":"tahun depan","-1":"tahun lalu"},"relativeTime":{"future":{"other":"Dalam {0} tahun"},"past":{"other":"{0} tahun yang lalu"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ig","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Nkejinta","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Nkeji","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Elekere","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ụbọchị","relative":{"0":"Taata","1":"Echi","-1":"Nnyaafụ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Ọnwa","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Afọ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ii","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"ꇙ","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"ꃏ","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"ꄮꈉ","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"ꑍ","relative":{"0":"ꀃꑍ","1":"ꃆꏂꑍ","2":"ꌕꀿꑍ","-2":"ꎴꂿꋍꑍ","-1":"ꀋꅔꉈ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"ꆪ","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"ꈎ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"is","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),t=parseInt(n.toString().replace(/^[^.]*\.?|0+$/g,""),10);n=Math.floor(n);if(t===0&&i%10===1&&((i%100!==11)||(t!==0)))return"one";return"other";},"fields":{"second":{"displayName":"sekúnda","relative":{"0":"núna"},"relativeTime":{"future":{"one":"eftir {0} sekúndu","other":"eftir {0} sekúndur"},"past":{"one":"fyrir {0} sekúndu","other":"fyrir {0} sekúndum"}}},"minute":{"displayName":"mínúta","relativeTime":{"future":{"one":"eftir {0} mínútu","other":"eftir {0} mínútur"},"past":{"one":"fyrir {0} mínútu","other":"fyrir {0} mínútum"}}},"hour":{"displayName":"klukkustund","relativeTime":{"future":{"one":"eftir {0} klukkustund","other":"eftir {0} klukkustundir"},"past":{"one":"fyrir {0} klukkustund","other":"fyrir {0} klukkustundum"}}},"day":{"displayName":"dagur","relative":{"0":"í dag","1":"á morgun","2":"eftir tvo daga","-2":"í fyrradag","-1":"í gær"},"relativeTime":{"future":{"one":"eftir {0} dag","other":"eftir {0} daga"},"past":{"one":"fyrir {0} degi","other":"fyrir {0} dögum"}}},"month":{"displayName":"mánuður","relative":{"0":"í þessum mánuði","1":"í næsta mánuði","-1":"í síðasta mánuði"},"relativeTime":{"future":{"one":"eftir {0} mánuð","other":"eftir {0} mánuði"},"past":{"one":"fyrir {0} mánuði","other":"fyrir {0} mánuðum"}}},"year":{"displayName":"ár","relative":{"0":"á þessu ári","1":"á næsta ári","-1":"á síðasta ári"},"relativeTime":{"future":{"one":"eftir {0} ár","other":"eftir {0} ár"},"past":{"one":"fyrir {0} ári","other":"fyrir {0} árum"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"it","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"secondo","relative":{"0":"ora"},"relativeTime":{"future":{"one":"tra {0} secondo","other":"tra {0} secondi"},"past":{"one":"{0} secondo fa","other":"{0} secondi fa"}}},"minute":{"displayName":"minuto","relativeTime":{"future":{"one":"tra {0} minuto","other":"tra {0} minuti"},"past":{"one":"{0} minuto fa","other":"{0} minuti fa"}}},"hour":{"displayName":"ora","relativeTime":{"future":{"one":"tra {0} ora","other":"tra {0} ore"},"past":{"one":"{0} ora fa","other":"{0} ore fa"}}},"day":{"displayName":"giorno","relative":{"0":"oggi","1":"domani","2":"dopodomani","-2":"l'altro ieri","-1":"ieri"},"relativeTime":{"future":{"one":"tra {0} giorno","other":"tra {0} giorni"},"past":{"one":"{0} giorno fa","other":"{0} giorni fa"}}},"month":{"displayName":"mese","relative":{"0":"questo mese","1":"mese prossimo","-1":"mese scorso"},"relativeTime":{"future":{"one":"tra {0} mese","other":"tra {0} mesi"},"past":{"one":"{0} mese fa","other":"{0} mesi fa"}}},"year":{"displayName":"anno","relative":{"0":"quest'anno","1":"anno prossimo","-1":"anno scorso"},"relativeTime":{"future":{"one":"tra {0} anno","other":"tra {0} anni"},"past":{"one":"{0} anno fa","other":"{0} anni fa"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ja","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"秒","relative":{"0":"今すぐ"},"relativeTime":{"future":{"other":"{0} 秒後"},"past":{"other":"{0} 秒前"}}},"minute":{"displayName":"分","relativeTime":{"future":{"other":"{0} 分後"},"past":{"other":"{0} 分前"}}},"hour":{"displayName":"時","relativeTime":{"future":{"other":"{0} 時間後"},"past":{"other":"{0} 時間前"}}},"day":{"displayName":"日","relative":{"0":"今日","1":"明日","2":"明後日","-2":"一昨日","-1":"昨日"},"relativeTime":{"future":{"other":"{0} 日後"},"past":{"other":"{0} 日前"}}},"month":{"displayName":"月","relative":{"0":"今月","1":"翌月","-1":"先月"},"relativeTime":{"future":{"other":"{0} か月後"},"past":{"other":"{0} か月前"}}},"year":{"displayName":"年","relative":{"0":"今年","1":"翌年","-1":"昨年"},"relativeTime":{"future":{"other":"{0} 年後"},"past":{"other":"{0} 年前"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"jgo","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"one":"nǔu {0} minút","other":"nǔu {0} minút"},"past":{"one":"ɛ́ gɛ́ mɔ́ minút {0}","other":"ɛ́ gɛ́ mɔ́ minút {0}"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"one":"nǔu háwa {0}","other":"nǔu háwa {0}"},"past":{"one":"ɛ́ gɛ mɔ́ {0} háwa","other":"ɛ́ gɛ mɔ́ {0} háwa"}}},"day":{"displayName":"Day","relative":{"0":"lɔꞋɔ","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"one":"Nǔu lɛ́Ꞌ {0}","other":"Nǔu lɛ́Ꞌ {0}"},"past":{"one":"Ɛ́ gɛ́ mɔ́ lɛ́Ꞌ {0}","other":"Ɛ́ gɛ́ mɔ́ lɛ́Ꞌ {0}"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"Nǔu {0} saŋ","other":"Nǔu {0} saŋ"},"past":{"one":"ɛ́ gɛ́ mɔ́ pɛsaŋ {0}","other":"ɛ́ gɛ́ mɔ́ pɛsaŋ {0}"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"Nǔu ŋguꞋ {0}","other":"Nǔu ŋguꞋ {0}"},"past":{"one":"Ɛ́gɛ́ mɔ́ ŋguꞋ {0}","other":"Ɛ́gɛ́ mɔ́ ŋguꞋ {0}"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"jmc","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakyika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Mfiri","relative":{"0":"Inu","1":"Ngama","-1":"Ukou"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mori","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Maka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ka","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"წამი","relative":{"0":"ახლა"},"relativeTime":{"future":{"one":"{0} წამში","other":"{0} წამში"},"past":{"one":"{0} წამის წინ","other":"{0} წამის წინ"}}},"minute":{"displayName":"წუთი","relativeTime":{"future":{"one":"{0} წუთში","other":"{0} წუთში"},"past":{"one":"{0} წუთის წინ","other":"{0} წუთის წინ"}}},"hour":{"displayName":"საათი","relativeTime":{"future":{"one":"{0} საათში","other":"{0} საათში"},"past":{"one":"{0} საათის წინ","other":"{0} საათის წინ"}}},"day":{"displayName":"დღე","relative":{"0":"დღეს","1":"ხვალ","2":"ზეგ","-2":"გუშინწინ","-1":"გუშინ"},"relativeTime":{"future":{"one":"{0} დღეში","other":"{0} დღეში"},"past":{"one":"{0} დღის წინ","other":"{0} დღის წინ"}}},"month":{"displayName":"თვე","relative":{"0":"ამ თვეში","1":"მომავალ თვეს","-1":"გასულ თვეს"},"relativeTime":{"future":{"one":"{0} თვეში","other":"{0} თვეში"},"past":{"one":"{0} თვის წინ","other":"{0} თვის წინ"}}},"year":{"displayName":"წელი","relative":{"0":"ამ წელს","1":"მომავალ წელს","-1":"გასულ წელს"},"relativeTime":{"future":{"one":"{0} წელიწადში","other":"{0} წელიწადში"},"past":{"one":"{0} წლის წინ","other":"{0} წლის წინ"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kab","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||i===1)return"one";return"other";},"fields":{"second":{"displayName":"Tasint","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Tamrect","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Tamert","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ass","relative":{"0":"Ass-a","1":"Azekka","-1":"Iḍelli"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Aggur","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Aseggas","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kde","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Lihiku","relative":{"0":"Nelo","1":"Nundu","-1":"Lido"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mwedi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Mwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kea","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Sigundu","relative":{"0":"now"},"relativeTime":{"future":{"other":"di li {0} sigundu"},"past":{"other":"a ten {0} sigundu"}}},"minute":{"displayName":"Minutu","relativeTime":{"future":{"other":"di li {0} minutu"},"past":{"other":"a ten {0} minutu"}}},"hour":{"displayName":"Ora","relativeTime":{"future":{"other":"di li {0} ora"},"past":{"other":"a ten {0} ora"}}},"day":{"displayName":"Dia","relative":{"0":"Oji","1":"Manha","-1":"Onti"},"relativeTime":{"future":{"other":"di li {0} dia"},"past":{"other":"a ten {0} dia"}}},"month":{"displayName":"Mes","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"di li {0} mes"},"past":{"other":"a ten {0} mes"}}},"year":{"displayName":"Anu","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"di li {0} anu"},"past":{"other":"a ten {0} anu"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kk","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"секунд","relative":{"0":"қазір"},"relativeTime":{"future":{"one":"{0} секундтан кейін","other":"{0} секундтан кейін"},"past":{"one":"{0} секунд бұрын","other":"{0} секунд бұрын"}}},"minute":{"displayName":"минут","relativeTime":{"future":{"one":"{0} минуттан кейін","other":"{0} минуттан кейін"},"past":{"one":"{0} минут бұрын","other":"{0} минут бұрын"}}},"hour":{"displayName":"сағат","relativeTime":{"future":{"one":"{0} сағаттан кейін","other":"{0} сағаттан кейін"},"past":{"one":"{0} сағат бұрын","other":"{0} сағат бұрын"}}},"day":{"displayName":"күн","relative":{"0":"бүгін","1":"ертең","2":"арғы күні","-2":"алдыңғы күні","-1":"кеше"},"relativeTime":{"future":{"one":"{0} күннен кейін","other":"{0} күннен кейін"},"past":{"one":"{0} күн бұрын","other":"{0} күн бұрын"}}},"month":{"displayName":"ай","relative":{"0":"осы ай","1":"келесі ай","-1":"өткен ай"},"relativeTime":{"future":{"one":"{0} айдан кейін","other":"{0} айдан кейін"},"past":{"one":"{0} ай бұрын","other":"{0} ай бұрын"}}},"year":{"displayName":"жыл","relative":{"0":"биылғы жыл","1":"келесі жыл","-1":"былтырғы жыл"},"relativeTime":{"future":{"one":"{0} жылдан кейін","other":"{0} жылдан кейін"},"past":{"one":"{0} жыл бұрын","other":"{0} жыл бұрын"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kkj","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"muka","1":"nɛmɛnɔ","-1":"kwey"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kl","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"sekundi","relative":{"0":"now"},"relativeTime":{"future":{"one":"om {0} sekundi","other":"om {0} sekundi"},"past":{"one":"for {0} sekundi siden","other":"for {0} sekundi siden"}}},"minute":{"displayName":"minutsi","relativeTime":{"future":{"one":"om {0} minutsi","other":"om {0} minutsi"},"past":{"one":"for {0} minutsi siden","other":"for {0} minutsi siden"}}},"hour":{"displayName":"nalunaaquttap-akunnera","relativeTime":{"future":{"one":"om {0} nalunaaquttap-akunnera","other":"om {0} nalunaaquttap-akunnera"},"past":{"one":"for {0} nalunaaquttap-akunnera siden","other":"for {0} nalunaaquttap-akunnera siden"}}},"day":{"displayName":"ulloq","relative":{"0":"ullumi","1":"aqagu","2":"aqaguagu","-2":"ippassaani","-1":"ippassaq"},"relativeTime":{"future":{"one":"om {0} ulloq unnuarlu","other":"om {0} ulloq unnuarlu"},"past":{"one":"for {0} ulloq unnuarlu siden","other":"for {0} ulloq unnuarlu siden"}}},"month":{"displayName":"qaammat","relative":{"0":"manna qaammat","1":"tulleq qaammat","-1":"kingulleq qaammat"},"relativeTime":{"future":{"one":"om {0} qaammat","other":"om {0} qaammat"},"past":{"one":"for {0} qaammat siden","other":"for {0} qaammat siden"}}},"year":{"displayName":"ukioq","relative":{"0":"manna ukioq","1":"tulleq ukioq","-1":"kingulleq ukioq"},"relativeTime":{"future":{"one":"om {0} ukioq","other":"om {0} ukioq"},"past":{"one":"for {0} ukioq siden","other":"for {0} ukioq siden"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"km","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"វិនាទី","relative":{"0":"ឥឡូវ"},"relativeTime":{"future":{"other":"ក្នុង​រយៈពេល {0} វិនាទី"},"past":{"other":"{0} វិនាទី​មុន"}}},"minute":{"displayName":"នាទី","relativeTime":{"future":{"other":"ក្នុង​រយៈពេល {0} នាទី"},"past":{"other":"{0} នាទី​មុន"}}},"hour":{"displayName":"ម៉ោង","relativeTime":{"future":{"other":"ក្នុង​រយៈ​ពេល {0} ម៉ោង"},"past":{"other":"{0} ម៉ោង​មុន"}}},"day":{"displayName":"ថ្ងៃ","relative":{"0":"ថ្ងៃ​នេះ","1":"ថ្ងៃ​ស្អែក","2":"​ខាន​ស្អែក","-2":"ម្សិល​ម៉្ងៃ","-1":"ម្សិលមិញ"},"relativeTime":{"future":{"other":"ក្នុង​រយៈ​ពេល {0} ថ្ងៃ"},"past":{"other":"{0} ថ្ងៃ​មុន"}}},"month":{"displayName":"ខែ","relative":{"0":"ខែ​នេះ","1":"ខែ​ក្រោយ","-1":"ខែ​មុន"},"relativeTime":{"future":{"other":"ក្នុង​រយៈ​ពេល {0} ខែ"},"past":{"other":"{0} ខែមុន"}}},"year":{"displayName":"ឆ្នាំ","relative":{"0":"ឆ្នាំ​នេះ","1":"ឆ្នាំ​ក្រោយ","-1":"ឆ្នាំ​មុន"},"relativeTime":{"future":{"other":"ក្នុង​រយៈ​ពេល {0} ឆ្នាំ"},"past":{"other":"{0} ឆ្នាំ​មុន"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kn","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"ಸೆಕೆಂಡ್","relative":{"0":"ಇದೀಗ"},"relativeTime":{"future":{"one":"{0} ಸೆಕೆಂಡ್‌ಗಳಲ್ಲಿ","other":"{0} ಸೆಕೆಂಡ್‌ಗಳಲ್ಲಿ"},"past":{"one":"{0} ಸೆಕೆಂಡುಗಳ ಹಿಂದೆ","other":"{0} ಸೆಕೆಂಡುಗಳ ಹಿಂದೆ"}}},"minute":{"displayName":"ನಿಮಿಷ","relativeTime":{"future":{"one":"{0} ನಿಮಿಷಗಳಲ್ಲಿ","other":"{0} ನಿಮಿಷಗಳಲ್ಲಿ"},"past":{"one":"{0} ನಿಮಿಷಗಳ ಹಿಂದೆ","other":"{0} ನಿಮಿಷಗಳ ಹಿಂದೆ"}}},"hour":{"displayName":"ಗಂಟೆ","relativeTime":{"future":{"one":"{0} ಗಂಟೆಗಳಲ್ಲಿ","other":"{0} ಗಂಟೆಗಳಲ್ಲಿ"},"past":{"one":"{0} ಗಂಟೆಗಳ ಹಿಂದೆ","other":"{0} ಗಂಟೆಗಳ ಹಿಂದೆ"}}},"day":{"displayName":"ದಿನ","relative":{"0":"ಇಂದು","1":"ನಾಳೆ","2":"ನಾಡಿದ್ದು","-2":"ಮೊನ್ನೆ","-1":"ನಿನ್ನೆ"},"relativeTime":{"future":{"one":"{0} ದಿನಗಳಲ್ಲಿ","other":"{0} ದಿನಗಳಲ್ಲಿ"},"past":{"one":"{0} ದಿನಗಳ ಹಿಂದೆ","other":"{0} ದಿನಗಳ ಹಿಂದೆ"}}},"month":{"displayName":"ತಿಂಗಳು","relative":{"0":"ಈ ತಿಂಗಳು","1":"ಮುಂದಿನ ತಿಂಗಳು","-1":"ಕಳೆದ ತಿಂಗಳು"},"relativeTime":{"future":{"one":"{0} ತಿಂಗಳುಗಳಲ್ಲಿ","other":"{0} ತಿಂಗಳುಗಳಲ್ಲಿ"},"past":{"one":"{0} ತಿಂಗಳುಗಳ ಹಿಂದೆ","other":"{0} ತಿಂಗಳುಗಳ ಹಿಂದೆ"}}},"year":{"displayName":"ವರ್ಷ","relative":{"0":"ಈ ವರ್ಷ","1":"ಮುಂದಿನ ವರ್ಷ","-1":"ಕಳೆದ ವರ್ಷ"},"relativeTime":{"future":{"one":"{0} ವರ್ಷಗಳಲ್ಲಿ","other":"{0} ವರ್ಷಗಳಲ್ಲಿ"},"past":{"one":"{0} ವರ್ಷಗಳ ಹಿಂದೆ","other":"{0} ವರ್ಷಗಳ ಹಿಂದೆ"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ko","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"초","relative":{"0":"지금"},"relativeTime":{"future":{"other":"{0}초 후"},"past":{"other":"{0}초 전"}}},"minute":{"displayName":"분","relativeTime":{"future":{"other":"{0}분 후"},"past":{"other":"{0}분 전"}}},"hour":{"displayName":"시","relativeTime":{"future":{"other":"{0}시간 후"},"past":{"other":"{0}시간 전"}}},"day":{"displayName":"일","relative":{"0":"오늘","1":"내일","2":"모레","-2":"그저께","-1":"어제"},"relativeTime":{"future":{"other":"{0}일 후"},"past":{"other":"{0}일 전"}}},"month":{"displayName":"월","relative":{"0":"이번 달","1":"다음 달","-1":"지난달"},"relativeTime":{"future":{"other":"{0}개월 후"},"past":{"other":"{0}개월 전"}}},"year":{"displayName":"년","relative":{"0":"올해","1":"내년","-1":"지난해"},"relativeTime":{"future":{"other":"{0}년 후"},"past":{"other":"{0}년 전"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ks","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"سٮ۪کَنڑ","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"مِنَٹ","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"گٲنٛٹہٕ","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"دۄہ","relative":{"0":"اَز","1":"پگاہ","-1":"راتھ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"رٮ۪تھ","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"ؤری","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ksb","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Siku","relative":{"0":"Evi eo","1":"Keloi","-1":"Ghuo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Ng'ezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Ng'waka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ksh","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===0)return"zero";if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekond","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Menutt","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Schtund","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Daach","relative":{"0":"hück","1":"morje","2":"övvermorje","-2":"vörjestere","-1":"jestere"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mohnd","relative":{"0":"diese Mohnd","1":"nächste Mohnd","-1":"lätzde Mohnd"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Johr","relative":{"0":"diese Johr","1":"nächste Johr","-1":"läz Johr"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"kw","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";if(n===2)return"two";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Eur","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Dedh","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mis","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Bledhen","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ky","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"секунд","relative":{"0":"азыр"},"relativeTime":{"future":{"one":"{0} секунддан кийин","other":"{0} секунддан кийин"},"past":{"one":"{0} секунд мурун","other":"{0} секунд мурун"}}},"minute":{"displayName":"мүнөт","relativeTime":{"future":{"one":"{0} мүнөттөн кийин","other":"{0} мүнөттөн кийин"},"past":{"one":"{0} мүнөт мурун","other":"{0} мүнөт мурун"}}},"hour":{"displayName":"саат","relativeTime":{"future":{"one":"{0} сааттан кийин","other":"{0} сааттан кийин"},"past":{"one":"{0} саат мурун","other":"{0} саат мурун"}}},"day":{"displayName":"күн","relative":{"0":"бүгүн","1":"эртеӊ","2":"бүрсүгүнү","-2":"мурдагы күнү","-1":"кечээ"},"relativeTime":{"future":{"one":"{0} күндөн кийин","other":"{0} күндөн кийин"},"past":{"one":"{0} күн мурун","other":"{0} күн мурун"}}},"month":{"displayName":"ай","relative":{"0":"бул айда","1":"эмдиги айда","-1":"өткөн айда"},"relativeTime":{"future":{"one":"{0} айдан кийин","other":"{0} айдан кийин"},"past":{"one":"{0} ай мурун","other":"{0} ай мурун"}}},"year":{"displayName":"жыл","relative":{"0":"быйыл","1":"эмдиги жылы","-1":"былтыр"},"relativeTime":{"future":{"one":"{0} жылдан кийин","other":"{0} жылдан кийин"},"past":{"one":"{0} жыл мурун","other":"{0} жыл мурун"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"lag","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(n===0)return"zero";if((i===0||i===1)&&(n!==0))return"one";return"other";},"fields":{"second":{"displayName":"Sekúunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakíka","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Sáa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Sikʉ","relative":{"0":"Isikʉ","1":"Lamʉtoondo","-1":"Niijo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mweéri","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Mwaáka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"lg","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Kasikonda","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakiika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saawa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Lunaku","relative":{"0":"Lwaleero","1":"Nkya","-1":"Ggulo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mwezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Mwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"lkt","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Okpí","relative":{"0":"now"},"relativeTime":{"future":{"other":"Letáŋhaŋ okpí {0} kiŋháŋ"},"past":{"other":"Hékta okpí {0} k’uŋ héhaŋ"}}},"minute":{"displayName":"Owápȟe oȟʼáŋkȟo","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Owápȟe","relativeTime":{"future":{"other":"Letáŋhaŋ owápȟe {0} kiŋháŋ"},"past":{"other":"Hékta owápȟe {0} kʼuŋ héhaŋ"}}},"day":{"displayName":"Aŋpétu","relative":{"0":"Lé aŋpétu kiŋ","1":"Híŋhaŋni kiŋháŋ","-1":"Lé aŋpétu kiŋ"},"relativeTime":{"future":{"other":"Letáŋhaŋ {0}-čháŋ kiŋháŋ"},"past":{"other":"Hékta {0}-čháŋ k’uŋ héhaŋ"}}},"month":{"displayName":"Wí","relative":{"0":"Lé wí kiŋ","1":"Wí kiŋháŋ","-1":"Wí kʼuŋ héhaŋ"},"relativeTime":{"future":{"other":"Letáŋhaŋ wíyawapi {0} kiŋháŋ"},"past":{"other":"Hékta wíyawapi {0} kʼuŋ héhaŋ"}}},"year":{"displayName":"Ómakȟa","relative":{"0":"Lé ómakȟa kiŋ","1":"Tȟokáta ómakȟa kiŋháŋ","-1":"Ómakȟa kʼuŋ héhaŋ"},"relativeTime":{"future":{"other":"Letáŋhaŋ ómakȟa {0} kiŋháŋ"},"past":{"other":"Hékta ómakȟa {0} kʼuŋ héhaŋ"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ln","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===Math.floor(n)&&n>=0&&n<=1)return"one";return"other";},"fields":{"second":{"displayName":"Sɛkɔ́ndɛ","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Monúti","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Ngonga","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Mokɔlɔ","relative":{"0":"Lɛlɔ́","1":"Lóbi ekoyâ","-1":"Lóbi elékí"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Sánzá","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Mobú","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"lo","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"ວິນາທີ","relative":{"0":"ຕອນນີ້"},"relativeTime":{"future":{"other":"ໃນອີກ {0} ວິນາທີ"},"past":{"other":"{0} ວິນາທີກ່ອນ"}}},"minute":{"displayName":"ນາທີ","relativeTime":{"future":{"other":"{0} ໃນອີກ 0 ນາທີ"},"past":{"other":"{0} ນາທີກ່ອນ"}}},"hour":{"displayName":"ຊົ່ວໂມງ","relativeTime":{"future":{"other":"ໃນອີກ {0} ຊົ່ວໂມງ"},"past":{"other":"{0} ຊົ່ວໂມງກ່ອນ"}}},"day":{"displayName":"ມື້","relative":{"0":"ມື້ນີ້","1":"ມື້ອື່ນ","2":"ມື້ຮື","-2":"ມື້ກ່ອນ","-1":"ມື້ວານ"},"relativeTime":{"future":{"other":"ໃນອີກ {0} ມື້"},"past":{"other":"{0} ມື້ກ່ອນ"}}},"month":{"displayName":"ເດືອນ","relative":{"0":"ເດືອນນີ້","1":"ເດືອນໜ້າ","-1":"ເດືອນແລ້ວ"},"relativeTime":{"future":{"other":"ໃນອີກ {0} ເດືອນ"},"past":{"other":"{0} ເດືອນກ່ອນ"}}},"year":{"displayName":"ປີ","relative":{"0":"ປີນີ້","1":"ປີໜ້າ","-1":"ປີກາຍ"},"relativeTime":{"future":{"other":"ໃນອີກ {0} ປີ"},"past":{"other":"{0} ປີກ່ອນ"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"lt","pluralRuleFunction":function (n) {var f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(n%10===1&&!(n%100>=11&&n%100<=19))return"one";if(n%10===Math.floor(n%10)&&n%10>=2&&n%10<=9&&!(n%100>=11&&n%100<=19))return"few";if((f!==0))return"many";return"other";},"fields":{"second":{"displayName":"Sekundė","relative":{"0":"dabar"},"relativeTime":{"future":{"one":"po {0} sekundės","few":"po {0} sekundžių","many":"po {0} sekundės","other":"po {0} sekundžių"},"past":{"one":"prieš {0} sekundę","few":"prieš {0} sekundes","many":"prieš {0} sekundės","other":"prieš {0} sekundžių"}}},"minute":{"displayName":"Minutė","relativeTime":{"future":{"one":"po {0} minutės","few":"po {0} minučių","many":"po {0} minutės","other":"po {0} minučių"},"past":{"one":"prieš {0} minutę","few":"prieš {0} minutes","many":"prieš {0} minutės","other":"prieš {0} minučių"}}},"hour":{"displayName":"Valanda","relativeTime":{"future":{"one":"po {0} valandos","few":"po {0} valandų","many":"po {0} valandos","other":"po {0} valandų"},"past":{"one":"prieš {0} valandą","few":"prieš {0} valandas","many":"prieš {0} valandos","other":"prieš {0} valandų"}}},"day":{"displayName":"Diena","relative":{"0":"šiandien","1":"rytoj","2":"poryt","-2":"užvakar","-1":"vakar"},"relativeTime":{"future":{"one":"po {0} dienos","few":"po {0} dienų","many":"po {0} dienos","other":"po {0} dienų"},"past":{"one":"prieš {0} dieną","few":"prieš {0} dienas","many":"prieš {0} dienos","other":"prieš {0} dienų"}}},"month":{"displayName":"Mėnuo","relative":{"0":"šį mėnesį","1":"kitą mėnesį","-1":"praėjusį mėnesį"},"relativeTime":{"future":{"one":"po {0} mėnesio","few":"po {0} mėnesių","many":"po {0} mėnesio","other":"po {0} mėnesių"},"past":{"one":"prieš {0} mėnesį","few":"prieš {0} mėnesius","many":"prieš {0} mėnesio","other":"prieš {0} mėnesių"}}},"year":{"displayName":"Metai","relative":{"0":"šiais metais","1":"kitais metais","-1":"praėjusiais metais"},"relativeTime":{"future":{"one":"po {0} metų","few":"po {0} metų","many":"po {0} metų","other":"po {0} metų"},"past":{"one":"prieš {0} metus","few":"prieš {0} metus","many":"prieš {0} metų","other":"prieš {0} metų"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"lv","pluralRuleFunction":function (n) {var v=n.toString().replace(/^[^.]*\.?/,"").length,f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(n%10===0||n%100===Math.floor(n%100)&&n%100>=11&&n%100<=19||v===2&&f%100===Math.floor(f%100)&&f%100>=11&&f%100<=19)return"zero";if(n%10===1&&((n%100!==11)||v===2&&f%10===1&&((f%100!==11)||(v!==2)&&f%10===1)))return"one";return"other";},"fields":{"second":{"displayName":"Sekundes","relative":{"0":"tagad"},"relativeTime":{"future":{"zero":"Pēc {0} sekundēm","one":"Pēc {0} sekundes","other":"Pēc {0} sekundēm"},"past":{"zero":"Pirms {0} sekundēm","one":"Pirms {0} sekundes","other":"Pirms {0} sekundēm"}}},"minute":{"displayName":"Minūtes","relativeTime":{"future":{"zero":"Pēc {0} minūtēm","one":"Pēc {0} minūtes","other":"Pēc {0} minūtēm"},"past":{"zero":"Pirms {0} minūtēm","one":"Pirms {0} minūtes","other":"Pirms {0} minūtēm"}}},"hour":{"displayName":"Stundas","relativeTime":{"future":{"zero":"Pēc {0} stundām","one":"Pēc {0} stundas","other":"Pēc {0} stundām"},"past":{"zero":"Pirms {0} stundām","one":"Pirms {0} stundas","other":"Pirms {0} stundām"}}},"day":{"displayName":"Diena","relative":{"0":"šodien","1":"rīt","2":"parīt","-2":"aizvakar","-1":"vakar"},"relativeTime":{"future":{"zero":"Pēc {0} dienām","one":"Pēc {0} dienas","other":"Pēc {0} dienām"},"past":{"zero":"Pirms {0} dienām","one":"Pirms {0} dienas","other":"Pirms {0} dienām"}}},"month":{"displayName":"Mēnesis","relative":{"0":"šomēnes","1":"nākammēnes","-1":"pagājušajā mēnesī"},"relativeTime":{"future":{"zero":"Pēc {0} mēnešiem","one":"Pēc {0} mēneša","other":"Pēc {0} mēnešiem"},"past":{"zero":"Pirms {0} mēnešiem","one":"Pirms {0} mēneša","other":"Pirms {0} mēnešiem"}}},"year":{"displayName":"Gads","relative":{"0":"šogad","1":"nākamgad","-1":"pagājušajā gadā"},"relativeTime":{"future":{"zero":"Pēc {0} gadiem","one":"Pēc {0} gada","other":"Pēc {0} gadiem"},"past":{"zero":"Pirms {0} gadiem","one":"Pirms {0} gada","other":"Pirms {0} gadiem"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"mas","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Oldákikaè","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Ɛ́sáâ","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ɛnkɔlɔ́ŋ","relative":{"0":"Táatá","1":"Tááisérè","-1":"Ŋolé"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Ɔlápà","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Ɔlárì","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"mg","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===Math.floor(n)&&n>=0&&n<=1)return"one";return"other";},"fields":{"second":{"displayName":"Segondra","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minitra","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Ora","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Andro","relative":{"0":"Anio","1":"Rahampitso","-1":"Omaly"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Volana","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Taona","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"mgo","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"one":"+{0} s","other":"+{0} s"},"past":{"one":"-{0} s","other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"one":"+{0} min","other":"+{0} min"},"past":{"one":"-{0} min","other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"one":"+{0} h","other":"+{0} h"},"past":{"one":"-{0} h","other":"-{0} h"}}},"day":{"displayName":"anəg","relative":{"0":"tèchɔ̀ŋ","1":"isu","2":"isu ywi","-1":"ikwiri"},"relativeTime":{"future":{"one":"+{0} d","other":"+{0} d"},"past":{"one":"-{0} d","other":"-{0} d"}}},"month":{"displayName":"iməg","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"+{0} m","other":"+{0} m"},"past":{"one":"-{0} m","other":"-{0} m"}}},"year":{"displayName":"fituʼ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"mk","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length,f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(v===0&&(i%10===1||f%10===1))return"one";return"other";},"fields":{"second":{"displayName":"Секунда","relative":{"0":"сега"},"relativeTime":{"future":{"one":"За {0} секунда","other":"За {0} секунди"},"past":{"one":"Пред {0} секунда","other":"Пред {0} секунди"}}},"minute":{"displayName":"Минута","relativeTime":{"future":{"one":"За {0} минута","other":"За {0} минути"},"past":{"one":"Пред {0} минута","other":"Пред {0} минути"}}},"hour":{"displayName":"Час","relativeTime":{"future":{"one":"За {0} час","other":"За {0} часа"},"past":{"one":"Пред {0} час","other":"Пред {0} часа"}}},"day":{"displayName":"ден","relative":{"0":"Денес","1":"утре","2":"задутре","-2":"завчера","-1":"вчера"},"relativeTime":{"future":{"one":"За {0} ден","other":"За {0} дена"},"past":{"one":"Пред {0} ден","other":"Пред {0} дена"}}},"month":{"displayName":"Месец","relative":{"0":"овој месец","1":"следниот месец","-1":"минатиот месец"},"relativeTime":{"future":{"one":"За {0} месец","other":"За {0} месеци"},"past":{"one":"Пред {0} месец","other":"Пред {0} месеци"}}},"year":{"displayName":"година","relative":{"0":"оваа година","1":"следната година","-1":"минатата година"},"relativeTime":{"future":{"one":"За {0} година","other":"За {0} години"},"past":{"one":"Пред {0} година","other":"Пред {0} години"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ml","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"സെക്കൻറ്","relative":{"0":"ഇപ്പോൾ"},"relativeTime":{"future":{"one":"{0} സെക്കൻഡിൽ","other":"{0} സെക്കൻഡിൽ"},"past":{"one":"{0} സെക്കൻറ് മുമ്പ്","other":"{0} സെക്കൻറ് മുമ്പ്"}}},"minute":{"displayName":"മിനിട്ട്","relativeTime":{"future":{"one":"{0} മിനിറ്റിൽ","other":"{0} മിനിറ്റിനുള്ളിൽ"},"past":{"one":"{0} മിനിറ്റ് മുമ്പ്","other":"{0} മിനിറ്റ് മുമ്പ്"}}},"hour":{"displayName":"മണിക്കൂർ","relativeTime":{"future":{"one":"{0} മണിക്കൂറിൽ","other":"{0} മണിക്കൂറിൽ"},"past":{"one":"{0} മണിക്കൂർ മുമ്പ്","other":"{0} മണിക്കൂർ മുമ്പ്"}}},"day":{"displayName":"ദിവസം","relative":{"0":"ഇന്ന്","1":"നാളെ","2":"മറ്റന്നാൾ","-2":"മിനിഞ്ഞാന്ന്","-1":"ഇന്നലെ"},"relativeTime":{"future":{"one":"{0} ദിവസത്തിൽ","other":"{0} ദിവസത്തിൽ"},"past":{"one":"{0} ദിവസം മുമ്പ്","other":"{0} ദിവസം മുമ്പ്"}}},"month":{"displayName":"മാസം","relative":{"0":"ഈ മാസം","1":"അടുത്ത മാസം","-1":"കഴിഞ്ഞ മാസം"},"relativeTime":{"future":{"one":"{0} മാസത്തിൽ","other":"{0} മാസത്തിൽ"},"past":{"one":"{0} മാസം മുമ്പ്","other":"{0} മാസം മുമ്പ്"}}},"year":{"displayName":"വർഷം","relative":{"0":"ഈ വർ‌ഷം","1":"അടുത്തവർഷം","-1":"കഴിഞ്ഞ വർഷം"},"relativeTime":{"future":{"one":"{0} വർഷത്തിൽ","other":"{0} വർഷത്തിൽ"},"past":{"one":"{0} വർഷം മുമ്പ്","other":"{0} വർഷം മുമ്പ്"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"mn","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Секунд","relative":{"0":"Одоо"},"relativeTime":{"future":{"one":"{0} секундын дараа","other":"{0} секундын дараа"},"past":{"one":"{0} секундын өмнө","other":"{0} секундын өмнө"}}},"minute":{"displayName":"Минут","relativeTime":{"future":{"one":"{0} минутын дараа","other":"{0} минутын дараа"},"past":{"one":"{0} минутын өмнө","other":"{0} минутын өмнө"}}},"hour":{"displayName":"Цаг","relativeTime":{"future":{"one":"{0} цагийн дараа","other":"{0} цагийн дараа"},"past":{"one":"{0} цагийн өмнө","other":"{0} цагийн өмнө"}}},"day":{"displayName":"Өдөр","relative":{"0":"өнөөдөр","1":"маргааш","2":"Нөгөөдөр","-2":"Уржигдар","-1":"өчигдөр"},"relativeTime":{"future":{"one":"{0} өдрийн дараа","other":"{0} өдрийн дараа"},"past":{"one":"{0} өдрийн өмнө","other":"{0} өдрийн өмнө"}}},"month":{"displayName":"Сар","relative":{"0":"энэ сар","1":"ирэх сар","-1":"өнгөрсөн сар"},"relativeTime":{"future":{"one":"{0} сарын дараа","other":"{0} сарын дараа"},"past":{"one":"{0} сарын өмнө","other":"{0} сарын өмнө"}}},"year":{"displayName":"Жил","relative":{"0":"энэ жил","1":"ирэх жил","-1":"өнгөрсөн жил"},"relativeTime":{"future":{"one":"{0} жилийн дараа","other":"{0} жилийн дараа"},"past":{"one":"{0} жилийн өмнө","other":"{0} жилийн өмнө"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"mr","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"सेकंद","relative":{"0":"आत्ता"},"relativeTime":{"future":{"one":"{0} सेकंदामध्ये","other":"{0} सेकंदांमध्ये"},"past":{"one":"{0} सेकंदापूर्वी","other":"{0} सेकंदांपूर्वी"}}},"minute":{"displayName":"मिनिट","relativeTime":{"future":{"one":"{0} मिनिटामध्ये","other":"{0} मिनिटांमध्ये"},"past":{"one":"{0} मिनिटापूर्वी","other":"{0} मिनिटांपूर्वी"}}},"hour":{"displayName":"तास","relativeTime":{"future":{"one":"{0} तासामध्ये","other":"{0} तासांमध्ये"},"past":{"one":"{0} तासापूर्वी","other":"{0} तासांपूर्वी"}}},"day":{"displayName":"दिवस","relative":{"0":"आज","1":"उद्या","-1":"काल"},"relativeTime":{"future":{"one":"{0} दिवसामध्ये","other":"{0} दिवसांमध्ये"},"past":{"one":"{0} दिवसापूर्वी","other":"{0} दिवसांपूर्वी"}}},"month":{"displayName":"महिना","relative":{"0":"हा महिना","1":"पुढील महिना","-1":"मागील महिना"},"relativeTime":{"future":{"one":"{0} महिन्यामध्ये","other":"{0} महिन्यांमध्ये"},"past":{"one":"{0} महिन्यापूर्वी","other":"{0} महिन्यांपूर्वी"}}},"year":{"displayName":"वर्ष","relative":{"0":"हे वर्ष","1":"पुढील वर्ष","-1":"मागील वर्ष"},"relativeTime":{"future":{"one":"{0} वर्षामध्ये","other":"{0} वर्षांमध्ये"},"past":{"one":"{0} वर्षापूर्वी","other":"{0} वर्षांपूर्वी"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ms","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Kedua","relative":{"0":"sekarang"},"relativeTime":{"future":{"other":"Dalam {0} saat"},"past":{"other":"{0} saat lalu"}}},"minute":{"displayName":"Minit","relativeTime":{"future":{"other":"Dalam {0} minit"},"past":{"other":"{0} minit lalu"}}},"hour":{"displayName":"Jam","relativeTime":{"future":{"other":"Dalam {0} jam"},"past":{"other":"{0} jam lalu"}}},"day":{"displayName":"Hari","relative":{"0":"Hari ini","1":"Esok","2":"Hari selepas esok","-2":"Hari sebelum semalam","-1":"Semalam"},"relativeTime":{"future":{"other":"Dalam {0} hari"},"past":{"other":"{0} hari lalu"}}},"month":{"displayName":"Bulan","relative":{"0":"bulan ini","1":"bulan depan","-1":"bulan lalu"},"relativeTime":{"future":{"other":"Dalam {0} bulan"},"past":{"other":"{0} bulan lalu"}}},"year":{"displayName":"Tahun","relative":{"0":"tahun ini","1":"tahun depan","-1":"tahun lepas"},"relativeTime":{"future":{"other":"Dalam {0} tahun"},"past":{"other":"{0} tahun lalu"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"mt","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";if(n===0||n%100===Math.floor(n%100)&&n%100>=2&&n%100<=10)return"few";if(n%100===Math.floor(n%100)&&n%100>=11&&n%100<=19)return"many";return"other";},"fields":{"second":{"displayName":"Sekonda","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minuta","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Siegħa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Jum","relative":{"0":"Illum","1":"Għada","-1":"Ilbieraħ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Xahar","relative":{"0":"Dan ix-xahar","1":"Ix-xahar id-dieħel","-1":"Ix-xahar li għadda"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Sena","relative":{"0":"Din is-sena","1":"Is-sena d-dieħla","-1":"Is-sena li għaddiet"},"relativeTime":{"past":{"one":"{0} sena ilu","few":"{0} snin ilu","many":"{0} snin ilu","other":"{0} snin ilu"},"future":{"other":"+{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"my","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"စက္ကန့်","relative":{"0":"ယခု"},"relativeTime":{"future":{"other":"{0}စက္ကန့်အတွင်း"},"past":{"other":"လွန်ခဲ့သော{0}စက္ကန့်"}}},"minute":{"displayName":"မိနစ်","relativeTime":{"future":{"other":"{0}မိနစ်အတွင်း"},"past":{"other":"လွန်ခဲ့သော{0}မိနစ်"}}},"hour":{"displayName":"နာရီ","relativeTime":{"future":{"other":"{0}နာရီအတွင်း"},"past":{"other":"လွန်ခဲ့သော{0}နာရီ"}}},"day":{"displayName":"ရက်","relative":{"0":"ယနေ့","1":"မနက်ဖြန်","2":"သဘက်ခါ","-2":"တနေ့က","-1":"မနေ့က"},"relativeTime":{"future":{"other":"{0}ရက်အတွင်း"},"past":{"other":"လွန်ခဲ့သော{0}ရက်"}}},"month":{"displayName":"လ","relative":{"0":"ယခုလ","1":"နောက်လ","-1":"ယမန်လ"},"relativeTime":{"future":{"other":"{0}လအတွင်း"},"past":{"other":"လွန်ခဲ့သော{0}လ"}}},"year":{"displayName":"နှစ်","relative":{"0":"ယခုနှစ်","1":"နောက်နှစ်","-1":"ယမန်နှစ်"},"relativeTime":{"future":{"other":"{0}နှစ်အတွင်း"},"past":{"other":"လွန်ခဲ့သော{0}နှစ်"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"naq","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";if(n===2)return"two";return"other";},"fields":{"second":{"displayName":"ǀGâub","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Haib","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Iiri","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Tsees","relative":{"0":"Neetsee","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"ǁKhâb","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Kurib","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nb","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekund","relative":{"0":"nå"},"relativeTime":{"future":{"one":"om {0} sekund","other":"om {0} sekunder"},"past":{"one":"for {0} sekund siden","other":"for {0} sekunder siden"}}},"minute":{"displayName":"Minutt","relativeTime":{"future":{"one":"om {0} minutt","other":"om {0} minutter"},"past":{"one":"for {0} minutt siden","other":"for {0} minutter siden"}}},"hour":{"displayName":"Time","relativeTime":{"future":{"one":"om {0} time","other":"om {0} timer"},"past":{"one":"for {0} time siden","other":"for {0} timer siden"}}},"day":{"displayName":"Dag","relative":{"0":"i dag","1":"i morgen","2":"i overmorgen","-2":"i forgårs","-1":"i går"},"relativeTime":{"future":{"one":"om {0} døgn","other":"om {0} døgn"},"past":{"one":"for {0} døgn siden","other":"for {0} døgn siden"}}},"month":{"displayName":"Måned","relative":{"0":"Denne måneden","1":"Neste måned","-1":"Sist måned"},"relativeTime":{"future":{"one":"om {0} måned","other":"om {0} måneder"},"past":{"one":"for {0} måned siden","other":"for {0} måneder siden"}}},"year":{"displayName":"År","relative":{"0":"Dette året","1":"Neste år","-1":"I fjor"},"relativeTime":{"future":{"one":"om {0} år","other":"om {0} år"},"past":{"one":"for {0} år siden","other":"for {0} år siden"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nd","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Isekendi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Umuzuzu","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Ihola","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ilanga","relative":{"0":"Lamuhla","1":"Kusasa","-1":"Izolo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Inyangacale","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Umnyaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ne","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"दोस्रो","relative":{"0":"अब"},"relativeTime":{"future":{"one":"{0} सेकेण्डमा","other":"{0} सेकेण्डमा"},"past":{"one":"{0} सेकेण्ड पहिले","other":"{0} सेकेण्ड पहिले"}}},"minute":{"displayName":"मिनेट","relativeTime":{"future":{"one":"{0} मिनेटमा","other":"{0} मिनेटमा"},"past":{"one":"{0} मिनेट पहिले","other":"{0} मिनेट पहिले"}}},"hour":{"displayName":"घण्टा","relativeTime":{"future":{"one":"{0} घण्टामा","other":"{0} घण्टामा"},"past":{"one":"{0} घण्टा पहिले","other":"{0} घण्टा पहिले"}}},"day":{"displayName":"बार","relative":{"0":"आज","1":"भोली","-2":"अस्ति","-1":"हिजो"},"relativeTime":{"future":{"one":"{0} दिनमा","other":"{0} दिनमा"},"past":{"one":"{0} दिन पहिले","other":"{0} दिन पहिले"}}},"month":{"displayName":"महिना","relative":{"0":"यो महिना","1":"अर्को महिना","-1":"गएको महिना"},"relativeTime":{"future":{"one":"{0} महिनामा","other":"{0} महिनामा"},"past":{"one":"{0} महिना पहिले","other":"{0} महिना पहिले"}}},"year":{"displayName":"बर्ष","relative":{"0":"यो वर्ष","1":"अर्को वर्ष","-1":"पहिलो वर्ष"},"relativeTime":{"future":{"one":"{0} वर्षमा","other":"{0} वर्षमा"},"past":{"one":"{0} वर्ष अघि","other":"{0} वर्ष अघि"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nl","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Seconde","relative":{"0":"nu"},"relativeTime":{"future":{"one":"Over {0} seconde","other":"Over {0} seconden"},"past":{"one":"{0} seconde geleden","other":"{0} seconden geleden"}}},"minute":{"displayName":"Minuut","relativeTime":{"future":{"one":"Over {0} minuut","other":"Over {0} minuten"},"past":{"one":"{0} minuut geleden","other":"{0} minuten geleden"}}},"hour":{"displayName":"Uur","relativeTime":{"future":{"one":"Over {0} uur","other":"Over {0} uur"},"past":{"one":"{0} uur geleden","other":"{0} uur geleden"}}},"day":{"displayName":"Dag","relative":{"0":"vandaag","1":"morgen","2":"overmorgen","-2":"eergisteren","-1":"gisteren"},"relativeTime":{"future":{"one":"Over {0} dag","other":"Over {0} dagen"},"past":{"one":"{0} dag geleden","other":"{0} dagen geleden"}}},"month":{"displayName":"Maand","relative":{"0":"deze maand","1":"volgende maand","-1":"vorige maand"},"relativeTime":{"future":{"one":"Over {0} maand","other":"Over {0} maanden"},"past":{"one":"{0} maand geleden","other":"{0} maanden geleden"}}},"year":{"displayName":"Jaar","relative":{"0":"dit jaar","1":"volgend jaar","-1":"vorig jaar"},"relativeTime":{"future":{"one":"Over {0} jaar","other":"Over {0} jaar"},"past":{"one":"{0} jaar geleden","other":"{0} jaar geleden"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nn","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"sekund","relative":{"0":"now"},"relativeTime":{"future":{"one":"om {0} sekund","other":"om {0} sekunder"},"past":{"one":"for {0} sekund siden","other":"for {0} sekunder siden"}}},"minute":{"displayName":"minutt","relativeTime":{"future":{"one":"om {0} minutt","other":"om {0} minutter"},"past":{"one":"for {0} minutt siden","other":"for {0} minutter siden"}}},"hour":{"displayName":"time","relativeTime":{"future":{"one":"om {0} time","other":"om {0} timer"},"past":{"one":"for {0} time siden","other":"for {0} timer siden"}}},"day":{"displayName":"dag","relative":{"0":"i dag","1":"i morgon","2":"i overmorgon","-2":"i forgårs","-1":"i går"},"relativeTime":{"future":{"one":"om {0} døgn","other":"om {0} døgn"},"past":{"one":"for {0} døgn siden","other":"for {0} døgn siden"}}},"month":{"displayName":"månad","relative":{"0":"denne månad","1":"neste månad","-1":"forrige månad"},"relativeTime":{"future":{"one":"om {0} måned","other":"om {0} måneder"},"past":{"one":"for {0} måned siden","other":"for {0} måneder siden"}}},"year":{"displayName":"år","relative":{"0":"dette år","1":"neste år","-1":"i fjor"},"relativeTime":{"future":{"one":"om {0} år","other":"om {0} år"},"past":{"one":"for {0} år siden","other":"for {0} år siden"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nnh","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"fʉ̀ʼ nèm","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"lyɛ̌ʼ","relative":{"0":"lyɛ̌ʼɔɔn","1":"jǔɔ gẅie à ne ntóo","-1":"jǔɔ gẅie à ka tɔ̌g"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"ngùʼ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nr","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nso","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===Math.floor(n)&&n>=0&&n<=1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"nyn","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Obucweka\u002FEsekendi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Edakiika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Shaaha","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Eizooba","relative":{"0":"Erizooba","1":"Nyenkyakare","-1":"Nyomwabazyo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Omwezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Omwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"om","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"or","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"os","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Секунд","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Минут","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Сахат","relativeTime":{"future":{"one":"{0} сахаты фӕстӕ","other":"{0} сахаты фӕстӕ"},"past":{"one":"{0} сахаты размӕ","other":"{0} сахаты размӕ"}}},"day":{"displayName":"Бон","relative":{"0":"Абон","1":"Сом","2":"Иннӕбон","-2":"Ӕндӕрӕбон","-1":"Знон"},"relativeTime":{"future":{"one":"{0} боны фӕстӕ","other":"{0} боны фӕстӕ"},"past":{"one":"{0} бон раздӕр","other":"{0} боны размӕ"}}},"month":{"displayName":"Мӕй","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Аз","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"pa","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===Math.floor(n)&&n>=0&&n<=1)return"one";return"other";},"fields":{"second":{"displayName":"ਸਕਿੰਟ","relative":{"0":"ਹੁਣ"},"relativeTime":{"future":{"one":"{0} ਸਕਿੰਟ ਵਿਚ","other":"{0} ਸਕਿੰਟ ਵਿਚ"},"past":{"one":"{0} ਸਕਿੰਟ ਪਹਿਲਾਂ","other":"{0} ਸਕਿੰਟ ਪਹਿਲਾਂ"}}},"minute":{"displayName":"ਮਿੰਟ","relativeTime":{"future":{"one":"{0} ਮਿੰਟ ਵਿਚ","other":"{0} ਮਿੰਟ ਵਿਚ"},"past":{"one":"{0} ਮਿੰਟ ਪਹਿਲਾਂ","other":"{0} ਮਿੰਟ ਪਹਿਲਾਂ"}}},"hour":{"displayName":"ਘੰਟਾ","relativeTime":{"future":{"one":"{0} ਘੰਟੇ ਵਿਚ","other":"{0} ਘੰਟੇ ਵਿਚ"},"past":{"one":"{0} ਘੰਟਾ ਪਹਿਲਾਂ","other":"{0} ਘੰਟੇ ਪਹਿਲਾਂ"}}},"day":{"displayName":"ਦਿਨ","relative":{"0":"ਅੱਜ","1":"ਭਲਕੇ","-1":"ਲੰਘਿਆ ਕੱਲ"},"relativeTime":{"future":{"one":"{0} ਦਿਨ ਵਿਚ","other":"{0} ਦਿਨਾਂ ਵਿਚ"},"past":{"one":"{0} ਦਿਨ ਪਹਿਲਾਂ","other":"{0} ਦਿਨ ਪਹਿਲਾਂ"}}},"month":{"displayName":"ਮਹੀਨਾ","relative":{"0":"ਇਹ ਮਹੀਨਾ","1":"ਅਗਲਾ ਮਹੀਨਾ","-1":"ਪਿਛਲਾ ਮਹੀਨਾ"},"relativeTime":{"future":{"one":"{0} ਮਹੀਨੇ ਵਿਚ","other":"{0} ਮਹੀਨੇ ਵਿਚ"},"past":{"one":"{0} ਮਹੀਨੇ ਪਹਿਲਾਂ","other":"{0} ਮਹੀਨੇ ਪਹਿਲਾਂ"}}},"year":{"displayName":"ਸਾਲ","relative":{"0":"ਇਹ ਸਾਲ","1":"ਅਗਲਾ ਸਾਲ","-1":"ਪਿਛਲਾ ਸਾਲ"},"relativeTime":{"future":{"one":"{0} ਸਾਲ ਵਿਚ","other":"{0} ਸਾਲ ਵਿਚ"},"past":{"one":"{0} ਸਾਲ ਪਹਿਲਾਂ","other":"{0} ਸਾਲ ਪਹਿਲਾਂ"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"pl","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";if(v===0&&i%10===Math.floor(i%10)&&i%10>=2&&i%10<=4&&!(i%100>=12&&i%100<=14))return"few";if(v===0&&(i!==1)&&(i%10===Math.floor(i%10)&&i%10>=0&&i%10<=1||v===0&&(i%10===Math.floor(i%10)&&i%10>=5&&i%10<=9||v===0&&i%100===Math.floor(i%100)&&i%100>=12&&i%100<=14)))return"many";return"other";},"fields":{"second":{"displayName":"sekunda","relative":{"0":"teraz"},"relativeTime":{"future":{"one":"Za {0} sekundę","few":"Za {0} sekundy","many":"Za {0} sekund","other":"Za {0} sekundy"},"past":{"one":"{0} sekundę temu","few":"{0} sekundy temu","many":"{0} sekund temu","other":"{0} sekundy temu"}}},"minute":{"displayName":"minuta","relativeTime":{"future":{"one":"Za {0} minutę","few":"Za {0} minuty","many":"Za {0} minut","other":"Za {0} minuty"},"past":{"one":"{0} minutę temu","few":"{0} minuty temu","many":"{0} minut temu","other":"{0} minuty temu"}}},"hour":{"displayName":"godzina","relativeTime":{"future":{"one":"Za {0} godzinę","few":"Za {0} godziny","many":"Za {0} godzin","other":"Za {0} godziny"},"past":{"one":"{0} godzinę temu","few":"{0} godziny temu","many":"{0} godzin temu","other":"{0} godziny temu"}}},"day":{"displayName":"dzień","relative":{"0":"dzisiaj","1":"jutro","2":"pojutrze","-2":"przedwczoraj","-1":"wczoraj"},"relativeTime":{"future":{"one":"Za {0} dzień","few":"Za {0} dni","many":"Za {0} dni","other":"Za {0} dnia"},"past":{"one":"{0} dzień temu","few":"{0} dni temu","many":"{0} dni temu","other":"{0} dnia temu"}}},"month":{"displayName":"miesiąc","relative":{"0":"w tym miesiącu","1":"w przyszłym miesiącu","-1":"w zeszłym miesiącu"},"relativeTime":{"future":{"one":"Za {0} miesiąc","few":"Za {0} miesiące","many":"Za {0} miesięcy","other":"Za {0} miesiąca"},"past":{"one":"{0} miesiąc temu","few":"{0} miesiące temu","many":"{0} miesięcy temu","other":"{0} miesiąca temu"}}},"year":{"displayName":"rok","relative":{"0":"w tym roku","1":"w przyszłym roku","-1":"w zeszłym roku"},"relativeTime":{"future":{"one":"Za {0} rok","few":"Za {0} lata","many":"Za {0} lat","other":"Za {0} roku"},"past":{"one":"{0} rok temu","few":"{0} lata temu","many":"{0} lat temu","other":"{0} roku temu"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ps","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"pt","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length,t=parseInt(n.toString().replace(/^[^.]*\.?|0+$/g,""),10);n=Math.floor(n);if(i===1&&(v===0||i===0&&t===1))return"one";return"other";},"fields":{"second":{"displayName":"Segundo","relative":{"0":"agora"},"relativeTime":{"future":{"one":"Dentro de {0} segundo","other":"Dentro de {0} segundos"},"past":{"one":"Há {0} segundo","other":"Há {0} segundos"}}},"minute":{"displayName":"Minuto","relativeTime":{"future":{"one":"Dentro de {0} minuto","other":"Dentro de {0} minutos"},"past":{"one":"Há {0} minuto","other":"Há {0} minutos"}}},"hour":{"displayName":"Hora","relativeTime":{"future":{"one":"Dentro de {0} hora","other":"Dentro de {0} horas"},"past":{"one":"Há {0} hora","other":"Há {0} horas"}}},"day":{"displayName":"Dia","relative":{"0":"hoje","1":"amanhã","2":"depois de amanhã","-2":"anteontem","-1":"ontem"},"relativeTime":{"future":{"one":"Dentro de {0} dia","other":"Dentro de {0} dias"},"past":{"one":"Há {0} dia","other":"Há {0} dias"}}},"month":{"displayName":"Mês","relative":{"0":"este mês","1":"próximo mês","-1":"mês passado"},"relativeTime":{"future":{"one":"Dentro de {0} mês","other":"Dentro de {0} meses"},"past":{"one":"Há {0} mês","other":"Há {0} meses"}}},"year":{"displayName":"Ano","relative":{"0":"este ano","1":"próximo ano","-1":"ano passado"},"relativeTime":{"future":{"one":"Dentro de {0} ano","other":"Dentro de {0} anos"},"past":{"one":"Há {0} ano","other":"Há {0} anos"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"rm","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"secunda","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"minuta","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"ura","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Tag","relative":{"0":"oz","1":"damaun","2":"puschmaun","-2":"stersas","-1":"ier"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"mais","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"onn","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ro","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";if((v!==0)||n===0||(n!==1)&&n%100===Math.floor(n%100)&&n%100>=1&&n%100<=19)return"few";return"other";},"fields":{"second":{"displayName":"secundă","relative":{"0":"acum"},"relativeTime":{"future":{"one":"Peste {0} secundă","few":"Peste {0} secunde","other":"Peste {0} de secunde"},"past":{"one":"Acum {0} secundă","few":"Acum {0} secunde","other":"Acum {0} de secunde"}}},"minute":{"displayName":"minut","relativeTime":{"future":{"one":"Peste {0} minut","few":"Peste {0} minute","other":"Peste {0} de minute"},"past":{"one":"Acum {0} minut","few":"Acum {0} minute","other":"Acum {0} de minute"}}},"hour":{"displayName":"oră","relativeTime":{"future":{"one":"Peste {0} oră","few":"Peste {0} ore","other":"Peste {0} de ore"},"past":{"one":"Acum {0} oră","few":"Acum {0} ore","other":"Acum {0} de ore"}}},"day":{"displayName":"zi","relative":{"0":"azi","1":"mâine","2":"poimâine","-2":"alaltăieri","-1":"ieri"},"relativeTime":{"future":{"one":"Peste {0} zi","few":"Peste {0} zile","other":"Peste {0} de zile"},"past":{"one":"Acum {0} zi","few":"Acum {0} zile","other":"Acum {0} de zile"}}},"month":{"displayName":"lună","relative":{"0":"luna aceasta","1":"luna viitoare","-1":"luna trecută"},"relativeTime":{"future":{"one":"Peste {0} lună","few":"Peste {0} luni","other":"Peste {0} de luni"},"past":{"one":"Acum {0} lună","few":"Acum {0} luni","other":"Acum {0} de luni"}}},"year":{"displayName":"an","relative":{"0":"anul acesta","1":"anul viitor","-1":"anul trecut"},"relativeTime":{"future":{"one":"Peste {0} an","few":"Peste {0} ani","other":"Peste {0} de ani"},"past":{"one":"Acum {0} an","few":"Acum {0} ani","other":"Acum {0} de ani"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"rof","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Isaa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Mfiri","relative":{"0":"Linu","1":"Ng'ama","-1":"Hiyo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mweri","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Muaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ru","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(v===0&&i%10===1&&(i%100!==11))return"one";if(v===0&&i%10===Math.floor(i%10)&&i%10>=2&&i%10<=4&&!(i%100>=12&&i%100<=14))return"few";if(v===0&&(i%10===0||v===0&&(i%10===Math.floor(i%10)&&i%10>=5&&i%10<=9||v===0&&i%100===Math.floor(i%100)&&i%100>=11&&i%100<=14)))return"many";return"other";},"fields":{"second":{"displayName":"Секунда","relative":{"0":"сейчас"},"relativeTime":{"future":{"one":"Через {0} секунду","few":"Через {0} секунды","many":"Через {0} секунд","other":"Через {0} секунды"},"past":{"one":"{0} секунду назад","few":"{0} секунды назад","many":"{0} секунд назад","other":"{0} секунды назад"}}},"minute":{"displayName":"Минута","relativeTime":{"future":{"one":"Через {0} минуту","few":"Через {0} минуты","many":"Через {0} минут","other":"Через {0} минуты"},"past":{"one":"{0} минуту назад","few":"{0} минуты назад","many":"{0} минут назад","other":"{0} минуты назад"}}},"hour":{"displayName":"Час","relativeTime":{"future":{"one":"Через {0} час","few":"Через {0} часа","many":"Через {0} часов","other":"Через {0} часа"},"past":{"one":"{0} час назад","few":"{0} часа назад","many":"{0} часов назад","other":"{0} часа назад"}}},"day":{"displayName":"День","relative":{"0":"сегодня","1":"завтра","2":"послезавтра","-2":"позавчера","-1":"вчера"},"relativeTime":{"future":{"one":"Через {0} день","few":"Через {0} дня","many":"Через {0} дней","other":"Через {0} дня"},"past":{"one":"{0} день назад","few":"{0} дня назад","many":"{0} дней назад","other":"{0} дня назад"}}},"month":{"displayName":"Месяц","relative":{"0":"в этом месяце","1":"в следующем месяце","-1":"в прошлом месяце"},"relativeTime":{"future":{"one":"Через {0} месяц","few":"Через {0} месяца","many":"Через {0} месяцев","other":"Через {0} месяца"},"past":{"one":"{0} месяц назад","few":"{0} месяца назад","many":"{0} месяцев назад","other":"{0} месяца назад"}}},"year":{"displayName":"Год","relative":{"0":"в этому году","1":"в следующем году","-1":"в прошлом году"},"relativeTime":{"future":{"one":"Через {0} год","few":"Через {0} года","many":"Через {0} лет","other":"Через {0} года"},"past":{"one":"{0} год назад","few":"{0} года назад","many":"{0} лет назад","other":"{0} года назад"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"rwk","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakyika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Mfiri","relative":{"0":"Inu","1":"Ngama","-1":"Ukou"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mori","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Maka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sah","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Сөкүүндэ","relative":{"0":"now"},"relativeTime":{"future":{"other":"{0} сөкүүндэннэн"},"past":{"other":"{0} сөкүүндэ ынараа өттүгэр"}}},"minute":{"displayName":"Мүнүүтэ","relativeTime":{"future":{"other":"{0} мүнүүтэннэн"},"past":{"other":"{0} мүнүүтэ ынараа өттүгэр"}}},"hour":{"displayName":"Чаас","relativeTime":{"future":{"other":"{0} чааһынан"},"past":{"other":"{0} чаас ынараа өттүгэр"}}},"day":{"displayName":"Күн","relative":{"0":"Бүгүн","1":"Сарсын","2":"Өйүүн","-2":"Иллэрээ күн","-1":"Бэҕэһээ"},"relativeTime":{"future":{"other":"{0} күнүнэн"},"past":{"other":"{0} күн ынараа өттүгэр"}}},"month":{"displayName":"Ый","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"{0} ыйынан"},"past":{"other":"{0} ый ынараа өттүгэр"}}},"year":{"displayName":"Сыл","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"{0} сылынан"},"past":{"other":"{0} сыл ынараа өттүгэр"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"saq","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Isekondi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Idakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saai","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Mpari","relative":{"0":"Duo","1":"Taisere","-1":"Ng'ole"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Lapa","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Lari","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"se","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";if(n===2)return"two";return"other";},"fields":{"second":{"displayName":"sekunda","relative":{"0":"now"},"relativeTime":{"future":{"one":"{0} sekunda maŋŋilit","two":"{0} sekundda maŋŋilit","other":"{0} sekundda maŋŋilit"},"past":{"one":"{0} sekunda árat","two":"{0} sekundda árat","other":"{0} sekundda árat"}}},"minute":{"displayName":"minuhtta","relativeTime":{"future":{"one":"{0} minuhta maŋŋilit","two":"{0} minuhtta maŋŋilit","other":"{0} minuhtta maŋŋilit"},"past":{"one":"{0} minuhta árat","two":"{0} minuhtta árat","other":"{0} minuhtta árat"}}},"hour":{"displayName":"diibmu","relativeTime":{"future":{"one":"{0} diibmu maŋŋilit","two":"{0} diibmur maŋŋilit","other":"{0} diibmur maŋŋilit"},"past":{"one":"{0} diibmu árat","two":"{0} diibmur árat","other":"{0} diibmur árat"}}},"day":{"displayName":"beaivi","relative":{"0":"odne","1":"ihttin","2":"paijeelittáá","-2":"oovdebpeivvi","-1":"ikte"},"relativeTime":{"future":{"one":"{0} jándor maŋŋilit","two":"{0} jándor amaŋŋilit","other":"{0} jándora maŋŋilit"},"past":{"one":"{0} jándor árat","two":"{0} jándora árat","other":"{0} jándora árat"}}},"month":{"displayName":"mánnu","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"{0} mánotbadji maŋŋilit","two":"{0} mánotbadji maŋŋilit","other":"{0} mánotbadji maŋŋilit"},"past":{"one":"{0} mánotbadji árat","two":"{0} mánotbadji árat","other":"{0} mánotbadji árat"}}},"year":{"displayName":"jáhki","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"{0} jahki maŋŋilit","two":"{0} jahkki maŋŋilit","other":"{0} jahkki maŋŋilit"},"past":{"one":"{0} jahki árat","two":"{0} jahkki árat","other":"{0} jahkki árat"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"seh","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Segundo","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minuto","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hora","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ntsiku","relative":{"0":"Lero","1":"Manguana","-1":"Zuro"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mwezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Chaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ses","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Miti","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Miniti","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Guuru","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Zaari","relative":{"0":"Hõo","1":"Suba","-1":"Bi"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Handu","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Jiiri","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sg","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Nzîna ngbonga","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Ndurü ngbonga","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Ngbonga","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Lâ","relative":{"0":"Lâsô","1":"Kêkerêke","-1":"Bîrï"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Nze","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Ngû","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"shi","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";if(n===Math.floor(n)&&n>=2&&n<=10)return"few";return"other";},"fields":{"second":{"displayName":"ⵜⴰⵙⵉⵏⵜ","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"ⵜⵓⵙⴷⵉⴷⵜ","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"ⵜⴰⵙⵔⴰⴳⵜ","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"ⴰⵙⵙ","relative":{"0":"ⴰⵙⵙⴰ","1":"ⴰⵙⴽⴽⴰ","-1":"ⵉⴹⵍⵍⵉ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"ⴰⵢⵢⵓⵔ","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"ⴰⵙⴳⴳⵯⴰⵙ","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"si","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(n===0||n===1||i===0&&f===1)return"one";return"other";},"fields":{"second":{"displayName":"තත්පරය","relative":{"0":"දැන්"},"relativeTime":{"future":{"one":"තත්පර {0} කින්","other":"තත්පර {0} කින්"},"past":{"one":"තත්පර {0}කට පෙර","other":"තත්පර {0}කට පෙර"}}},"minute":{"displayName":"මිනිත්තුව","relativeTime":{"future":{"one":"මිනිත්තු {0} කින්","other":"මිනිත්තු {0} කින්"},"past":{"one":"මිනිත්තු {0}ට පෙර","other":"මිනිත්තු {0}ට පෙර"}}},"hour":{"displayName":"පැය","relativeTime":{"future":{"one":"පැය {0} කින්","other":"පැය {0} කින්"},"past":{"one":"පැය {0}ට පෙර","other":"පැය {0}ට පෙර"}}},"day":{"displayName":"දිනය","relative":{"0":"අද","1":"හෙට","2":"අනිද්දා","-2":"පෙරේදා","-1":"ඊයෙ"},"relativeTime":{"future":{"one":"දින {0}න්","other":"දින {0}න්"},"past":{"one":"දින {0} ට පෙර","other":"දින {0} ට පෙර"}}},"month":{"displayName":"මාසය","relative":{"0":"මෙම මාසය","1":"ඊළඟ මාසය","-1":"පසුගිය මාසය"},"relativeTime":{"future":{"one":"මාස {0}කින්","other":"මාස {0}කින්"},"past":{"one":"මාස {0}කට පෙර","other":"මාස {0}කට පෙර"}}},"year":{"displayName":"වර්ෂය","relative":{"0":"මෙම වසර","1":"ඊළඟ වසර","-1":"පසුගිය වසර"},"relativeTime":{"future":{"one":"වසර {0} කින්","other":"වසර {0} කින්"},"past":{"one":"වසර {0}ට පෙර","other":"වසර {0}ට පෙර"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sk","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";if(i===Math.floor(i)&&i>=2&&i<=4&&v===0)return"few";if((v!==0))return"many";return"other";},"fields":{"second":{"displayName":"Sekunda","relative":{"0":"teraz"},"relativeTime":{"future":{"one":"O {0} sekundu","few":"O {0} sekundy","many":"O {0} sekundy","other":"O {0} sekúnd"},"past":{"one":"Pred {0} sekundou","few":"Pred {0} sekundami","many":"Pred {0} sekundami","other":"Pred {0} sekundami"}}},"minute":{"displayName":"Minúta","relativeTime":{"future":{"one":"O {0} minútu","few":"O {0} minúty","many":"O {0} minúty","other":"O {0} minút"},"past":{"one":"Pred {0} minútou","few":"Pred {0} minútami","many":"Pred {0} minútami","other":"Pred {0} minútami"}}},"hour":{"displayName":"Hodina","relativeTime":{"future":{"one":"O {0} hodinu","few":"O {0} hodiny","many":"O {0} hodiny","other":"O {0} hodín"},"past":{"one":"Pred {0} hodinou","few":"Pred {0} hodinami","many":"Pred {0} hodinami","other":"Pred {0} hodinami"}}},"day":{"displayName":"Deň","relative":{"0":"Dnes","1":"Zajtra","2":"Pozajtra","-2":"Predvčerom","-1":"Včera"},"relativeTime":{"future":{"one":"O {0} deň","few":"O {0} dni","many":"O {0} dňa","other":"O {0} dní"},"past":{"one":"Pred {0} dňom","few":"Pred {0} dňami","many":"Pred {0} dňami","other":"Pred {0} dňami"}}},"month":{"displayName":"Mesiac","relative":{"0":"Tento mesiac","1":"Budúci mesiac","-1":"Posledný mesiac"},"relativeTime":{"future":{"one":"O {0} mesiac","few":"O {0} mesiace","many":"O {0} mesiaca","other":"O {0} mesiacov"},"past":{"one":"Pred {0} mesiacom","few":"Pred {0} mesiacmi","many":"Pred {0} mesiacmi","other":"Pred {0} mesiacmi"}}},"year":{"displayName":"Rok","relative":{"0":"Tento rok","1":"Budúci rok","-1":"Minulý rok"},"relativeTime":{"future":{"one":"O {0} rok","few":"O {0} roky","many":"O {0} roka","other":"O {0} rokov"},"past":{"one":"Pred {0} rokom","few":"Pred {0} rokmi","many":"Pred {0} rokmi","other":"Pred {0} rokmi"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sl","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(v===0&&i%100===1)return"one";if(v===0&&i%100===2)return"two";if(v===0&&(i%100===Math.floor(i%100)&&i%100>=3&&i%100<=4||(v!==0)))return"few";return"other";},"fields":{"second":{"displayName":"Sekunda","relative":{"0":"zdaj"},"relativeTime":{"future":{"one":"Čez {0} sekundo","two":"Čez {0} sekundi","few":"Čez {0} sekunde","other":"Čez {0} sekundi"},"past":{"one":"Pred {0} sekundo","two":"Pred {0} sekundama","few":"Pred {0} sekundami","other":"Pred {0} sekundami"}}},"minute":{"displayName":"Minuta","relativeTime":{"future":{"one":"Čez {0} min.","two":"Čez {0} min.","few":"Čez {0} min.","other":"Čez {0} min."},"past":{"one":"Pred {0} min.","two":"Pred {0} min.","few":"Pred {0} min.","other":"Pred {0} min."}}},"hour":{"displayName":"Ura","relativeTime":{"future":{"one":"Čez {0} h","two":"Čez {0} h","few":"Čez {0} h","other":"Čez {0} h"},"past":{"one":"Pred {0} h","two":"Pred {0} h","few":"Pred {0} h","other":"Pred {0} h"}}},"day":{"displayName":"Dan","relative":{"0":"Danes","1":"Jutri","2":"Pojutrišnjem","-2":"Predvčerajšnjim","-1":"Včeraj"},"relativeTime":{"future":{"one":"Čez {0} dan","two":"Čez {0} dni","few":"Čez {0} dni","other":"Čez {0} dni"},"past":{"one":"Pred {0} dnevom","two":"Pred {0} dnevoma","few":"Pred {0} dnevi","other":"Pred {0} dnevi"}}},"month":{"displayName":"Mesec","relative":{"0":"Ta mesec","1":"Naslednji mesec","-1":"Prejšnji mesec"},"relativeTime":{"future":{"one":"Čez {0} mesec","two":"Čez {0} meseca","few":"Čez {0} mesece","other":"Čez {0} mesecev"},"past":{"one":"Pred {0} mesecem","two":"Pred {0} meseci","few":"Pred {0} meseci","other":"Pred {0} meseci"}}},"year":{"displayName":"Leto","relative":{"0":"Letos","1":"Naslednje leto","-1":"Lani"},"relativeTime":{"future":{"one":"Čez {0} leto","two":"Čez {0} leti","few":"Čez {0} leta","other":"Čez {0} let"},"past":{"one":"Pred {0} letom","two":"Pred {0} leti","few":"Pred {0} leti","other":"Pred {0} leti"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sn","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekondi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Mineti","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Awa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Zuva","relative":{"0":"Nhasi","1":"Mangwana","-1":"Nezuro"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mwedzi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Gore","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"so","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Il biriqsi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Daqiiqad","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saacad","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Maalin","relative":{"0":"Maanta","1":"Berri","-1":"Shalay"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Bil","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Sanad","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sq","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"sekondë","relative":{"0":"tani"},"relativeTime":{"future":{"one":"pas {0} sekonde","other":"pas {0} sekondash"},"past":{"one":"para {0} sekonde","other":"para {0} sekondash"}}},"minute":{"displayName":"minutë","relativeTime":{"future":{"one":"pas {0} minute","other":"pas {0} minutash"},"past":{"one":"para {0} minute","other":"para {0} minutash"}}},"hour":{"displayName":"orë","relativeTime":{"future":{"one":"pas {0} ore","other":"pas {0} orësh"},"past":{"one":"para {0} ore","other":"para {0} orësh"}}},"day":{"displayName":"ditë","relative":{"0":"sot","1":"nesër","-1":"dje"},"relativeTime":{"future":{"one":"pas {0} dite","other":"pas {0} ditësh"},"past":{"one":"para {0} dite","other":"para {0} ditësh"}}},"month":{"displayName":"muaj","relative":{"0":"këtë muaj","1":"muajin e ardhshëm","-1":"muajin e kaluar"},"relativeTime":{"future":{"one":"pas {0} muaji","other":"pas {0} muajsh"},"past":{"one":"para {0} muaji","other":"para {0} muajsh"}}},"year":{"displayName":"vit","relative":{"0":"këtë vit","1":"vitin e ardhshëm","-1":"vitin e kaluar"},"relativeTime":{"future":{"one":"pas {0} viti","other":"pas {0} vjetësh"},"past":{"one":"para {0} viti","other":"para {0} vjetësh"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sr","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length,f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(v===0&&i%10===1&&((i%100!==11)||f%10===1&&(f%100!==11)))return"one";if(v===0&&i%10===Math.floor(i%10)&&i%10>=2&&i%10<=4&&(!(i%100>=12&&i%100<=14)||f%10===Math.floor(f%10)&&f%10>=2&&f%10<=4&&!(f%100>=12&&f%100<=14)))return"few";return"other";},"fields":{"second":{"displayName":"секунд","relative":{"0":"сада"},"relativeTime":{"future":{"one":"за {0} секунду","few":"за {0} секунде","other":"за {0} секунди"},"past":{"one":"пре {0} секунде","few":"пре {0} секунде","other":"пре {0} секунди"}}},"minute":{"displayName":"минут","relativeTime":{"future":{"one":"за {0} минут","few":"за {0} минута","other":"за {0} минута"},"past":{"one":"пре {0} минута","few":"пре {0} минута","other":"пре {0} минута"}}},"hour":{"displayName":"час","relativeTime":{"future":{"one":"за {0} сат","few":"за {0} сата","other":"за {0} сати"},"past":{"one":"пре {0} сата","few":"пре {0} сата","other":"пре {0} сати"}}},"day":{"displayName":"дан","relative":{"0":"данас","1":"сутра","2":"прекосутра","-2":"прекјуче","-1":"јуче"},"relativeTime":{"future":{"one":"за {0} дан","few":"за {0} дана","other":"за {0} дана"},"past":{"one":"пре {0} дана","few":"пре {0} дана","other":"пре {0} дана"}}},"month":{"displayName":"месец","relative":{"0":"Овог месеца","1":"Следећег месеца","-1":"Прошлог месеца"},"relativeTime":{"future":{"one":"за {0} месец","few":"за {0} месеца","other":"за {0} месеци"},"past":{"one":"пре {0} месеца","few":"пре {0} месеца","other":"пре {0} месеци"}}},"year":{"displayName":"година","relative":{"0":"Ове године","1":"Следеће године","-1":"Прошле године"},"relativeTime":{"future":{"one":"за {0} годину","few":"за {0} године","other":"за {0} година"},"past":{"one":"пре {0} године","few":"пре {0} године","other":"пре {0} година"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ss","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ssy","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"st","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sv","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Sekund","relative":{"0":"nu"},"relativeTime":{"future":{"one":"om {0} sekund","other":"om {0} sekunder"},"past":{"one":"för {0} sekund sedan","other":"för {0} sekunder sedan"}}},"minute":{"displayName":"Minut","relativeTime":{"future":{"one":"om {0} minut","other":"om {0} minuter"},"past":{"one":"för {0} minut sedan","other":"för {0} minuter sedan"}}},"hour":{"displayName":"timme","relativeTime":{"future":{"one":"om {0} timme","other":"om {0} timmar"},"past":{"one":"för {0} timme sedan","other":"för {0} timmar sedan"}}},"day":{"displayName":"Dag","relative":{"0":"i dag","1":"i morgon","2":"i övermorgon","-2":"i förrgår","-1":"i går"},"relativeTime":{"future":{"one":"om {0} dag","other":"om {0} dagar"},"past":{"one":"för {0} dag sedan","other":"för {0} dagar sedan"}}},"month":{"displayName":"Månad","relative":{"0":"denna månad","1":"nästa månad","-1":"förra månaden"},"relativeTime":{"future":{"one":"om {0} månad","other":"om {0} månader"},"past":{"one":"för {0} månad sedan","other":"för {0} månader sedan"}}},"year":{"displayName":"År","relative":{"0":"i år","1":"nästa år","-1":"i fjol"},"relativeTime":{"future":{"one":"om {0} år","other":"om {0} år"},"past":{"one":"för {0} år sedan","other":"för {0} år sedan"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"sw","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"sasa"},"relativeTime":{"future":{"one":"Baada ya sekunde {0}","other":"Baada ya sekunde {0}"},"past":{"one":"Sekunde {0} iliyopita","other":"Sekunde {0} zilizopita"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"one":"Baada ya dakika {0}","other":"Baada ya dakika {0}"},"past":{"one":"Dakika {0} iliyopita","other":"Dakika {0} zilizopita"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"one":"Baada ya saa {0}","other":"Baada ya saa {0}"},"past":{"one":"Saa {0} iliyopita","other":"Saa {0} zilizopita"}}},"day":{"displayName":"Siku","relative":{"0":"leo","1":"kesho","2":"kesho kutwa","-2":"juzi","-1":"jana"},"relativeTime":{"future":{"one":"Baada ya siku {0}","other":"Baada ya siku {0}"},"past":{"one":"Siku {0} iliyopita","other":"Siku {0} zilizopita"}}},"month":{"displayName":"Mwezi","relative":{"0":"mwezi huu","1":"mwezi ujao","-1":"mwezi uliopita"},"relativeTime":{"future":{"one":"Baada ya mwezi {0}","other":"Baada ya miezi {0}"},"past":{"one":"Miezi {0} iliyopita","other":"Miezi {0} iliyopita"}}},"year":{"displayName":"Mwaka","relative":{"0":"mwaka huu","1":"mwaka ujao","-1":"mwaka uliopita"},"relativeTime":{"future":{"one":"Baada ya mwaka {0}","other":"Baada ya miaka {0}"},"past":{"one":"Mwaka {0} uliopita","other":"Miaka {0} iliyopita"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ta","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"வினாடி","relative":{"0":"இப்போது"},"relativeTime":{"future":{"one":"{0} வினாடியில்","other":"{0} விநாடிகளில்"},"past":{"one":"{0} வினாடிக்கு முன்","other":"{0} வினாடிக்கு முன்"}}},"minute":{"displayName":"நிமிடம்","relativeTime":{"future":{"one":"{0} நிமிடத்தில்","other":"{0} நிமிடங்களில்"},"past":{"one":"{0} நிமிடத்திற்கு முன்","other":"{0} நிமிடங்களுக்கு முன்"}}},"hour":{"displayName":"மணி","relativeTime":{"future":{"one":"{0} மணிநேரத்தில்","other":"{0} மணிநேரத்தில்"},"past":{"one":"{0} மணிநேரம் முன்","other":"{0} மணிநேரம் முன்"}}},"day":{"displayName":"நாள்","relative":{"0":"இன்று","1":"நாளை","2":"நாளை மறுநாள்","-2":"நேற்று முன் தினம்","-1":"நேற்று"},"relativeTime":{"future":{"one":"{0} நாளில்","other":"{0} நாட்களில்"},"past":{"one":"{0} நாளுக்கு முன்","other":"{0} நாட்களுக்கு முன்"}}},"month":{"displayName":"மாதம்","relative":{"0":"இந்த மாதம்","1":"அடுத்த மாதம்","-1":"கடந்த மாதம்"},"relativeTime":{"future":{"one":"{0} மாதத்தில்","other":"{0} மாதங்களில்"},"past":{"one":"{0} மாதத்துக்கு முன்","other":"{0} மாதங்களுக்கு முன்"}}},"year":{"displayName":"ஆண்டு","relative":{"0":"இந்த ஆண்டு","1":"அடுத்த ஆண்டு","-1":"கடந்த ஆண்டு"},"relativeTime":{"future":{"one":"{0} ஆண்டில்","other":"{0} ஆண்டுகளில்"},"past":{"one":"{0} ஆண்டிற்கு முன்","other":"{0} ஆண்டுகளுக்கு முன்"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"te","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"క్షణం","relative":{"0":"ప్రస్తుతం"},"relativeTime":{"future":{"one":"{0} సెకన్‌లో","other":"{0} సెకన్లలో"},"past":{"one":"{0} సెకను క్రితం","other":"{0} సెకన్ల క్రితం"}}},"minute":{"displayName":"నిమిషము","relativeTime":{"future":{"one":"{0} నిమిషంలో","other":"{0} నిమిషాల్లో"},"past":{"one":"{0} నిమిషం క్రితం","other":"{0} నిమిషాల క్రితం"}}},"hour":{"displayName":"గంట","relativeTime":{"future":{"one":"{0} గంటలో","other":"{0} గంటల్లో"},"past":{"one":"{0} గంట క్రితం","other":"{0} గంటల క్రితం"}}},"day":{"displayName":"దినం","relative":{"0":"ఈ రోజు","1":"రేపు","2":"ఎల్లుండి","-2":"మొన్న","-1":"నిన్న"},"relativeTime":{"future":{"one":"{0} రోజులో","other":"{0} రోజుల్లో"},"past":{"one":"{0} రోజు క్రితం","other":"{0} రోజుల క్రితం"}}},"month":{"displayName":"నెల","relative":{"0":"ఈ నెల","1":"తదుపరి నెల","-1":"గత నెల"},"relativeTime":{"future":{"one":"{0} నెలలో","other":"{0} నెలల్లో"},"past":{"one":"{0} నెల క్రితం","other":"{0} నెలల క్రితం"}}},"year":{"displayName":"సంవత్సరం","relative":{"0":"ఈ సంవత్సరం","1":"తదుపరి సంవత్సరం","-1":"గత సంవత్సరం"},"relativeTime":{"future":{"one":"{0} సంవత్సరంలో","other":"{0} సంవత్సరాల్లో"},"past":{"one":"{0} సంవత్సరం క్రితం","other":"{0} సంవత్సరాల క్రితం"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"teo","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Isekonde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Idakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Esaa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Aparan","relative":{"0":"Lolo","1":"Moi","-1":"Jaan"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Elap","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Ekan","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"th","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"วินาที","relative":{"0":"ขณะนี้"},"relativeTime":{"future":{"other":"ในอีก {0} วินาที"},"past":{"other":"{0} วินาทีที่ผ่านมา"}}},"minute":{"displayName":"นาที","relativeTime":{"future":{"other":"ในอีก {0} นาที"},"past":{"other":"{0} นาทีที่ผ่านมา"}}},"hour":{"displayName":"ชั่วโมง","relativeTime":{"future":{"other":"ในอีก {0} ชั่วโมง"},"past":{"other":"{0} ชั่วโมงที่ผ่านมา"}}},"day":{"displayName":"วัน","relative":{"0":"วันนี้","1":"พรุ่งนี้","2":"มะรืนนี้","-2":"เมื่อวานซืน","-1":"เมื่อวาน"},"relativeTime":{"future":{"other":"ในอีก {0} วัน"},"past":{"other":"{0} วันที่ผ่านมา"}}},"month":{"displayName":"เดือน","relative":{"0":"เดือนนี้","1":"เดือนหน้า","-1":"เดือนที่แล้ว"},"relativeTime":{"future":{"other":"ในอีก {0} เดือน"},"past":{"other":"{0} เดือนที่ผ่านมา"}}},"year":{"displayName":"ปี","relative":{"0":"ปีนี้","1":"ปีหน้า","-1":"ปีที่แล้ว"},"relativeTime":{"future":{"other":"ในอีก {0} ปี"},"past":{"other":"{0} ปีที่แล้ว"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ti","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===Math.floor(n)&&n>=0&&n<=1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"tig","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"tn","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"to","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"sekoni","relative":{"0":"taimiʻni"},"relativeTime":{"future":{"other":"ʻi he sekoni ʻe {0}"},"past":{"other":"sekoni ʻe {0} kuoʻosi"}}},"minute":{"displayName":"miniti","relativeTime":{"future":{"other":"ʻi he miniti ʻe {0}"},"past":{"other":"miniti ʻe {0} kuoʻosi"}}},"hour":{"displayName":"houa","relativeTime":{"future":{"other":"ʻi he houa ʻe {0}"},"past":{"other":"houa ʻe {0} kuoʻosi"}}},"day":{"displayName":"ʻaho","relative":{"0":"ʻaho⸍ni","1":"ʻapongipongi","2":"ʻahepongipongi","-2":"ʻaneheafi","-1":"ʻaneafi"},"relativeTime":{"future":{"other":"ʻi he ʻaho ʻe {0}"},"past":{"other":"ʻaho ʻe {0} kuoʻosi"}}},"month":{"displayName":"māhina","relative":{"0":"māhina⸍ni","1":"māhina kahaʻu","-1":"māhina kuoʻosi"},"relativeTime":{"future":{"other":"ʻi he māhina ʻe {0}"},"past":{"other":"māhina ʻe {0} kuoʻosi"}}},"year":{"displayName":"taʻu","relative":{"0":"taʻu⸍ni","1":"taʻu kahaʻu","-1":"taʻu kuoʻosi"},"relativeTime":{"future":{"other":"ʻi he taʻu ʻe {0}"},"past":{"other":"taʻu ʻe {0} kuo hili"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"tr","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Saniye","relative":{"0":"şimdi"},"relativeTime":{"future":{"one":"{0} saniye sonra","other":"{0} saniye sonra"},"past":{"one":"{0} saniye önce","other":"{0} saniye önce"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"one":"{0} dakika sonra","other":"{0} dakika sonra"},"past":{"one":"{0} dakika önce","other":"{0} dakika önce"}}},"hour":{"displayName":"Saat","relativeTime":{"future":{"one":"{0} saat sonra","other":"{0} saat sonra"},"past":{"one":"{0} saat önce","other":"{0} saat önce"}}},"day":{"displayName":"Gün","relative":{"0":"bugün","1":"yarın","2":"öbür gün","-2":"evvelsi gün","-1":"dün"},"relativeTime":{"future":{"one":"{0} gün sonra","other":"{0} gün sonra"},"past":{"one":"{0} gün önce","other":"{0} gün önce"}}},"month":{"displayName":"Ay","relative":{"0":"bu ay","1":"gelecek ay","-1":"geçen ay"},"relativeTime":{"future":{"one":"{0} ay sonra","other":"{0} ay sonra"},"past":{"one":"{0} ay önce","other":"{0} ay önce"}}},"year":{"displayName":"Yıl","relative":{"0":"bu yıl","1":"gelecek yıl","-1":"geçen yıl"},"relativeTime":{"future":{"one":"{0} yıl sonra","other":"{0} yıl sonra"},"past":{"one":"{0} yıl önce","other":"{0} yıl önce"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ts","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"tzm","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===Math.floor(n)&&n>=0&&n<=1||n===Math.floor(n)&&n>=11&&n<=99)return"one";return"other";},"fields":{"second":{"displayName":"Tusnat","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Tusdat","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Tasragt","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ass","relative":{"0":"Assa","1":"Asekka","-1":"Assenaṭ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Ayur","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Asseggas","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ug","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"سېكۇنت","relative":{"0":"now"},"relativeTime":{"future":{"one":"{0} سېكۇنتتىن كېيىن","other":"{0} سېكۇنتتىن كېيىن"},"past":{"one":"{0} سېكۇنت ئىلگىرى","other":"{0} سېكۇنت ئىلگىرى"}}},"minute":{"displayName":"مىنۇت","relativeTime":{"future":{"one":"{0} مىنۇتتىن كېيىن","other":"{0} مىنۇتتىن كېيىن"},"past":{"one":"{0} مىنۇت ئىلگىرى","other":"{0} مىنۇت ئىلگىرى"}}},"hour":{"displayName":"سائەت","relativeTime":{"future":{"one":"{0} سائەتتىن كېيىن","other":"{0} سائەتتىن كېيىن"},"past":{"one":"{0} سائەت ئىلگىرى","other":"{0} سائەت ئىلگىرى"}}},"day":{"displayName":"كۈن","relative":{"0":"بۈگۈن","1":"ئەتە","-1":"تۈنۈگۈن"},"relativeTime":{"future":{"one":"{0} كۈندىن كېيىن","other":"{0} كۈندىن كېيىن"},"past":{"one":"{0} كۈن ئىلگىرى","other":"{0} كۈن ئىلگىرى"}}},"month":{"displayName":"ئاي","relative":{"0":"بۇ ئاي","1":"كېلەر ئاي","-1":"ئۆتكەن ئاي"},"relativeTime":{"future":{"one":"{0} ئايدىن كېيىن","other":"{0} ئايدىن كېيىن"},"past":{"one":"{0} ئاي ئىلگىرى","other":"{0} ئاي ئىلگىرى"}}},"year":{"displayName":"يىل","relative":{"0":"بۇ يىل","1":"كېلەر يىل","-1":"ئۆتكەن يىل"},"relativeTime":{"future":{"one":"{0} يىلدىن كېيىن","other":"{0} يىلدىن كېيىن"},"past":{"one":"{0} يىل ئىلگىرى","other":"{0} يىل ئىلگىرى"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"uk","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(v===0&&i%10===1&&(i%100!==11))return"one";if(v===0&&i%10===Math.floor(i%10)&&i%10>=2&&i%10<=4&&!(i%100>=12&&i%100<=14))return"few";if(v===0&&(i%10===0||v===0&&(i%10===Math.floor(i%10)&&i%10>=5&&i%10<=9||v===0&&i%100===Math.floor(i%100)&&i%100>=11&&i%100<=14)))return"many";return"other";},"fields":{"second":{"displayName":"Секунда","relative":{"0":"зараз"},"relativeTime":{"future":{"one":"Через {0} секунду","few":"Через {0} секунди","many":"Через {0} секунд","other":"Через {0} секунди"},"past":{"one":"{0} секунду тому","few":"{0} секунди тому","many":"{0} секунд тому","other":"{0} секунди тому"}}},"minute":{"displayName":"Хвилина","relativeTime":{"future":{"one":"Через {0} хвилину","few":"Через {0} хвилини","many":"Через {0} хвилин","other":"Через {0} хвилини"},"past":{"one":"{0} хвилину тому","few":"{0} хвилини тому","many":"{0} хвилин тому","other":"{0} хвилини тому"}}},"hour":{"displayName":"Година","relativeTime":{"future":{"one":"Через {0} годину","few":"Через {0} години","many":"Через {0} годин","other":"Через {0} години"},"past":{"one":"{0} годину тому","few":"{0} години тому","many":"{0} годин тому","other":"{0} години тому"}}},"day":{"displayName":"День","relative":{"0":"сьогодні","1":"завтра","2":"післязавтра","-2":"позавчора","-1":"учора"},"relativeTime":{"future":{"one":"Через {0} день","few":"Через {0} дні","many":"Через {0} днів","other":"Через {0} дня"},"past":{"one":"{0} день тому","few":"{0} дні тому","many":"{0} днів тому","other":"{0} дня тому"}}},"month":{"displayName":"Місяць","relative":{"0":"цього місяця","1":"наступного місяця","-1":"минулого місяця"},"relativeTime":{"future":{"one":"Через {0} місяць","few":"Через {0} місяці","many":"Через {0} місяців","other":"Через {0} місяця"},"past":{"one":"{0} місяць тому","few":"{0} місяці тому","many":"{0} місяців тому","other":"{0} місяця тому"}}},"year":{"displayName":"Рік","relative":{"0":"цього року","1":"наступного року","-1":"минулого року"},"relativeTime":{"future":{"one":"Через {0} рік","few":"Через {0} роки","many":"Через {0} років","other":"Через {0} року"},"past":{"one":"{0} рік тому","few":"{0} роки тому","many":"{0} років тому","other":"{0} року тому"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ur","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n)),v=n.toString().replace(/^[^.]*\.?/,"").length;n=Math.floor(n);if(i===1&&v===0)return"one";return"other";},"fields":{"second":{"displayName":"سیکنڈ","relative":{"0":"اب"},"relativeTime":{"future":{"one":"{0} سیکنڈ میں","other":"{0} سیکنڈ میں"},"past":{"one":"{0} سیکنڈ پہلے","other":"{0} سیکنڈ پہلے"}}},"minute":{"displayName":"منٹ","relativeTime":{"future":{"one":"{0} منٹ میں","other":"{0} منٹ میں"},"past":{"one":"{0} منٹ پہلے","other":"{0} منٹ پہلے"}}},"hour":{"displayName":"گھنٹہ","relativeTime":{"future":{"one":"{0} گھنٹہ میں","other":"{0} گھنٹے میں"},"past":{"one":"{0} گھنٹہ پہلے","other":"{0} گھنٹے پہلے"}}},"day":{"displayName":"دن","relative":{"0":"آج","1":"آئندہ کل","2":"آنے والا پرسوں","-2":"گزشتہ پرسوں","-1":"گزشتہ کل"},"relativeTime":{"future":{"one":"{0} دن میں","other":"{0} دن میں"},"past":{"one":"{0} دن پہلے","other":"{0} دن پہلے"}}},"month":{"displayName":"مہینہ","relative":{"0":"اس مہینہ","1":"اگلے مہینہ","-1":"پچھلے مہینہ"},"relativeTime":{"future":{"one":"{0} مہینہ میں","other":"{0} مہینے میں"},"past":{"one":"{0} مہینہ پہلے","other":"{0} مہینے پہلے"}}},"year":{"displayName":"سال","relative":{"0":"اس سال","1":"اگلے سال","-1":"پچھلے سال"},"relativeTime":{"future":{"one":"{0} سال میں","other":"{0} سال میں"},"past":{"one":"{0} سال پہلے","other":"{0} سال پہلے"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"uz","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Soniya","relative":{"0":"hozir"},"relativeTime":{"future":{"one":"{0} soniyadan soʻng","other":"{0} soniyadan soʻng"},"past":{"one":"{0} soniya oldin","other":"{0} soniya oldin"}}},"minute":{"displayName":"Daqiqa","relativeTime":{"future":{"one":"{0} daqiqadan soʻng","other":"{0} daqiqadan soʻng"},"past":{"one":"{0} daqiqa oldin","other":"{0} daqiqa oldin"}}},"hour":{"displayName":"Soat","relativeTime":{"future":{"one":"{0} soatdan soʻng","other":"{0} soatdan soʻng"},"past":{"one":"{0} soat oldin","other":"{0} soat oldin"}}},"day":{"displayName":"Kun","relative":{"0":"bugun","1":"ertaga","-1":"kecha"},"relativeTime":{"future":{"one":"{0} kundan soʻng","other":"{0} kundan soʻng"},"past":{"one":"{0} kun oldin","other":"{0} kun oldin"}}},"month":{"displayName":"Oy","relative":{"0":"bu oy","1":"keyingi oy","-1":"oʻtgan oy"},"relativeTime":{"future":{"one":"{0} oydan soʻng","other":"{0} oydan soʻng"},"past":{"one":"{0} oy avval","other":"{0} oy avval"}}},"year":{"displayName":"Yil","relative":{"0":"bu yil","1":"keyingi yil","-1":"oʻtgan yil"},"relativeTime":{"future":{"one":"{0} yildan soʻng","other":"{0} yildan soʻng"},"past":{"one":"{0} yil avval","other":"{0} yil avval"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"ve","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"vi","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Giây","relative":{"0":"bây giờ"},"relativeTime":{"future":{"other":"Trong {0} giây nữa"},"past":{"other":"{0} giây trước"}}},"minute":{"displayName":"Phút","relativeTime":{"future":{"other":"Trong {0} phút nữa"},"past":{"other":"{0} phút trước"}}},"hour":{"displayName":"Giờ","relativeTime":{"future":{"other":"Trong {0} giờ nữa"},"past":{"other":"{0} giờ trước"}}},"day":{"displayName":"Ngày","relative":{"0":"Hôm nay","1":"Ngày mai","2":"Ngày kia","-2":"Hôm kia","-1":"Hôm qua"},"relativeTime":{"future":{"other":"Trong {0} ngày nữa"},"past":{"other":"{0} ngày trước"}}},"month":{"displayName":"Tháng","relative":{"0":"tháng này","1":"tháng sau","-1":"tháng trước"},"relativeTime":{"future":{"other":"Trong {0} tháng nữa"},"past":{"other":"{0} tháng trước"}}},"year":{"displayName":"Năm","relative":{"0":"năm nay","1":"năm sau","-1":"năm ngoái"},"relativeTime":{"future":{"other":"Trong {0} năm nữa"},"past":{"other":"{0} năm trước"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"vo","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"sekun","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"minut","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"düp","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Tag","relative":{"0":"adelo","1":"odelo","2":"udelo","-2":"edelo","-1":"ädelo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"mul","relative":{"0":"amulo","1":"omulo","-1":"ämulo"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"yel","relative":{"0":"ayelo","1":"oyelo","-1":"äyelo"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"vun","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Dakyika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Mfiri","relative":{"0":"Inu","1":"Ngama","-1":"Ukou"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Mori","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Maka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"wae","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Sekunda","relative":{"0":"now"},"relativeTime":{"future":{"one":"i {0} sekund","other":"i {0} sekunde"},"past":{"one":"vor {0} sekund","other":"vor {0} sekunde"}}},"minute":{"displayName":"Mínütta","relativeTime":{"future":{"one":"i {0} minüta","other":"i {0} minüte"},"past":{"one":"vor {0} minüta","other":"vor {0} minüte"}}},"hour":{"displayName":"Schtund","relativeTime":{"future":{"one":"i {0} stund","other":"i {0} stunde"},"past":{"one":"vor {0} stund","other":"vor {0} stunde"}}},"day":{"displayName":"Tag","relative":{"0":"Hitte","1":"Móre","2":"Ubermóre","-2":"Vorgešter","-1":"Gešter"},"relativeTime":{"future":{"one":"i {0} tag","other":"i {0} täg"},"past":{"one":"vor {0} tag","other":"vor {0} täg"}}},"month":{"displayName":"Mánet","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"one":"I {0} mánet","other":"I {0} mánet"},"past":{"one":"vor {0} mánet","other":"vor {0} mánet"}}},"year":{"displayName":"Jár","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"one":"I {0} jár","other":"I {0} jár"},"past":{"one":"vor {0} jár","other":"cor {0} jár"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"xh","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"xog","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";},"fields":{"second":{"displayName":"Obutikitiki","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Edakiika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"Essawa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Olunaku","relative":{"0":"Olwaleelo (leelo)","1":"Enkyo","-1":"Edho"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Omwezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Omwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"yo","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"Ìsẹ́jú Ààyá","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}},"minute":{"displayName":"Ìsẹ́jú","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"hour":{"displayName":"wákàtí","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"day":{"displayName":"Ọjọ́","relative":{"0":"Òní","1":"Ọ̀la","2":"òtúùnla","-2":"íjẹta","-1":"Àná"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"month":{"displayName":"Osù","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"year":{"displayName":"Ọdún","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"zh","pluralRuleFunction":function (n) {return"other";},"fields":{"second":{"displayName":"秒钟","relative":{"0":"现在"},"relativeTime":{"future":{"other":"{0}秒钟后"},"past":{"other":"{0}秒钟前"}}},"minute":{"displayName":"分钟","relativeTime":{"future":{"other":"{0}分钟后"},"past":{"other":"{0}分钟前"}}},"hour":{"displayName":"小时","relativeTime":{"future":{"other":"{0}小时后"},"past":{"other":"{0}小时前"}}},"day":{"displayName":"日","relative":{"0":"今天","1":"明天","2":"后天","-2":"前天","-1":"昨天"},"relativeTime":{"future":{"other":"{0}天后"},"past":{"other":"{0}天前"}}},"month":{"displayName":"月","relative":{"0":"本月","1":"下个月","-1":"上个月"},"relativeTime":{"future":{"other":"{0}个月后"},"past":{"other":"{0}个月前"}}},"year":{"displayName":"年","relative":{"0":"今年","1":"明年","-1":"去年"},"relativeTime":{"future":{"other":"{0}年后"},"past":{"other":"{0}年前"}}}}}); ReactIntlMixin.__addLocaleData({"locale":"zu","pluralRuleFunction":function (n) {var i=Math.floor(Math.abs(n));n=Math.floor(n);if(i===0||n===1)return"one";return"other";},"fields":{"second":{"displayName":"Isekhondi","relative":{"0":"manje"},"relativeTime":{"future":{"one":"Kusekhondi elingu-{0}","other":"Kumasekhondi angu-{0}"},"past":{"one":"isekhondi elingu-{0} eledlule","other":"amasekhondi angu-{0} adlule"}}},"minute":{"displayName":"Iminithi","relativeTime":{"future":{"one":"Kumunithi engu-{0}","other":"Emaminithini angu-{0}"},"past":{"one":"eminithini elingu-{0} eledlule","other":"amaminithi angu-{0} adlule"}}},"hour":{"displayName":"Ihora","relativeTime":{"future":{"one":"Ehoreni elingu-{0}","other":"Emahoreni angu-{0}"},"past":{"one":"ehoreni eligu-{0} eledluli","other":"emahoreni angu-{0} edlule"}}},"day":{"displayName":"Usuku","relative":{"0":"namhlanje","1":"kusasa","2":"Usuku olulandela olakusasa","-2":"Usuku olwandulela olwayizolo","-1":"izolo"},"relativeTime":{"future":{"one":"Osukwini olungu-{0}","other":"Ezinsukwini ezingu-{0}"},"past":{"one":"osukwini olungu-{0} olwedlule","other":"ezinsukwini ezingu-{0} ezedlule."}}},"month":{"displayName":"Inyanga","relative":{"0":"le nyanga","1":"inyanga ezayo","-1":"inyanga edlule"},"relativeTime":{"future":{"one":"Enyangeni engu-{0}","other":"Ezinyangeni ezingu-{0}"},"past":{"one":"enyangeni engu-{0} eyedlule","other":"ezinyangeni ezingu-{0} ezedlule"}}},"year":{"displayName":"Unyaka","relative":{"0":"kulo nyaka","1":"unyaka ozayo","-1":"onyakeni odlule"},"relativeTime":{"future":{"one":"Onyakeni ongu-{0}","other":"Eminyakeni engu-{0}"},"past":{"one":"enyakeni ongu-{0} owedlule","other":"iminyaka engu-{0} eyedlule"}}}}});
/*! jQuery v@1.8.0 jquery.com | jquery.org/license */ (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(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 cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,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(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.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):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.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=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",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){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);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{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._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,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.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,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.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,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.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):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.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;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),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){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.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]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(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(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);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=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.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){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.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){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),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(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),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)}}),p.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){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=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}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={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,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(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){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.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=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[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","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,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||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),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):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
!function(global, factory) { 'object' == typeof exports && 'undefined' != typeof module ? module.exports = factory() : 'function' == typeof define && define.amd ? define(factory) : global.preact = factory(); }(this, function() { 'use strict'; function VNode(nodeName, attributes, children) { this.nodeName = nodeName; this.attributes = attributes; this.children = children; } function extend(obj, props) { for (var i in props) if (hasOwnProperty.call(props, i)) obj[i] = props[i]; return obj; } function clone(obj) { var out = {}; for (var i in obj) out[i] = obj[i]; return out; } function memoize(fn, mem) { mem = mem || {}; return function(k) { return hasOwnProperty.call(mem, k) ? mem[k] : mem[k] = fn(k); }; } function delve(obj, key) { for (var p = key.split('.'), i = 0; i < p.length && obj; i++) obj = obj[p[i]]; return obj; } function toArray(obj) { var arr = [], i = obj.length; for (;i--; ) arr[i] = obj[i]; return arr; } function styleObjToCss(s) { var str = ''; for (var prop in s) { var val = s[prop]; if (!empty(val)) { if (str) str += ' '; str += jsToCss(prop); str += ': '; str += val; if ('number' == typeof val && !NON_DIMENSION_PROPS[prop]) str += 'px'; str += ';'; } } return str; } function hashToClassName(c) { var str = ''; for (var prop in c) if (c[prop]) { if (str) str += ' '; str += prop; } return str; } function normalize(obj, prop, fn) { var v = obj[prop]; if (v && !isString(v)) obj[prop] = fn(v); } function optionsHook(name, a, b) { return hook(options, name, a, b); } function hook(obj, name, a, b, c) { if (obj[name]) return obj[name](a, b, c); else ; } function deepHook(obj, type) { do hook(obj, type); while (obj = obj._component); } function h(nodeName, attributes) { var len = arguments.length, children = void 0, arr = void 0, lastSimple = void 0; if (len > 2) { children = []; for (var i = 2; len > i; i++) { var _p = arguments[i]; if (!falsey(_p)) { if (_p.join) arr = _p; else { arr = SHARED_TEMP_ARRAY; arr[0] = _p; } for (var j = 0; j < arr.length; j++) { var child = arr[j], simple = !(falsey(child) || child instanceof VNode); if (simple) child = String(child); if (simple && lastSimple) children[children.length - 1] += child; else if (!falsey(child)) children.push(child); lastSimple = simple; } } else ; } } if (attributes && attributes.children) delete attributes.children; var p = new VNode(nodeName, attributes || void 0, children || void 0); optionsHook('vnode', p); return p; } function createLinkedState(component, key, eventPath) { var path = key.split('.'), p0 = path[0], len = path.length; return function(e) { var _component$setState; var t = this, s = component.state, obj = s, v = void 0, i = void 0; if (isString(eventPath)) { v = delve(e, eventPath); if (empty(v) && (t = t._component)) v = delve(t, eventPath); } else v = (t.nodeName + t.type).match(/^input(checkbox|radio)$/i) ? t.checked : t.value; if (isFunction(v)) v = v.call(t); if (len > 1) { for (i = 0; len - 1 > i; i++) obj = obj[path[i]] || (obj[path[i]] = {}); obj[path[i]] = v; v = s[p0]; } component.setState((_component$setState = {}, _component$setState[p0] = v, _component$setState)); }; } function enqueueRender(component) { if (1 === items.push(component)) (options.debounceRendering || setImmediate)(rerender); } function rerender() { if (items.length) { var currentItems = items, p = void 0; items = itemsOffline; itemsOffline = currentItems; for (;p = currentItems.pop(); ) if (p._dirty) renderComponent(p); } } function isFunctionalComponent(_ref) { var nodeName = _ref.nodeName; return isFunction(nodeName) && !(nodeName.prototype && nodeName.prototype.render); } function buildFunctionalComponent(vnode, context) { return vnode.nodeName(getNodeProps(vnode), context || EMPTY) || EMPTY_BASE; } function ensureNodeData(node) { return node[ATTR_KEY] || (node[ATTR_KEY] = {}); } function getNodeType(node) { return node.nodeType; } function appendChildren(parent, children) { var len = children.length, many = len > 2, into = many ? document.createDocumentFragment() : parent; for (var i = 0; len > i; i++) into.appendChild(children[i]); if (many) parent.appendChild(into); } function getAccessor(node, name, value, cache) { if ('type' !== name && 'style' !== name && name in node) return node[name]; var attrs = node[ATTR_KEY]; if (cache !== !1 && attrs && hasOwnProperty.call(attrs, name)) return attrs[name]; if ('class' === name) return node.className; if ('style' === name) return node.style.cssText; else return value; } function setAccessor(node, name, value) { if ('class' === name) node.className = value || ''; else if ('style' === name) node.style.cssText = value || ''; else if ('dangerouslySetInnerHTML' === name) { if (value && value.__html) node.innerHTML = value.__html; } else if ('key' === name || name in node && 'type' !== name) { node[name] = value; if (falsey(value)) node.removeAttribute(name); } else setComplexAccessor(node, name, value); ensureNodeData(node)[name] = value; } function setComplexAccessor(node, name, value) { if ('on' !== name.substring(0, 2)) { var type = typeof value; if (falsey(value)) node.removeAttribute(name); else if ('function' !== type && 'object' !== type) node.setAttribute(name, value); } else { var _type = normalizeEventName(name), l = node._listeners || (node._listeners = {}), fn = !l[_type] ? 'add' : !value ? 'remove' : null; if (fn) node[fn + 'EventListener'](_type, eventProxy); l[_type] = value; } } function eventProxy(e) { var fn = this._listeners[normalizeEventName(e.type)]; if (fn) return fn.call(this, optionsHook('event', e) || e); else ; } function getNodeAttributes(node) { return node[ATTR_KEY] || getRawNodeAttributes(node) || EMPTY; } function getRawNodeAttributes(node) { var list = node.attributes; if (!list || !list.getNamedItem) return list; else return getAttributesAsObject(list); } function getAttributesAsObject(list) { var attrs = void 0; for (var i = list.length; i--; ) { var item = list[i]; if (!attrs) attrs = {}; attrs[item.name] = item.value; } return attrs; } function isSameNodeType(node, vnode) { if (isFunctionalComponent(vnode)) return !0; var nodeName = vnode.nodeName; if (isFunction(nodeName)) return node._componentConstructor === nodeName; if (3 === getNodeType(node)) return isString(vnode); else return toLowerCase(node.nodeName) === nodeName; } function getNodeProps(vnode) { var props = clone(vnode.attributes), c = vnode.children; if (c) props.children = c; var defaultProps = vnode.nodeName.defaultProps; if (defaultProps) for (var i in defaultProps) if (hasOwnProperty.call(defaultProps, i) && !(i in props)) props[i] = defaultProps[i]; return props; } function collectNode(node) { cleanNode(node); var name = normalizeName(node.nodeName), list = nodes[name]; if (list) list.push(node); else nodes[name] = [ node ]; } function createNode(nodeName) { var name = normalizeName(nodeName), list = nodes[name], node = list && list.pop() || document.createElement(nodeName); ensureNodeData(node); return node; } function cleanNode(node) { var p = node.parentNode; if (p) p.removeChild(node); if (3 !== getNodeType(node)) { if (!node[ATTR_KEY]) node[ATTR_KEY] = getRawNodeAttributes(node); node._component = node._componentConstructor = null; } } function diff(dom, vnode, context) { var originalAttributes = vnode.attributes; for (;isFunctionalComponent(vnode); ) vnode = buildFunctionalComponent(vnode, context); if (isFunction(vnode.nodeName)) return buildComponentFromVNode(dom, vnode, context); if (isString(vnode)) { if (dom) { var type = getNodeType(dom); if (3 === type) { dom[TEXT_CONTENT] = vnode; return dom; } else if (1 === type) collectNode(dom); } return document.createTextNode(vnode); } var out = dom, nodeName = vnode.nodeName || UNDEFINED_ELEMENT; if (!dom) out = createNode(nodeName); else if (toLowerCase(dom.nodeName) !== nodeName) { out = createNode(nodeName); appendChildren(out, toArray(dom.childNodes)); recollectNodeTree(dom); } innerDiffNode(out, vnode, context); diffAttributes(out, vnode); if (originalAttributes && originalAttributes.ref) (out[ATTR_KEY].ref = originalAttributes.ref)(out); return out; } function innerDiffNode(dom, vnode, context) { var children = void 0, keyed = void 0, keyedLen = 0, len = dom.childNodes.length, childrenLen = 0; if (len) { children = []; for (var i = 0; len > i; i++) { var child = dom.childNodes[i], key = child._component ? child._component.__key : getAccessor(child, 'key'); if (!empty(key)) { if (!keyed) keyed = {}; keyed[key] = child; keyedLen++; } else children[childrenLen++] = child; } } var vchildren = vnode.children, vlen = vchildren && vchildren.length, min = 0; if (vlen) for (var i = 0; vlen > i; i++) { var vchild = vchildren[i], child = void 0; if (keyedLen) { var attrs = vchild.attributes, key = attrs && attrs.key; if (!empty(key) && hasOwnProperty.call(keyed, key)) { child = keyed[key]; keyed[key] = null; keyedLen--; } } if (!child && childrenLen > min) for (var j = min; childrenLen > j; j++) { var c = children[j]; if (c && isSameNodeType(c, vchild)) { child = c; children[j] = null; if (j === childrenLen - 1) childrenLen--; if (j === min) min++; break; } } child = diff(child, vchild, context); if (dom.childNodes[i] !== child) { var c = child.parentNode !== dom && child._component, next = dom.childNodes[i + 1]; if (c) deepHook(c, 'componentWillMount'); if (next) dom.insertBefore(child, next); else dom.appendChild(child); if (c) deepHook(c, 'componentDidMount'); } } if (keyedLen) for (var i in keyed) if (hasOwnProperty.call(keyed, i) && keyed[i]) children[min = childrenLen++] = keyed[i]; if (childrenLen > min) removeOrphanedChildren(children); } function removeOrphanedChildren(children, unmountOnly) { for (var i = children.length; i--; ) { var child = children[i]; if (child) recollectNodeTree(child, unmountOnly); } } function recollectNodeTree(node, unmountOnly) { var attrs = node[ATTR_KEY]; if (attrs) hook(attrs, 'ref', null); var component = node._component; if (component) unmountComponent(node, component, !unmountOnly); else { if (!unmountOnly) { if (1 !== getNodeType(node)) { var p = node.parentNode; if (p) p.removeChild(node); return; } collectNode(node); } var c = node.childNodes; if (c && c.length) removeOrphanedChildren(c, unmountOnly); } } function diffAttributes(dom, vnode) { var old = getNodeAttributes(dom) || EMPTY, attrs = vnode.attributes || EMPTY, name = void 0, value = void 0; for (name in old) if (empty(attrs[name])) setAccessor(dom, name, null); if (attrs !== EMPTY) for (name in attrs) if (hasOwnProperty.call(attrs, name)) { value = attrs[name]; if (!empty(value) && value != getAccessor(dom, name)) setAccessor(dom, name, value); } } function collectComponent(component) { var name = component.constructor.name, list = components[name]; if (list) list.push(component); else components[name] = [ component ]; } function createComponent(ctor, props, context) { var list = components[ctor.name], len = list && list.length, c = void 0; for (var i = 0; len > i; i++) { c = list[i]; if (c.constructor === ctor) { list.splice(i, 1); var inst = new ctor(props, context); inst.base = c.base; return inst; } } return new ctor(props, context); } function triggerComponentRender(component) { if (!component._dirty) { component._dirty = !0; enqueueRender(component); } } function setComponentProps(component, props, opts, context) { var d = component._disableRendering; component.__ref = props.ref; component.__key = props.key; delete props.ref; delete props.key; component._disableRendering = !0; if (context) { if (!component.prevContext) component.prevContext = component.context; component.context = context; } if (component.base) hook(component, 'componentWillReceiveProps', props, component.context); if (!component.prevProps) component.prevProps = component.props; component.props = props; component._disableRendering = d; if (!opts || opts.render !== !1) if (opts && opts.renderSync || options.syncComponentUpdates !== !1) renderComponent(component); else triggerComponentRender(component); hook(component, '__ref', component); } function renderComponent(component, opts) { if (!component._disableRendering) { var skip = void 0, rendered = void 0, props = component.props, state = component.state, context = component.context, previousProps = component.prevProps || props, previousState = component.prevState || state, previousContext = component.prevContext || context, isUpdate = component.base; if (isUpdate) { component.props = previousProps; component.state = previousState; component.context = previousContext; if (hook(component, 'shouldComponentUpdate', props, state, context) === !1) skip = !0; else hook(component, 'componentWillUpdate', props, state, context); component.props = props; component.state = state; component.context = context; } component.prevProps = component.prevState = component.prevContext = null; component._dirty = !1; if (!skip) { rendered = hook(component, 'render', props, state, context); var childComponent = rendered && rendered.nodeName, childContext = component.getChildContext ? component.getChildContext() : context, toUnmount = void 0, base = void 0; if (isFunction(childComponent) && childComponent.prototype.render) { var inst = component._component; if (inst && inst.constructor !== childComponent) { toUnmount = inst; inst = null; } var childProps = getNodeProps(rendered); if (inst) setComponentProps(inst, childProps, SYNC_RENDER, childContext); else { inst = createComponent(childComponent, childProps, childContext); inst._parentComponent = component; component._component = inst; if (component.base) deepHook(inst, 'componentWillMount'); setComponentProps(inst, childProps, NO_RENDER, childContext); renderComponent(inst, DOM_RENDER); if (component.base) deepHook(inst, 'componentDidMount'); } base = inst.base; } else { var cbase = component.base; toUnmount = component._component; if (toUnmount) cbase = component._component = null; if (component.base || opts && opts.build) base = diff(cbase, rendered || EMPTY_BASE, childContext); } if (component.base && base !== component.base) { var p = component.base.parentNode; if (p && base !== p) p.replaceChild(base, component.base); } if (toUnmount) unmountComponent(toUnmount.base, toUnmount, !0); component.base = base; if (base) { var componentRef = component, t = component; for (;t = t._parentComponent; ) componentRef = t; base._component = componentRef; base._componentConstructor = componentRef.constructor; } if (isUpdate) hook(component, 'componentDidUpdate', previousProps, previousState, previousContext); } var cb = component._renderCallbacks, fn = void 0; if (cb) for (;fn = cb.pop(); ) fn.call(component); return rendered; } } function buildComponentFromVNode(dom, vnode, context) { var c = dom && dom._component, oldDom = dom; var isOwner = c && dom._componentConstructor === vnode.nodeName; for (;c && !isOwner && (c = c._parentComponent); ) isOwner = c.constructor === vnode.nodeName; if (isOwner) { setComponentProps(c, getNodeProps(vnode), SYNC_RENDER, context); dom = c.base; } else { if (c) { unmountComponent(dom, c, !0); dom = oldDom = null; } dom = createComponentFromVNode(vnode, dom, context); if (oldDom && dom !== oldDom) recollectNodeTree(oldDom); } return dom; } function createComponentFromVNode(vnode, dom, context) { var props = getNodeProps(vnode); var component = createComponent(vnode.nodeName, props, context); if (dom && !component.base) component.base = dom; setComponentProps(component, props, NO_RENDER, context); renderComponent(component, DOM_RENDER); return component.base; } function unmountComponent(dom, component, remove) { hook(component, '__ref', null); hook(component, 'componentWillUnmount'); var inner = component._component; if (inner) { unmountComponent(dom, inner, remove); remove = !1; } var base = component.base; if (base) { if (remove !== !1) { var p = base.parentNode; if (p) p.removeChild(base); } removeOrphanedChildren(base.childNodes, !0); } if (remove) { component._parentComponent = null; collectComponent(component); } hook(component, 'componentDidUnmount'); } function Component(props, context) { this._dirty = this._disableRendering = !1; this._linkedStates = {}; this._renderCallbacks = []; this.prevState = this.prevProps = this.prevContext = this.base = this._parentComponent = this._component = this.__ref = this.__key = null; this.context = context || {}; this.props = props || {}; this.state = hook(this, 'getInitialState') || {}; } function render(vnode, parent, merge) { var existing = merge && merge._component && merge._componentConstructor === vnode.nodeName, built = diff(merge, vnode), c = !existing && built._component; if (c) deepHook(c, 'componentWillMount'); if (built.parentNode !== parent) parent.appendChild(built); if (c) deepHook(c, 'componentDidMount'); return built; } var NO_RENDER = { render: !1 }; var SYNC_RENDER = { renderSync: !0 }; var DOM_RENDER = { build: !0 }; var EMPTY = {}; var EMPTY_BASE = ''; var HAS_DOM = 'undefined' != typeof document; var TEXT_CONTENT = !HAS_DOM || 'textContent' in document ? 'textContent' : 'nodeValue'; var ATTR_KEY = 'undefined' != typeof Symbol ? Symbol['for']('preactattr') : '__preactattr_'; var UNDEFINED_ELEMENT = 'undefined'; var NON_DIMENSION_PROPS = { boxFlex: 1, boxFlexGroup: 1, columnCount: 1, fillOpacity: 1, flex: 1, flexGrow: 1, flexPositive: 1, flexShrink: 1, flexNegative: 1, fontWeight: 1, lineClamp: 1, lineHeight: 1, opacity: 1, order: 1, orphans: 1, strokeOpacity: 1, widows: 1, zIndex: 1, zoom: 1 }; var isFunction = function(obj) { return 'function' == typeof obj; }; var isString = function(obj) { return 'string' == typeof obj; }; var hasOwnProperty = {}.hasOwnProperty; var empty = function(x) { return null == x; }; var falsey = function(value) { return value === !1 || null == value; }; var jsToCss = memoize(function(s) { return s.replace(/([A-Z])/g, '-$1').toLowerCase(); }); var toLowerCase = memoize(function(s) { return s.toLowerCase(); }); var ch = void 0; try { ch = new MessageChannel(); } catch (e) {} var setImmediate = ch ? function(f) { ch.port1.onmessage = f; ch.port2.postMessage(''); } : setTimeout; var options = { vnode: function(n) { var attrs = n.attributes; if (attrs && !isFunction(n.nodeName)) { var p = attrs.className; if (p) { attrs['class'] = p; delete attrs.className; } if (attrs['class']) normalize(attrs, 'class', hashToClassName); if (attrs.style) normalize(attrs, 'style', styleObjToCss); } } }; var SHARED_TEMP_ARRAY = []; var items = []; var itemsOffline = []; var normalizeEventName = memoize(function(t) { return t.replace(/^on/i, '').toLowerCase(); }); var nodes = {}; var normalizeName = memoize(function(name) { return name.toUpperCase(); }); var components = {}; extend(Component.prototype, { linkState: function(key, eventPath) { var c = this._linkedStates, cacheKey = key + '|' + (eventPath || ''); return c[cacheKey] || (c[cacheKey] = createLinkedState(this, key, eventPath)); }, setState: function(state, callback) { var s = this.state; if (!this.prevState) this.prevState = clone(s); extend(s, isFunction(state) ? state(s, this.props) : state); if (callback) this._renderCallbacks.push(callback); triggerComponentRender(this); }, forceUpdate: function() { renderComponent(this); }, render: function() { return null; } }); var preact = { h: h, Component: Component, render: render, rerender: rerender, options: options, hooks: options }; return preact; }); //# sourceMappingURL=preact.js.map
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(function(){var define,module,exports;return 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(require,module,exports){(function(global){"use strict";var transform=module.exports=require("./transformation/transform");transform.version=require("../../package").version;transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5","module"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i=0;i<_scripts.length;++i){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../package":197,"./transformation/transform":47}],2:[function(require,module,exports){"use strict";module.exports=File;var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation/transform");var generate=require("./generation/generator");var clone=require("./helpers/clone");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var _=require("lodash");function File(opts){this.dynamicImportIds={};this.dynamicImported=[];this.dynamicImports=[];this.dynamicData={};this.data={};this.lastStatements=[];this.opts=File.normaliseOptions(opts);this.ast={};this.buildTransformers()}File.helpers=["inherits","defaults","prototype-properties","apply-constructor","tagged-template-literal","tagged-template-literal-loose","interop-require","to-array","sliced-to-array","object-without-properties","has-own","slice","bind","define-property","async-to-generator","interop-require-wildcard","typeof","extends","get"];File.validOptions=["filename","filenameRelative","blacklist","whitelist","loose","optional","modules","sourceMap","sourceMapName","sourceFileName","sourceRoot","moduleRoot","moduleIds","comments","reactCompat","keepModuleIdExtensions","code","ast","format","playground","experimental","ignore","only","extensions"];File.normaliseOptions=function(opts){opts=clone(opts);for(var key in opts){if(key[0]!=="_"&&File.validOptions.indexOf(key)<0){throw new ReferenceError("Unknown option: "+key)}}_.defaults(opts,{keepModuleIdExtensions:false,experimental:false,reactCompat:false,playground:false,whitespace:true,moduleIds:false,blacklist:[],whitelist:[],sourceMap:false,optional:[],comments:true,filename:"unknown",modules:"common",loose:[],code:true,ast:true});opts.filename=opts.filename.replace(/\\/g,"/");opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);opts.optional=util.arrayify(opts.optional);opts.loose=util.arrayify(opts.loose);if(_.contains(opts.loose,"all")){opts.loose=Object.keys(transform.transformers)}_.defaults(opts,{moduleRoot:opts.sourceRoot});_.defaults(opts,{sourceRoot:opts.moduleRoot});_.defaults(opts,{filenameRelative:opts.filename});_.defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.playground){opts.experimental=true}opts.blacklist=transform._ensureTransformerNames("blacklist",opts.blacklist);opts.whitelist=transform._ensureTransformerNames("whitelist",opts.whitelist);opts.optional=transform._ensureTransformerNames("optional",opts.optional);opts.loose=transform._ensureTransformerNames("loose",opts.loose);return opts};File.prototype.isLoose=function(key){return _.contains(this.opts.loose,key)};File.prototype.buildTransformers=function(){var file=this;var transformers={};var secondaryStack=[];var stack=[];_.each(transform.transformers,function(transformer,key){var pass=transformers[key]=transformer.buildPass(file);if(pass.canRun(file)){stack.push(pass);if(transformer.secondPass){secondaryStack.push(pass)}if(transformer.manipulateOptions){transformer.manipulateOptions(file.opts,file)}}});this.transformerStack=stack.concat(secondaryStack);this.transformers=transformers};File.prototype.toArray=function(node,i){if(t.isArrayExpression(node)){return node}else if(t.isIdentifier(node)&&node.name==="arguments"){return t.callExpression(t.memberExpression(this.addHelper("slice"),t.identifier("call")),[node])}else{var declarationName="to-array";var args=[node];if(i){args.push(t.literal(i));declarationName="sliced-to-array"}return t.callExpression(this.addHelper(declarationName),args)}};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=_.isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("Unknown module formatter type "+JSON.stringify(type))}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.set=function(key,val){return this.data[key]=val};File.prototype.setDynamic=function(key,fn){this.dynamicData[key]=fn};File.prototype.get=function(key){var data=this.data[key];if(data){return data}else{var dynamic=this.dynamicData[key];if(dynamic){return this.set(key,dynamic())}}};File.prototype.addImport=function(source,name){name=name||source;var id=this.dynamicImportIds[name];if(!id){id=this.dynamicImportIds[name]=this.generateUidIdentifier(name);var specifiers=[t.importSpecifier(t.identifier("default"),id)];var declar=t.importDeclaration(specifiers,t.literal(source));declar._blockHoist=3;this.dynamicImported.push(declar);this.moduleFormatter.importSpecifier(specifiers[0],declar,this.dynamicImports)}return id};File.prototype.isConsequenceExpressionStatement=function(node){return t.isExpressionStatement(node)&&this.lastStatements.indexOf(node)>=0};File.prototype.addHelper=function(name){if(!_.contains(File.helpers,name)){throw new ReferenceError("unknown declaration "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var runtime=this.get("runtimeIdentifier");if(runtime){name=t.identifier(t.toIdentifier(name));return t.memberExpression(runtime,name)}else{var ref=util.template(name);ref._compact=true;var uid=this.generateUidIdentifier(name);this.scope.push({key:name,id:uid,init:ref});return uid}};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.addCode=function(code){code=(code||"")+"";this.code=code;return this.parseShebang(code)};File.prototype.parse=function(code){var self=this;code=this.addCode(code);var opts=this.opts;opts.allowImportExportEverywhere=this.isLoose("es6.modules");return util.parse(opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){var self=this;util.debug(this.opts.filename);this.ast=ast;this.lastStatements=t.getLastStatements(ast.program);this.scope=new Scope(ast.program,ast,null,this);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var astRun=function(key){_.each(self.transformerStack,function(pass){pass.astRun(key)})};astRun("enter");_.each(this.transformerStack,function(pass){pass.transform()});astRun("exit")};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;var result={code:"",map:null,ast:null};if(opts.ast)result.ast=ast;if(!opts.code)return result;var _result=generate(ast,opts,this.code);result.code=_result.code;result.map=_result.map;if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name).replace(/^_+/,"");scope=scope||this.scope;var uid;var i=0;do{uid=this._generateUid(name,i);i++}while(scope.has(uid));return uid};File.prototype.generateUidIdentifier=function(name,scope){scope=scope||this.scope;var id=t.identifier(this.generateUid(name,scope));scope.add(id);return id};File.prototype._generateUid=function(name,i){var id=name;if(i>1)id+=i;return"_"+id}},{"./generation/generator":4,"./helpers/clone":23,"./transformation/transform":47,"./traverse/scope":98,"./types":101,"./util":104,lodash:168}],3:[function(require,module,exports){"use strict";module.exports=Buffer;var util=require("../util");var _=require("lodash");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.substr(0,this.buf.length-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(this.format.compact){this.space();return}removeLast=removeLast||false;if(_.isNumber(i)){if(this.endsWith("{\n"))i--;if(this.endsWith(util.repeat(i,"\n")))return;while(i--){this._newline(removeLast)}return}if(_.isBoolean(i)){removeLast=i}this._newline(removeLast)};Buffer.prototype._newline=function(removeLast){if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this._removeSpacesAfterLastNewline();this._push("\n")};Buffer.prototype._removeSpacesAfterLastNewline=function(){var lastNewlineIndex=this.buf.lastIndexOf("\n");if(lastNewlineIndex===-1)return;var index=this.buf.length-1;while(index>lastNewlineIndex){if(this.buf[index]!==" "){break}index--}if(index===lastNewlineIndex){this.buf=this.buf.substring(0,index+1)}};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){var d=this.buf.length-str.length;return d>=0&&this.buf.lastIndexOf(str)===d};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var last=buf[buf.length-1];if(Array.isArray(cha)){return _.contains(cha,last)}else{return cha===last}}},{"../util":104,lodash:168}],4:[function(require,module,exports){"use strict";module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var detectIndent=require("detect-indent");var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var _=require("lodash");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(code,opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}_.each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(code,opts){var indent=detectIndent(code);var style=indent.indent;if(!style||style===" ")style=" ";return _.merge({parentheses:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:style,base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),playground:require("./generators/playground"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),flow:require("./generators/flow"),base:require("./generators/base"),jsx:require("./generators/jsx")};_.each(CodeGenerator.generators,function(generator){_.extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);var comments=[];_.each(ast.comments,function(comment){if(!comment._displayed)comments.push(comment)});this._printComments(comments);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";if(parent&&parent._compact){node._compact=true}var oldCompact=this.format.compact;if(node._compact){this.format.compact=true}var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null&&!node._ignoreUserWhitespace){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent);if(!self.buffer.get())lines=0}self.newline(lines)};if(this[node.type]){var needsNoLineTermParens=n.needsParensNoLineTerminator(node,parent);var needsParens=needsNoLineTermParens||n.needsParens(node,parent);if(needsParens)this.push("(");if(needsNoLineTermParens)this.indent();this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");this[node.type](node,this.buildPrint(node),parent);if(needsNoLineTermParens){this.newline();this.dedent()}if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node of type "+JSON.stringify(node.type)+" with constructor "+JSON.stringify(node&&node.constructor.name))}this.format.compact=oldCompact};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();_.each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}_.each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;_.each(comments,function(comment){var skip=false;_.each(self.ast.comments,function(origComment){if(origComment.start===comment.start){if(origComment._displayed)skip=true;origComment._displayed=true;return false}});if(skip)return;self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":101,"../util":104,"./buffer":3,"./generators/base":5,"./generators/classes":6,"./generators/comprehensions":7,"./generators/expressions":8,"./generators/flow":9,"./generators/jsx":10,"./generators/methods":11,"./generators/modules":12,"./generators/playground":13,"./generators/statements":14,"./generators/template-literals":15,"./generators/types":16,"./node":17,"./position":20,"./source-map":21,"./whitespace":22,"detect-indent":159,lodash:168}],5:[function(require,module,exports){"use strict";exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],6:[function(require,module,exports){"use strict";exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],7:[function(require,module,exports){"use strict";exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],8:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");var separator=",";if(node._prettyCall){separator+="\n";this.newline();this.indent()}else{separator+=" "}print.join(node.arguments,{separator:separator});if(node._prettyCall){this.newline();this.dedent()}this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate||node.all){this.push("*")}if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentPattern=exports.AssignmentExpression=function(node,print){print(node.left);this.space();this.push(node.operator);this.space();print(node.right)};var SCIENTIFIC_NOTATION=/e/i;exports.MemberExpression=function(node,print){var obj=node.object;print(obj);if(!node.computed&&t.isMemberExpression(node.property)){throw new TypeError("Got a MemberExpression for MemberExpression property")}var computed=node.computed;if(t.isLiteral(node.property)&&_.isNumber(node.property.value)){computed=true}if(computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(obj)&&util.isInteger(obj.value)&&!SCIENTIFIC_NOTATION.test(obj.value.toString())){this.push(".")}this.push(".");print(node.property)}}},{"../../types":101,"../../util":104,lodash:168}],9:[function(require,module,exports){"use strict";exports.AnyTypeAnnotation=exports.ArrayTypeAnnotation=exports.BooleanTypeAnnotation=exports.ClassProperty=exports.DeclareClass=exports.DeclareFunction=exports.DeclareModule=exports.DeclareVariable=exports.FunctionTypeAnnotation=exports.FunctionTypeParam=exports.GenericTypeAnnotation=exports.InterfaceExtends=exports.InterfaceDeclaration=exports.IntersectionTypeAnnotation=exports.NullableTypeAnnotation=exports.NumberTypeAnnotation=exports.StringLiteralTypeAnnotation=exports.StringTypeAnnotation=exports.TupleTypeAnnotation=exports.TypeofTypeAnnotation=exports.TypeAlias=exports.TypeAnnotation=exports.TypeParameterDeclaration=exports.TypeParameterInstantiation=exports.ObjectTypeAnnotation=exports.ObjectTypeCallProperty=exports.ObjectTypeIndexer=exports.ObjectTypeProperty=exports.QualifiedTypeIdentifier=exports.UnionTypeAnnotation=exports.VoidTypeAnnotation=function(){}},{}],10:[function(require,module,exports){"use strict";var t=require("../../types");var _=require("lodash");exports.JSXAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.JSXIdentifier=function(node){this.push(node.name)};exports.JSXNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.JSXMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.JSXSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.JSXExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.JSXElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();_.each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.JSXOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.push(" ");print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.JSXClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.JSXEmptyExpression=function(){}},{"../../types":101,lodash:168}],11:[function(require,module,exports){"use strict";var t=require("../../types");exports._params=function(node,print){this.push("(");print.join(node.params,{separator:", "});this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.push(" ");print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.push(" ");if(node.id){this.space();print(node.id)}this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":101}],12:[function(require,module,exports){"use strict";var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=function(node,print){if(t.isSpecifierDefault(node)){print(t.getSpecifierName(node))}else{return exports.ExportSpecifier.apply(this,arguments)}};exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;_.each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}var isDefault=t.isSpecifierDefault(spec);if(!isDefault&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":101,lodash:168}],13:[function(require,module,exports){"use strict";var _=require("lodash");_.each(["BindMemberExpression","BindFunctionExpression"],function(type){exports[type]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(type))}})},{lodash:168}],14:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(")");this.space();print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.push(" ");this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.push(" ");print(node.test)}this.push(";");if(node.update){this.push(" ");print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.push(" ");print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();if(node.handlers){print(node.handlers[0])}else{print(node.handler)}if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(")");this.space();this.push("{");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.newline();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");var hasInits=false;if(!t.isFor(parent)){for(var i=0;i<node.declarations.length;i++){if(node.declarations[i].init){hasInits=true}}}var sep=",";if(hasInits){sep+="\n"+util.repeat(node.kind.length+1) }else{sep+=" "}print.join(node.declarations,{separator:sep});if(!t.isFor(parent)){this.semicolon()}};exports.PrivateDeclaration=function(node,print){this.push("private ");print.join(node.declarations,{separator:", "});this.semicolon()};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.space();this.push("=");this.space();print(node.init)}else{print(node.id)}}},{"../../types":101,"../../util":104}],15:[function(require,module,exports){"use strict";var _=require("lodash");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;_.each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{lodash:168}],16:[function(require,module,exports){"use strict";var _=require("lodash");exports.Identifier=function(node){this.push(node.name)};exports.RestElement=exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");_.each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u000A\u000D\u2028\u2029]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{lodash:168}],17:[function(require,module,exports){"use strict";module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var _=require("lodash");var find=function(obj,node,parent){if(!obj)return;var result;var types=Object.keys(obj);for(var i=0;i<types.length;i++){var type=types[i];if(t.is(type,node)){var fn=obj[type];result=fn(node,parent);if(result!=null)break}}return result};function Node(node,parent){this.parent=parent;this.node=node}Node.isUserWhitespacable=function(node){return t.isUserWhitespacable(node)};Node.needsWhitespace=function(node,parent,type){if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;_.each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.needsWhitespaceBefore=function(node,parent){return Node.needsWhitespace(node,parent,"before")};Node.needsWhitespaceAfter=function(node,parent){return Node.needsWhitespace(node,parent,"after")};Node.needsParens=function(node,parent){if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){if(t.isCallExpression(node))return true;var hasCall=_.some(node,function(val){return t.isCallExpression(val)});if(hasCall)return true}return find(parens,node,parent)};Node.needsParensNoLineTerminator=function(node,parent){if(!parent)return false;if(!node.leadingComments||!node.leadingComments.length){return false}if(t.isYieldExpression(parent)||t.isAwaitExpression(parent)){return true}if(t.isContinueStatement(parent)||t.isBreakStatement(parent)||t.isReturnStatement(parent)||t.isThrowStatement(parent)){return true}return false};_.each(Node,function(fn,key){Node.prototype[key]=function(){var args=new Array(arguments.length+2);args[0]=this.node;args[1]=this.parent;for(var i=0;i<args.length;i++){args[i+2]=arguments[i]}return Node[key].apply(null,args)}})},{"../../types":101,"./parentheses":18,"./whitespace":19,lodash:168}],18:[function(require,module,exports){"use strict";var t=require("../../types");var _=require("lodash");var PRECEDENCE={};_.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(tier,i){_.each(tier,function(op){PRECEDENCE[op]=i})});exports.UpdateExpression=function(node,parent){if(t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ObjectExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false};exports.Binary=function(node,parent){if((t.isCallExpression(parent)||t.isNewExpression(parent))&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)||t.isNewExpression(parent)){if(parent.callee===node){return true}}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":101,lodash:168}],19:[function(require,module,exports){"use strict";var _=require("lodash");var t=require("../../types");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{AssignmentExpression:function(node){if(t.isFunction(node.right)){return 1}}},list:{VariableDeclaration:function(node){return _.map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};_.each({Function:1,Class:1,For:1,ArrayExpression:{after:1},ObjectExpression:{after:1},SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(_.isNumber(amounts)){amounts={after:amounts,before:amounts}}_.each([type].concat(t.FLIPPED_ALIAS_KEYS[type]||[]),function(type){_.each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})})},{"../../types":101,lodash:168}],20:[function(require,module,exports){"use strict";module.exports=Position;function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line++;this.column=0}else{this.column++}}};Position.prototype.unshift=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line--}else{this.column--}}}},{}],21:[function(require,module,exports){"use strict";module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];if(generated.line===original.line&&generated.column===original.column)return;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":101,"source-map":185}],22:[function(require,module,exports){"use strict";module.exports=Whitespace;var _=require("lodash");function getLookupIndex(i,base,max){i+=base;if(i>=max)i-=max;return i}function Whitespace(tokens,comments){this.tokens=_.sortBy(tokens.concat(comments),"start");this.used={};this._lastFoundIndex=0}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.start===token.start){startToken=tokens[i-1];endToken=token;this._lastFoundIndex=i;break}}return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.end===token.end){startToken=token;endToken=tokens[i+1];this._lastFoundIndex=i;break}}if(endToken.type.type==="eof"){return 1}else{var lines=this.getNewlinesBetween(startToken,endToken);if(node.type==="Line"&&!lines){return 1}else{return lines}}};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(typeof this.used[line]==="undefined"){this.used[line]=true;lines++}}return lines}},{lodash:168}],23:[function(require,module,exports){"use strict";module.exports=function cloneDeep(obj){var obj2={};if(!obj)return obj2;for(var key in obj){obj2[key]=obj[key]}return obj2}},{}],24:[function(require,module,exports){var supportsColor=require("supports-color");var tokenize=require("js-tokenizer");var chalk=require("chalk");var util=require("../util");var defs={string1:"red",string2:"red",punct:["white","bold"],curly:"green",parens:["blue","bold"],square:["yellow"],name:"white",keyword:["cyan"],number:"magenta",regexp:"magenta",comment1:"grey",comment2:"grey"};var highlight=function(text){var colorize=function(str,col){if(!col)return str;if(Array.isArray(col)){col.forEach(function(col){str=chalk[col](str)})}else{str=chalk[col](str)}return str};return tokenize(text,true).map(function(str){var type=tokenize.type(str);return colorize(str,defs[type])}).join("")};module.exports=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);if(supportsColor){lines=highlight(lines)}lines=lines.split("\n");var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+util.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=util.repeat(gutter.length-2);str+="|"+util.repeat(colNumber)+"^"}return str}).join("\n")}},{"../util":104,chalk:147,"js-tokenizer":167,"supports-color":196}],25:[function(require,module,exports){"use strict";module.exports=function(){return Object.create(null)}},{}],26:[function(require,module,exports){"use strict";module.exports=function toFastProperties(obj){function f(){}f.prototype=obj;return f;eval(obj)}},{}],27:[function(require,module,exports){"use strict";var t=require("./types");var _=require("lodash");require("./types/node");var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS);var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;def("File").bases("Node").build("program").field("program",def("Program"));def("AssignmentPattern").bases("Pattern").build("left","right").field("left",def("Pattern")).field("right",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));def("RestElement").bases("Pattern").build("argument").field("argument",def("expression"));def("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression")));def("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[def("Identifier")]);def("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("arguments",[def("Expression")]);def("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);types.finalize()},{"./types":101,"./types/node":102,"ast-types":119,estraverse:162,lodash:168}],28:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var isAssignment=function(node){return node.operator===opts.operator+"="};var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,context,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!isAssignment(expr))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope,true);nodes.push(t.expressionStatement(buildAssignment(exploded.ref,opts.build(exploded.uid,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!isAssignment(node))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(buildAssignment(exploded.ref,opts.build(exploded.uid,node.right)));return t.toSequenceExpression(nodes,scope)};exports.BinaryExpression=function(node){if(node.operator!==opts.operator)return;return opts.build(node.left,node.right)}}},{"../../types":101,"./explode-assignable-expression":31}],29:[function(require,module,exports){"use strict";var t=require("../../types");module.exports=function build(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("let",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))}},{"../../types":101}],30:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,context,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!opts.is(expr,file))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope);nodes.push(t.ifStatement(opts.build(exploded.uid,file),t.expressionStatement(buildAssignment(exploded.ref,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!opts.is(node,file))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(t.logicalExpression("&&",opts.build(exploded.uid,file),buildAssignment(exploded.ref,node.right)));nodes.push(exploded.ref);return t.toSequenceExpression(nodes,scope)}}},{"../../types":101,"./explode-assignable-expression":31}],31:[function(require,module,exports){"use strict";var t=require("../../types");var getObjRef=function(node,nodes,file,scope){var ref;if(t.isIdentifier(node)){if(scope.has(node.name,true)){return node}else{ref=node}}else if(t.isMemberExpression(node)){ref=node.object;if(t.isIdentifier(ref)&&scope.has(ref.name)){return ref}}else{throw new Error("We can't explode this node type "+node.type)}var temp=scope.generateUidBasedOnNode(ref);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,ref)]));return temp};var getPropRef=function(node,nodes,file,scope){var prop=node.property;var key=t.toComputedKey(node,prop);if(t.isLiteral(key))return key;var temp=scope.generateUidBasedOnNode(prop);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,prop)]));return temp};module.exports=function(node,nodes,file,scope,allowedSingleIdent){var obj;if(t.isIdentifier(node)&&allowedSingleIdent){obj=node}else{obj=getObjRef(node,nodes,file,scope)}var ref,uid;if(t.isIdentifier(node)){ref=node;uid=obj}else{var prop=getPropRef(node,nodes,file,scope);var computed=node.computed||t.isLiteral(prop);uid=ref=t.memberExpression(obj,prop,computed)}return{uid:uid,ref:ref}}},{"../../types":101}],32:[function(require,module,exports){"use strict";var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var visitor={enter:function(node,parent,scope,context,state){if(!t.isIdentifier(node,{name:state.id}))return;if(!t.isReferenced(node,parent))return;var localDeclar=scope.get(state.id,true);if(localDeclar!==state.outerDeclar)return;state.selfReference=true;context.stop()}};exports.property=function(node,file,scope){var key=t.toComputedKey(node,node.key);if(!t.isLiteral(key))return node;var id=t.toIdentifier(key.value);key=t.identifier(id);var state={id:id,selfReference:false,outerDeclar:scope.get(id,true)};traverse(node,visitor,scope,state);if(state.selfReference){node.value=util.template("property-method-assignment-wrapper",{FUNCTION:node.value,FUNCTION_ID:key,FUNCTION_KEY:scope.generateUidIdentifier(id),WRAPPER_KEY:scope.generateUidIdentifier(id+"Wrapper")})}else{node.value.id=key}}},{"../../traverse":97,"../../types":101,"../../util":104}],33:[function(require,module,exports){"use strict";var traverse=require("../../traverse");var t=require("../../types");var visitor={enter:function(node,parent,scope,context){if(t.isFunction(node))context.skip();if(t.isAwaitExpression(node)){node.type="YieldExpression";if(node.all){node.all=false;node.argument=t.callExpression(t.memberExpression(t.identifier("Promise"),t.identifier("all")),[node.argument])}}}};module.exports=function(node,callId,scope){node.async=false;node.generator=true;traverse(node,visitor,scope);var call=t.callExpression(callId,[node]);var id=node.id;delete node.id;if(t.isFunctionDeclaration(node)){var declar=t.variableDeclaration("let",[t.variableDeclarator(id,call)]);declar._blockHoist=true;return declar}else{return call}}},{"../../traverse":97,"../../types":101}],34:[function(require,module,exports){"use strict";module.exports=ReplaceSupers;var traverse=require("../../traverse");var t=require("../../types");function ReplaceSupers(opts){this.topLevelThisReference=null;this.methodNode=opts.methodNode;this.className=opts.className;this.superName=opts.superName;this.isLoose=opts.isLoose;this.scope=opts.scope;this.file=opts.file}ReplaceSupers.prototype.superProperty=function(property,isStatic,isComputed,thisExpression){return t.callExpression(this.file.addHelper("get"),[t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getPrototypeOf")),[isStatic?this.className:t.memberExpression(this.className,t.identifier("prototype"))]),isComputed?property:t.literal(property.name),thisExpression])};ReplaceSupers.prototype.looseSuperProperty=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};ReplaceSupers.prototype.replace=function(){this.traverseLevel(this.methodNode.value,true)};var visitor={enter:function(node,parent,scope,context,state){var topLevel=state.topLevel;var self=state.self;if(t.isFunction(node)&&!t.isArrowFunctionExpression(node)){self.traverseLevel(node,false);return context.skip()}if(t.isProperty(node,{method:true})||t.isMethodDefinition(node)){return context.skip()}var getThisReference=topLevel?t.thisExpression:self.getThisReference;var callback=self.specHandle;if(self.isLoose)callback=self.looseHandle;return callback.call(self,getThisReference,node,parent)}};ReplaceSupers.prototype.traverseLevel=function(node,topLevel){var state={self:this,topLevel:topLevel};traverse(node,visitor,this.scope,state)};ReplaceSupers.prototype.getThisReference=function(){if(this.topLevelThisReference){return this.topLevelThisReference}else{var ref=this.topLevelThisReference=this.file.generateUidIdentifier("this");this.methodNode.value.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(this.topLevelThisReference,t.thisExpression())]));return ref}};ReplaceSupers.prototype.looseHandle=function(getThisReference,node,parent){if(t.isIdentifier(node,{name:"super"})){return this.looseSuperProperty(this.methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;t.appendToMemberExpression(callee,t.identifier("call"));node.arguments.unshift(getThisReference())}};ReplaceSupers.prototype.specHandle=function(getThisReference,node,parent){var methodNode=this.methodNode;var property;var computed;var args;if(t.isIdentifier(node,{name:"super"})){if(!(t.isMemberExpression(parent)&&!parent.computed&&parent.property===node)){throw this.file.errorWithNode(node,"illegal use of bare super")}}else if(t.isCallExpression(node)){var callee=node.callee;if(t.isIdentifier(callee,{name:"super"})){property=methodNode.key;computed=methodNode.computed;args=node.arguments;if(methodNode.key.name!=="constructor"){var methodName=methodNode.key.name||"METHOD_NAME";throw this.file.errorWithNode(node,"Direct super call is illegal in non-constructor, use super."+methodName+"() instead")}}else{if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;property=callee.property;computed=callee.computed;args=node.arguments}}else if(t.isMemberExpression(node)){if(!t.isIdentifier(node.object,{name:"super"}))return;property=node.property;computed=node.computed}if(!property)return;var thisReference=getThisReference();var superProperty=this.superProperty(property,methodNode.static,computed,thisReference);if(args){if(args.length===1&&t.isSpreadElement(args[0])){return t.callExpression(t.memberExpression(superProperty,t.identifier("apply")),[thisReference,args[0].argument])}else{return t.callExpression(t.memberExpression(superProperty,t.identifier("call")),[thisReference].concat(args))}}else{return superProperty}}},{"../../traverse":97,"../../types":101}],35:[function(require,module,exports){"use strict";var t=require("../../types");exports.has=function(node){var first=node.body[0];return t.isExpressionStatement(first)&&t.isLiteral(first.expression,{value:"use strict"})};exports.wrap=function(node,callback){var useStrictNode;if(exports.has(node)){useStrictNode=node.body.shift()}callback();if(useStrictNode){node.body.unshift(useStrictNode)}}},{"../../types":101}],36:[function(require,module,exports){"use strict";module.exports=DefaultFormatter;var traverse=require("../../traverse");var object=require("../../helpers/object");var util=require("../../util");var t=require("../../types");var _=require("lodash");function DefaultFormatter(file){this.file=file;this.ids=object();this.hasNonDefaultExports=false;this.hasLocalExports=false;this.hasLocalImports=false;this.localImportOccurences=object();this.localExports=object();this.localImports=object();this.getLocalExports();this.getLocalImports();this.remapAssignments()}DefaultFormatter.prototype.doDefaultExportInterop=function(node){return node.default&&!this.noInteropRequire&&!this.hasNonDefaultExports};DefaultFormatter.prototype.bumpImportOccurences=function(node){var source=node.source.value;var occurs=this.localImportOccurences;occurs[source]=occurs[source]||0;occurs[source]+=node.specifiers.length};var exportsVisitor={enter:function(node,parent,scope,context,formatter){var declar=node&&node.declaration;if(t.isExportDeclaration(node)){formatter.hasLocalImports=true;if(declar&&t.isStatement(declar)){_.extend(formatter.localExports,t.getIds(declar,true))}if(!node.default){formatter.hasNonDefaultExports=true}if(node.source){formatter.bumpImportOccurences(node)}}}};DefaultFormatter.prototype.getLocalExports=function(){traverse(this.file.ast,exportsVisitor,this.file.scope,this)};var importsVisitor={enter:function(node,parent,scope,context,formatter){if(t.isImportDeclaration(node)){formatter.hasLocalImports=true;_.extend(formatter.localImports,t.getIds(node,true));formatter.bumpImportOccurences(node)}}};DefaultFormatter.prototype.getLocalImports=function(){traverse(this.file.ast,importsVisitor,this.file.scope,this)};var remapVisitor={enter:function(node,parent,scope,context,formatter){if(t.isUpdateExpression(node)&&formatter.isLocalReference(node.argument,scope)){context.skip();var assign=t.assignmentExpression(node.operator[0]+"=",node.argument,t.literal(1));var remapped=formatter.remapExportAssignment(assign);if(t.isExpressionStatement(parent)||node.prefix){return remapped}var nodes=[];nodes.push(remapped);var operator;if(node.operator==="--"){operator="+"}else{operator="-"}nodes.push(t.binaryExpression(operator,node.argument,t.literal(1)));return t.sequenceExpression(nodes)}if(t.isAssignmentExpression(node)&&formatter.isLocalReference(node.left,scope)){context.skip();return formatter.remapExportAssignment(node)}}};DefaultFormatter.prototype.remapAssignments=function(){if(this.hasLocalImports){traverse(this.file.ast,remapVisitor,this.file.scope,this)}};DefaultFormatter.prototype.isLocalReference=function(node){var localImports=this.localImports;return t.isIdentifier(node)&&localImports[node.name]&&localImports[node.name]!==node};DefaultFormatter.prototype.checkLocalReference=function(node){var file=this.file;if(this.isLocalReference(node)){throw file.errorWithNode(node,"Illegal assignment of module import")}};DefaultFormatter.prototype.remapExportAssignment=function(node){return t.assignmentExpression("=",node.left,t.assignmentExpression(node.operator,t.memberExpression(t.identifier("exports"),node.left),node.right))};DefaultFormatter.prototype.isLocalReference=function(node,scope){var localExports=this.localExports;var name=node.name;return t.isIdentifier(node)&&localExports[name]&&localExports[name]===scope.get(name,true)};DefaultFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}if(!opts.keepModuleIdExtensions){filenameRelative=filenameRelative.replace(/\.(.*?)$/,"")}moduleName+=filenameRelative;moduleName=moduleName.replace(/\\/g,"/");return moduleName};DefaultFormatter.prototype._pushStatement=function(ref,nodes){if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}return ref};DefaultFormatter.prototype._hoistExport=function(declar,assign,priority){if(t.isFunctionDeclaration(declar)){assign._blockHoist=priority||2}return assign};DefaultFormatter.prototype.getExternalReference=function(node,nodes){var ids=this.ids;var id=node.source.value;if(ids[id]){return ids[id]}else{return this.ids[id]=this._getExternalReference(node,nodes)}};DefaultFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){var ref=this.getExternalReference(node,nodes);if(t.isExportBatchSpecifier(specifier)){nodes.push(this.buildExportsWildcard(ref,node))}else{if(t.isSpecifierDefault(specifier)&&!this.noInteropRequire){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier))}nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),ref,node))}}else{nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),specifier.id,node))}};DefaultFormatter.prototype.buildExportsWildcard=function(objectIdentifier){return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"),[t.identifier("exports"),t.callExpression(this.file.addHelper("interop-require-wildcard"),[objectIdentifier])]))};DefaultFormatter.prototype.buildExportsAssignment=function(id,init){return util.template("exports-assign",{VALUE:init,KEY:id},true)};DefaultFormatter.prototype.exportDeclaration=function(node,nodes){var declar=node.declaration;var id=declar.id;if(node.default){id=t.identifier("default")}var assign;if(t.isVariableDeclaration(declar)){for(var i=0;i<declar.declarations.length;i++){var decl=declar.declarations[i];decl.init=this.buildExportsAssignment(decl.id,decl.init,node).expression;var newDeclar=t.variableDeclaration(declar.kind,[decl]);if(i===0)t.inherits(newDeclar,declar);nodes.push(newDeclar)}}else{var ref=declar;if(t.isFunctionDeclaration(declar)||t.isClassDeclaration(declar)){ref=declar.id;nodes.push(declar)}assign=this.buildExportsAssignment(id,ref,node);nodes.push(assign);this._hoistExport(declar,assign)}}},{"../../helpers/object":25,"../../traverse":97,"../../types":101,"../../util":104,lodash:168}],37:[function(require,module,exports){"use strict";var util=require("../../util");module.exports=function(Parent){var Constructor=function(){this.noInteropRequire=true;Parent.apply(this,arguments)};util.inherits(Constructor,Parent);return Constructor}},{"../../util":104}],38:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./amd"))},{"./_strict":37,"./amd":39}],39:[function(require,module,exports){"use strict";module.exports=AMDFormatter;var DefaultFormatter=require("./_default");var CommonFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(){CommonFormatter.apply(this,arguments)}util.inherits(AMDFormatter,DefaultFormatter);AMDFormatter.prototype.buildDependencyLiterals=function(){var names=[]; for(var name in this.ids){names.push(t.literal(name))}return names};AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];if(this.passModuleArg)names.push(t.literal("module"));names=names.concat(this.buildDependencyLiterals());names=t.arrayExpression(names);var params=_.values(this.ids);if(this.passModuleArg)params.unshift(t.identifier("module"));params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){if(this.file.opts.moduleIds){return DefaultFormatter.prototype.getModuleName.apply(this,arguments)}else{return null}};AMDFormatter.prototype._getExternalReference=function(node){return this.file.generateUidIdentifier(node.source.value)};AMDFormatter.prototype.importDeclaration=function(node){this.getExternalReference(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var ref=this.getExternalReference(node);if(_.contains(this.file.dynamicImported,node)){this.ids[node.source.value]=key;return}else if(t.isImportBatchSpecifier(specifier)){}else if(t.isSpecifierDefault(specifier)&&!this.noInteropRequire){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier),false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportDeclaration=function(node){if(this.doDefaultExportInterop(node)){this.passModuleArg=true}CommonFormatter.prototype.exportDeclaration.apply(this,arguments)}},{"../../types":101,"../../util":104,"./_default":36,"./common":41,lodash:168}],40:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./common"))},{"./_strict":37,"./common":41}],41:[function(require,module,exports){"use strict";module.exports=CommonJSFormatter;var DefaultFormatter=require("./_default");var util=require("../../util");var t=require("../../types");var _=require("lodash");function CommonJSFormatter(file){DefaultFormatter.apply(this,arguments);if(this.hasNonDefaultExports){file.ast.program.body.push(util.template("exports-module-declaration",true))}}util.inherits(CommonJSFormatter,DefaultFormatter);CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var ref=this.getExternalReference(node,nodes);if(t.isSpecifierDefault(specifier)){if(!_.contains(this.file.dynamicImported,node)){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,ref)]))}else{if(specifier.type==="ImportBatchSpecifier"){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addHelper("interop-require-wildcard"),[ref]))]))}else{nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.memberExpression(ref,t.getSpecifierId(specifier)))]))}}};CommonJSFormatter.prototype.importDeclaration=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source},true))};CommonJSFormatter.prototype.exportDeclaration=function(node,nodes){if(this.doDefaultExportInterop(node)){var declar=node.declaration;var assign=util.template("exports-default-assign",{VALUE:this._pushStatement(declar,nodes)},true);if(t.isFunctionDeclaration(declar)){assign._blockHoist=3}nodes.push(assign);return}DefaultFormatter.prototype.exportDeclaration.apply(this,arguments)};CommonJSFormatter.prototype._getExternalReference=function(node,nodes){var source=node.source.value;var call=t.callExpression(t.identifier("require"),[node.source]);if(this.localImportOccurences[source]>1){var uid=this.file.generateUidIdentifier(source);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(uid,call)]));return uid}else{return call}}},{"../../types":101,"../../util":104,"./_default":36,lodash:168}],42:[function(require,module,exports){"use strict";module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.exportDeclaration=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.importDeclaration=IgnoreFormatter.prototype.importSpecifier=IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":101}],43:[function(require,module,exports){module.exports={commonStrict:require("./common-strict"),amdStrict:require("./amd-strict"),umdStrict:require("./umd-strict"),common:require("./common"),system:require("./system"),ignore:require("./ignore"),amd:require("./amd"),umd:require("./umd")}},{"./amd":39,"./amd-strict":38,"./common":41,"./common-strict":40,"./ignore":42,"./system":44,"./umd":46,"./umd-strict":45}],44:[function(require,module,exports){"use strict";module.exports=SystemFormatter;var DefaultFormatter=require("./_default");var AMDFormatter=require("./amd");var useStrict=require("../helpers/use-strict");var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");function SystemFormatter(file){this.exportIdentifier=file.generateUidIdentifier("export");this.noInteropRequire=true;DefaultFormatter.apply(this,arguments)}util.inherits(SystemFormatter,AMDFormatter);SystemFormatter.prototype._addImportSource=function(node,exportNode){node._importSource=exportNode.source&&exportNode.source.value;return node};SystemFormatter.prototype.buildExportsWildcard=function(objectIdentifier,node){var leftIdentifier=this.file.generateUidIdentifier("key");var valIdentifier=t.memberExpression(objectIdentifier,leftIdentifier,true);var left=t.variableDeclaration("var",[t.variableDeclarator(leftIdentifier)]);var right=objectIdentifier;var block=t.blockStatement([t.expressionStatement(this.buildExportCall(leftIdentifier,valIdentifier))]);return this._addImportSource(t.forInStatement(left,right,block),node)};SystemFormatter.prototype.buildExportsAssignment=function(id,init,node){var call=this.buildExportCall(t.literal(id.name),init,true);return this._addImportSource(call,node)};SystemFormatter.prototype.remapExportAssignment=function(node){return this.buildExportCall(t.literal(node.left.name),node)};SystemFormatter.prototype.buildExportCall=function(id,init,isStatement){var call=t.callExpression(this.exportIdentifier,[id,init]);if(isStatement){return t.expressionStatement(call)}else{return call}};SystemFormatter.prototype.importSpecifier=function(specifier,node,nodes){AMDFormatter.prototype.importSpecifier.apply(this,arguments);this._addImportSource(_.last(nodes),node)};var runnerSettersVisitor={enter:function(node,parent,scope,context,state){if(node._importSource===state.source){if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){state.hoistDeclarators.push(t.variableDeclarator(declar.id));state.nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init)))})}else{state.nodes.push(node)}context.remove()}}};SystemFormatter.prototype.buildRunnerSetters=function(block,hoistDeclarators){var scope=this.file.scope;return t.arrayExpression(_.map(this.ids,function(uid,source){var state={source:source,nodes:[],hoistDeclarators:hoistDeclarators};traverse(block,runnerSettersVisitor,scope,state);return t.functionExpression(null,[uid],t.blockStatement(state.nodes))}))};var hoistVariablesVisitor={enter:function(node,parent,scope,context,hoistDeclarators){if(t.isFunction(node)){return context.skip()}if(t.isVariableDeclaration(node)){if(node.kind!=="var"&&!t.isProgram(parent)){return}if(node._blockHoist)return;var nodes=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];hoistDeclarators.push(t.variableDeclarator(declar.id));if(declar.init){var assign=t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init));nodes.push(assign)}}if(t.isFor(parent)){if(parent.left===node){return node.declarations[0].id}if(parent.init===node){return t.toSequenceExpression(nodes,scope)}}return nodes}}};var hoistFunctionsVisitor={enter:function(node,parent,scope,context,handlerBody){if(t.isFunction(node))context.skip();if(t.isFunctionDeclaration(node)||node._blockHoist){handlerBody.push(node);context.remove()}}};SystemFormatter.prototype.transform=function(ast){var program=ast.program;var hoistDeclarators=[];var moduleName=this.getModuleName();var moduleNameLiteral=t.literal(moduleName);var block=t.blockStatement(program.body);var runner=util.template("system",{MODULE_NAME:moduleNameLiteral,MODULE_DEPENDENCIES:t.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(block,hoistDeclarators),EXECUTE:t.functionExpression(null,[],block)},true);var handlerBody=runner.expression.arguments[2].body.body;if(!moduleName)runner.expression.arguments.shift();var returnStatement=handlerBody.pop();traverse(block,hoistVariablesVisitor,this.file.scope,hoistDeclarators);if(hoistDeclarators.length){var hoistDeclar=t.variableDeclaration("var",hoistDeclarators);hoistDeclar._blockHoist=true;handlerBody.unshift(hoistDeclar)}traverse(block,hoistFunctionsVisitor,this.file.scope,handlerBody);handlerBody.push(returnStatement);if(useStrict.has(block)){handlerBody.unshift(block.body.shift())}program.body=[runner]}},{"../../traverse":97,"../../types":101,"../../util":104,"../helpers/use-strict":35,"./_default":36,"./amd":39,lodash:168}],45:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./umd"))},{"./_strict":37,"./umd":46}],46:[function(require,module,exports){"use strict";module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];for(var name in this.ids){names.push(t.literal(name))}var ids=_.values(this.ids);var args=[t.identifier("exports")];if(this.passModuleArg)args.push(t.identifier("module"));args=args.concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.literal("exports")];if(this.passModuleArg)defineArgs.push(t.literal("module"));defineArgs=defineArgs.concat(names);defineArgs=[t.arrayExpression(defineArgs)];var testExports=util.template("test-exports");var testModule=util.template("test-module");var commonTests=this.passModuleArg?t.logicalExpression("&&",testExports,testModule):testExports;var commonArgs=[t.identifier("exports")];if(this.passModuleArg)commonArgs.push(t.identifier("module"));commonArgs=commonArgs.concat(names.map(function(name){return t.callExpression(t.identifier("require"),[name])}));var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_TEST:commonTests,COMMON_ARGUMENTS:commonArgs});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":101,"../../util":104,"./amd":39,lodash:168}],47:[function(require,module,exports){"use strict";module.exports=transform;var Transformer=require("./transformer");var object=require("../helpers/object");var File=require("../file");var util=require("../util");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform.fromAst=function(ast,code,opts){ast=util.normaliseAst(ast);var file=new File(opts);file.addCode(code);file.transform(ast);return file.generate()};transform._ensureTransformerNames=function(type,rawKeys){var keys=[];for(var i=0;i<rawKeys.length;i++){var key=rawKeys[i];var deprecatedKey=transform.deprecatedTransformerMap[key];if(deprecatedKey){console.error("The transformer "+key+" has been renamed to "+deprecatedKey+" in v3.0.0 - backwards compatibilty will be removed 4.0.0");rawKeys.push(deprecatedKey)}else if(transform.transformers[key]){keys.push(key)}else if(transform.namespaces[key]){keys=keys.concat(transform.namespaces[key])}else{throw new ReferenceError("Unknown transformer "+key+" specified in "+type+" - "+"transformer key names have been changed in 3.0.0 see "+"the changelog for more info "+"https://github.com/6to5/6to5/blob/master/CHANGELOG.md#300")}}return keys};transform.transformers=object();transform.namespaces=object();transform.deprecatedTransformerMap=require("./transformers/deprecated");transform.moduleFormatters=require("./modules");var rawTransformers=require("./transformers");_.each(rawTransformers,function(transformer,key){var namespace=key.split(".")[0];transform.namespaces[namespace]=transform.namespaces[namespace]||[];transform.namespaces[namespace].push(key);transform.transformers[key]=new Transformer(key,transformer)})},{"../file":2,"../helpers/object":25,"../util":104,"./modules":43,"./transformer":49,"./transformers":71,"./transformers/deprecated":50,lodash:168}],48:[function(require,module,exports){module.exports=TransformerPass;var traverse=require("../traverse");var util=require("../util");var _=require("lodash");function TransformerPass(file,transformer){this.transformer=transformer;this.handlers=transformer.handlers;this.file=file}TransformerPass.prototype.astRun=function(key){var handlers=this.handlers;var file=this.file;if(handlers.ast&&handlers.ast[key]){handlers.ast[key](file.ast,file)}};TransformerPass.prototype.canRun=function(){var transformer=this.transformer;var opts=this.file.opts;var key=transformer.key;if(key[0]==="_")return true;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false;if(transformer.optional&&!_.contains(opts.optional,key))return false;if(transformer.experimental&&!opts.experimental)return false;return true};var transformVisitor={enter:function(node,parent,scope,context,state){var fns=state.handlers[node.type];if(!fns)return;return fns.enter(node,parent,scope,context,state.file,state.pass)},exit:function(node,parent,scope,context,state){var fns=state.handlers[node.type];if(!fns)return;return fns.exit(node,parent,scope,context,state.file,state.pass)}};TransformerPass.prototype.transform=function(){var file=this.file;util.debug(file.opts.filename+": Running transformer "+this.transformer.key);this.astRun("before");var state={file:file,handlers:this.handlers,pass:this};traverse(file.ast,transformVisitor,file.scope,state);this.astRun("after")}},{"../traverse":97,"../util":104,lodash:168}],49:[function(require,module,exports){"use strict";module.exports=Transformer;var TransformerPass=require("./transformer-pass");var t=require("../types");var _=require("lodash");function Transformer(key,transformer,opts){this.manipulateOptions=transformer.manipulateOptions;this.experimental=!!transformer.experimental;this.secondPass=!!transformer.secondPass;this.optional=!!transformer.optional;this.handlers=this.normalise(transformer);this.opts=opts||{};this.key=key}Transformer.prototype.normalise=function(transformer){var self=this;if(_.isFunction(transformer)){transformer={ast:transformer}}_.each(transformer,function(fns,type){if(type[0]==="_"){self[type]=fns;return}if(_.isFunction(fns))fns={enter:fns};if(!_.isObject(fns))return;if(!fns.enter)fns.enter=_.noop;if(!fns.exit)fns.exit=_.noop;transformer[type]=fns;var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){_.each(aliases,function(alias){transformer[alias]=fns})}});return transformer};Transformer.prototype.buildPass=function(file){return new TransformerPass(file,this)}},{"../types":101,"./transformer-pass":48,lodash:168}],50:[function(require,module,exports){module.exports={specNoForInOfAssignment:"validation.noForInOfAssignment",specSetters:"validation.setters",specBlockScopedFunctions:"spec.blockScopedFunctions",malletOperator:"playground.malletOperator",methodBinding:"playground.methodBinding",memoizationOperator:"playground.memoizationOperator",objectGetterMemoization:"playground.objectGetterMemoization",modules:"es6.modules",propertyNameShorthand:"es6.properties.shorthand",arrayComprehension:"es7.comprehensions",generatorComprehension:"es7.comprehensions",arrowFunctions:"es6.arrowFunctions",classes:"es6.classes",objectSpread:"es7.objectSpread",exponentiationOperator:"es7.exponentiationOperator",spread:"es6.spread",templateLiterals:"es6.templateLiterals",propertyMethodAssignment:"es6.properties.shorthand",computedPropertyNames:"es6.properties.computed",defaultParameters:"es6.parameters.default",restParameters:"es6.parameters.rest",destructuring:"es6.destructuring",forOf:"es6.forOf",unicodeRegex:"es6.unicodeRegex",abstractReferences:"es7.abstractReferences",constants:"es6.constants",letScoping:"es6.letScoping",blockScopingTDZ:"es6.blockScopingTDZ",generators:"regenerator",protoToAssign:"spec.protoToAssign",typeofSymbol:"spec.typeofSymbol",coreAliasing:"selfContained",undefinedToVoid:"spec.undefinedToVoid",undeclaredVariableCheck:"validation.undeclaredVariableCheck",specPropertyLiterals:"minification.propertyLiterals",specMemberExpressionLiterals:"minification.memberExpressionLiterals"}},{}],51:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.ObjectExpression=function(node){var mutatorMap={};var hasAny=false;node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){hasAny=true;util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.computed,prop.value);return false}else{return true}});if(!hasAny)return;return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("defineProperties")),[node,util.buildDefineProperties(mutatorMap)])}},{"../../../types":101,"../../../util":104}],52:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction="arrow";node.expression=false;node.type="FunctionExpression";return node}},{"../../../types":101}],53:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(!t.isReferencedIdentifier(node,parent))return;var declared=state.letRefs[node.name];if(!declared)return;if(scope.get(node.name,true)!==declared)return;var declaredLoc=declared.loc;var referenceLoc=node.loc;if(!declaredLoc||!referenceLoc)return;var before=referenceLoc.start.line<declaredLoc.start.line;if(referenceLoc.start.line===declaredLoc.start.line){before=referenceLoc.start.col<declaredLoc.start.col}if(before){throw state.file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}}};exports.optional=true;exports.Loop=exports.Program=exports.BlockStatement=function(node,parent,scope,context,file){var letRefs=node._letReferences;if(!letRefs)return;var state={letRefs:letRefs,file:file};traverse(node,visitor,scope,state)}},{"../../../traverse":97,"../../../types":101}],54:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var object=require("../../../helpers/object");var util=require("../../../util");var t=require("../../../types");var _=require("lodash");var isLet=function(node,parent){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;if(!t.isFor(parent)||t.isFor(parent)&&parent.left!==node){for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];declar.init=declar.init||t.identifier("undefined")}}node._let=true;node.kind="var";return true};var isVar=function(node,parent){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node,parent)};var standardiseLets=function(declars){for(var i=0;i<declars.length;i++){delete declars[i]._let}};exports.VariableDeclaration=function(node,parent){isLet(node,parent)};exports.Loop=function(node,parent,scope,context,file){var init=node.left||node.init;if(isLet(init,node)){t.ensureBlock(node);node.body._letDeclarators=[init]}if(t.isLabeledStatement(parent)){node.label=parent.label}var letScoping=new LetScoping(node,node.body,parent,scope,file);letScoping.run();if(node.label&&!t.isLabeledStatement(parent)){return t.labeledStatement(node.label,node)}};exports.Program=exports.BlockStatement=function(block,parent,scope,context,file){if(!t.isLoop(parent)){var letScoping=new LetScoping(false,block,parent,scope,file);letScoping.run()}};function LetScoping(loopParent,block,parent,scope,file){this.loopParent=loopParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.outsideLetReferences=object();this.hasLetReferences=false;this.letReferences=block._letReferences=object();this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;var needsClosure=this.getLetReferences();if(t.isFunction(this.parent)||t.isProgram(this.block))return;if(!this.hasLetReferences)return;if(needsClosure){this.needsClosure()}else{this.remap()}};function replace(node,parent,scope,context,remaps){if(!t.isReferencedIdentifier(node,parent))return;var remap=remaps[node.name];if(!remap)return;var own=scope.get(node.name,true);if(own===remap.node){node.name=remap.uid}else{if(context)context.skip()}}var replaceVisitor={enter:replace};function traverseReplace(node,parent,scope,remaps){replace(node,parent,scope,null,remaps);traverse(node,replaceVisitor,scope,remaps)}LetScoping.prototype.remap=function(){var hasRemaps=false;var letRefs=this.letReferences;var scope=this.scope;var remaps=object();for(var key in letRefs){var ref=letRefs[key];if(scope.parentHas(key)){var uid=scope.generateUidIdentifier(ref.name).name;ref.name=uid;hasRemaps=true;remaps[key]=remaps[uid]={node:ref,uid:uid}}}if(!hasRemaps)return;var loopParent=this.loopParent;if(loopParent){traverseReplace(loopParent.right,loopParent,scope,remaps);traverseReplace(loopParent.test,loopParent,scope,remaps);traverseReplace(loopParent.update,loopParent,scope,remaps)}traverse(this.block,replaceVisitor,scope,remaps)};LetScoping.prototype.needsClosure=function(){var block=this.block;this.has=this.checkLoop();this.hoistVarDeclarations();var params=_.values(this.outsideLetReferences);var fn=t.functionExpression(null,params,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var call=t.callExpression(fn,params);var ret=this.scope.generateUidIdentifier("ret");var hasYield=traverse.hasType(fn.body,this.scope,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}var hasAsync=traverse.hasType(fn.body,this.scope,"AwaitExpression",t.FUNCTION_TYPES);if(hasAsync){fn.async=true;call=t.awaitExpression(call,true)}this.build(ret,call)};var letReferenceFunctionVisitor={enter:function(node,parent,scope,context,state){if(!t.isReferencedIdentifier(node,parent))return;if(scope.hasOwn(node.name,true))return;if(!state.letReferences[node.name])return;state.closurify=true}};var letReferenceBlockVisitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node)){traverse(node,letReferenceFunctionVisitor,scope,state);return context.skip()}}};LetScoping.prototype.getLetReferences=function(){var block=this.block;var declarators=block._letDeclarators||[];var declar;for(var i=0;i<declarators.length;i++){declar=declarators[i];_.extend(this.outsideLetReferences,t.getIds(declar,true))}if(block.body){for(i=0;i<block.body.length;i++){declar=block.body[i];if(isLet(declar,block)){declarators=declarators.concat(declar.declarations)}}}for(i=0;i<declarators.length;i++){declar=declarators[i];var keys=t.getIds(declar,true);_.extend(this.letReferences,keys);this.hasLetReferences=true}if(!this.hasLetReferences)return;standardiseLets(declarators);var state={letReferences:this.letReferences,closurify:false};traverse(this.block,letReferenceBlockVisitor,this.scope,state);return state.closurify};var loopVisitor={enter:function(node,parent,scope,context,state){var replace;if(t.isFunction(node)||t.isLoop(node)){return context.skip()}if(node&&!node.label&&state.isLoop){if(t.isBreakStatement(node)){if(t.isSwitchCase(parent))return;state.hasBreak=true;replace=t.returnStatement(t.literal("break"))}else if(t.isContinueStatement(node)){state.hasContinue=true;replace=t.returnStatement(t.literal("continue"))}}if(t.isReturnStatement(node)){state.hasReturn=true;replace=t.returnStatement(t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))]))}if(replace)return t.inherits(replace,node)}};LetScoping.prototype.checkLoop=function(){var state={hasContinue:false,hasReturn:false,hasBreak:false,isLoop:!!this.loopParent};traverse(this.block,loopVisitor,this.scope,state);return state};var hoistVarDeclarationsVisitor={enter:function(node,parent,scope,context,self){if(t.isForStatement(node)){if(isVar(node.init,node)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left,node)){node.left=node.left.declarations[0].id}}else if(isVar(node,parent)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return context.skip()}}};LetScoping.prototype.hoistVarDeclarations=function(){traverse(this.block,hoistVarDeclarationsVisitor,this.scope,this)};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];if(!declar.init)continue;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))}return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreak||has.hasContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var loopParent=this.loopParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreak||has.hasContinue){if(!loopParent){throw new Error("Has no loop parent but we're trying to reassign breaks "+"and continues, something is going wrong here.")}var label=loopParent.label=loopParent.label||this.scope.generateUidIdentifier("loop");if(has.hasBreak){cases.push(t.switchCase(t.literal("break"),[t.breakStatement(label)]))}if(has.hasContinue){cases.push(t.switchCase(t.literal("continue"),[t.continueStatement(label)]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../../helpers/object":25,"../../../traverse":97,"../../../types":101,"../../../util":104,lodash:168}],55:[function(require,module,exports){"use strict";var ReplaceSupers=require("../../helpers/replace-supers");var nameMethod=require("../../helpers/name-method");var util=require("../../../util");var t=require("../../../types");exports.ClassDeclaration=function(node,parent,scope,context,file){return new Class(node,file,scope,true).run()};exports.ClassExpression=function(node,parent,scope,context,file){if(!node.id){if(t.isProperty(parent)&&parent.value===node&&!parent.computed&&t.isIdentifier(parent.key)){node.id=parent.key}if(t.isVariableDeclarator(parent)&&t.isIdentifier(parent.id)){node.id=parent.id}}return new Class(node,file,scope,false).run()};function Class(node,file,scope,isStatement){this.isStatement=isStatement;this.scope=scope;this.node=node;this.file=file;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||scope.generateUidIdentifier("class");this.superName=node.superClass;this.isLoose=file.isLoose("es6.classes")}Class.prototype.run=function(){var superName=this.superName;var className=this.className;var file=this.file;var body=this.body=[];var constructor;if(this.node.id){constructor=t.functionDeclaration(className,[],t.blockStatement([]));body.push(constructor)}else{constructor=t.functionExpression(null,[],t.blockStatement([]));body.push(t.variableDeclaration("var",[t.variableDeclarator(className,constructor)]))}this.constructor=constructor;var closureParams=[];var closureArgs=[];if(superName){closureArgs.push(superName);if(!t.isIdentifier(superName)){var superRef=this.scope.generateUidBasedOnNode(superName,this.file);superName=superRef}closureParams.push(superName);this.superName=superName;body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"),[className,superName])))}this.buildBody();t.inheritsComments(body[0],this.node);var init;if(body.length===1){init=t.toExpression(constructor)}else{body.push(t.returnStatement(className));init=t.callExpression(t.functionExpression(null,closureParams,t.blockStatement(body)),closureArgs)}if(this.isStatement){return t.variableDeclaration("let",[t.variableDeclarator(className,init)])}else{return init}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;for(var i=0;i<classBody.length;i++){var node=classBody[i];if(t.isMethodDefinition(node)){var replaceSupers=new ReplaceSupers({methodNode:node,className:this.className,superName:this.superName,isLoose:this.isLoose,scope:this.scope,file:this.file});replaceSupers.replace();if(node.key.name==="constructor"){this.pushConstructor(node)}else{this.pushMethod(node)}}else if(t.isPrivateDeclaration(node)){this.closure=true;body.unshift(node)}}if(!this.hasConstructor&&superName&&!t.isFalsyExpression(superName)){var defaultConstructorTemplate="class-super-constructor-call";if(this.isLoose)defaultConstructorTemplate+="-loose";constructor.body.body.push(util.template(defaultConstructorTemplate,{CLASS_NAME:className,SUPER_NAME:this.superName},true))}var instanceProps;var staticProps;if(this.hasInstanceMutators){instanceProps=util.buildDefineProperties(this.instanceMutatorMap)}if(this.hasStaticMutators){staticProps=util.buildDefineProperties(this.staticMutatorMap)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addHelper("prototype-properties"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var kind=node.kind;if(kind===""){nameMethod.property(node,this.file,this.scope);if(this.isLoose){var className=this.className;if(!node.static)className=t.memberExpression(className,t.identifier("prototype"));methodName=t.memberExpression(className,methodName,node.computed);var expr=t.expressionStatement(t.assignmentExpression("=",methodName,node.value));t.inheritsComments(expr,node);this.body.push(expr);return}kind="value"}var mutatorMap=this.instanceMutatorMap;if(node.static){this.hasStaticMutators=true;mutatorMap=this.staticMutatorMap}else{this.hasInstanceMutators=true}util.pushMutatorMap(mutatorMap,methodName,kind,node.computed,node)};Class.prototype.pushConstructor=function(method){if(method.kind){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct._ignoreUserWhitespace=true;construct.params=fn.params; construct.body=fn.body}},{"../../../types":101,"../../../util":104,"../../helpers/name-method":32,"../../helpers/replace-supers":34}],56:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(t.isDeclaration(node)||t.isAssignmentExpression(node)){var ids=t.getIds(node,true);for(var key in ids){var id=ids[key];var constant=state.constants[key];if(!constant)continue;if(id===constant)continue;throw state.file.errorWithNode(id,key+" is read-only")}}else if(t.isScope(node)){context.skip()}}};exports.Scope=function(node,parent,scope,context,file){traverse(node,visitor,scope,{constants:scope.getAllOfKind("const"),file:file})};exports.VariableDeclaration=function(node){if(node.kind==="const")node.kind="let"}},{"../../../traverse":97,"../../../types":101}],57:[function(require,module,exports){"use strict";var t=require("../../../types");var buildVariableAssign=function(opts,id,init){var op=opts.operator;if(t.isMemberExpression(id))op="=";var node;if(op){node=t.expressionStatement(t.assignmentExpression(op,id,init))}else{node=t.variableDeclaration(opts.kind,[t.variableDeclarator(id,init)])}node._blockHoist=opts.blockHoist;return node};var buildVariableDeclar=function(opts,id,init){var declar=t.variableDeclaration("var",[t.variableDeclarator(id,init)]);declar._blockHoist=opts.blockHoist;return declar};var push=function(opts,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(opts,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(opts,nodes,elem,parentId)}else if(t.isAssignmentPattern(elem)){pushAssignmentPattern(opts,nodes,elem,parentId)}else{nodes.push(buildVariableAssign(opts,elem,parentId))}};var pushAssignmentPattern=function(opts,nodes,pattern,parentId){var tempParentId=opts.scope.generateUidBasedOnNode(parentId,opts.file);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(tempParentId,parentId)]));nodes.push(buildVariableAssign(opts,pattern.left,t.conditionalExpression(t.binaryExpression("===",tempParentId,t.identifier("undefined")),pattern.right,tempParentId)))};var pushObjectPattern=function(opts,nodes,pattern,parentId){for(var i=0;i<pattern.properties.length;i++){var prop=pattern.properties[i];if(t.isSpreadProperty(prop)){var keys=[];for(var i2=0;i2<pattern.properties.length;i2++){var prop2=pattern.properties[i2];if(i2>=i)break;if(t.isSpreadProperty(prop2))continue;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)}keys=t.arrayExpression(keys);var value=t.callExpression(opts.file.addHelper("object-without-properties"),[parentId,keys]);nodes.push(buildVariableAssign(opts,prop.argument,value))}else{if(t.isLiteral(prop.key))prop.computed=true;var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){push(opts,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(opts,pattern2,patternId2))}}}};var pushArrayPattern=function(opts,nodes,pattern,parentId){if(!pattern.elements)return;var i;var hasRest=false;for(i=0;i<pattern.elements.length;i++){if(t.isRestElement(pattern.elements[i])){hasRest=true;break}}var toArray=opts.file.toArray(parentId,!hasRest&&pattern.elements.length);var _parentId=opts.scope.generateUidBasedOnNode(parentId,opts.file);nodes.push(buildVariableDeclar(opts,_parentId,toArray));parentId=_parentId;for(i=0;i<pattern.elements.length;i++){var elem=pattern.elements[i];if(!elem)continue;i=+i;var newPatternId;if(t.isRestElement(elem)){newPatternId=opts.file.toArray(parentId);if(i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}push(opts,nodes,elem,newPatternId)}};var pushPattern=function(opts){var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var scope=opts.scope;if(!t.isArrayExpression(parentId)&&!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=scope.generateUidBasedOnNode(parentId);nodes.push(buildVariableDeclar(opts,key,parentId));parentId=key}push(opts,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,context,file){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=scope.generateUidIdentifier("ref");node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push({kind:declar.kind,file:file,scope:scope},nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,scope,context,file){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern,i){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=scope.generateUidIdentifier("ref");pushPattern({blockHoist:node.params.length-i,pattern:pattern,nodes:nodes,scope:scope,file:file,kind:"var",id:parentId});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.CatchClause=function(node,parent,scope,context,file){var pattern=node.param;if(!t.isPattern(pattern))return;var ref=scope.generateUidIdentifier("ref");node.param=ref;var nodes=[];push({kind:"var",file:file,scope:scope},nodes,pattern,ref);node.body.body=nodes.concat(node.body.body)};exports.ExpressionStatement=function(node,parent,scope,context,file){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;if(file.isConsequenceExpressionStatement(node))return;var nodes=[];var ref=scope.generateUidIdentifier("ref");nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push({operator:expr.operator,file:file,scope:scope},nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!t.isPattern(node.left))return;var ref=scope.generateUidIdentifier("temp");scope.push({key:ref.name,id:ref});var nodes=[];nodes.push(t.assignmentExpression("=",ref,node.right));push({operator:node.operator,file:file,scope:scope},nodes,node.left,ref);nodes.push(ref);return t.toSequenceExpression(nodes,scope)};exports.VariableDeclaration=function(node,parent,scope,context,file){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var i;var declar;var hasPattern=false;for(i=0;i<node.declarations.length;i++){declar=node.declarations[i];if(t.isPattern(declar.id)){hasPattern=true;break}}if(!hasPattern)return;for(i=0;i<node.declarations.length;i++){declar=node.declarations[i];var patternId=declar.init;var pattern=declar.id;var opts={pattern:pattern,nodes:nodes,scope:scope,kind:node.kind,file:file,id:patternId};if(t.isPattern(pattern)&&patternId){pushPattern(opts);if(+i!==node.declarations.length-1){t.inherits(nodes[nodes.length-1],declar)}}else{nodes.push(t.inherits(buildVariableAssign(opts,declar.id,declar.init),declar))}}if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){declar=null;for(i=0;i<nodes.length;i++){node=nodes[i];declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)}return declar}return nodes}},{"../../../types":101}],58:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.ForOfStatement=function(node,parent,scope,context,file){var callback=spec;if(file.isLoose("es6.forOf"))callback=loose;var build=callback(node,parent,scope,context,file);var declar=build.declar;var loop=build.loop;var block=loop.body;t.inheritsComments(loop,node);t.ensureBlock(node);if(declar){block.body.push(declar)}block.body=block.body.concat(node.body.body);loop._scopeInfo=node._scopeInfo;return loop};var loose=function(node,parent,scope,context,file){var left=node.left;var declar,id;if(t.isIdentifier(left)||t.isPattern(left)){id=left}else if(t.isVariableDeclaration(left)){id=scope.generateUidIdentifier("ref");declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,id)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var loop=util.template("for-of-loose",{LOOP_OBJECT:scope.generateUidIdentifier("iterator"),IS_ARRAY:scope.generateUidIdentifier("isArray"),OBJECT:node.right,INDEX:scope.generateUidIdentifier("i"),ID:id});if(!declar){loop.body.body.shift()}return{declar:declar,loop:loop}};var spec=function(node,parent,scope,context,file){var left=node.left;var declar;var stepKey=scope.generateUidIdentifier("step");var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)||t.isPattern(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var loop=util.template("for-of",{ITERATOR_KEY:scope.generateUidIdentifier("iterator"),STEP_KEY:stepKey,OBJECT:node.right});return{declar:declar,loop:loop}}},{"../../../types":101,"../../../util":104}],59:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ImportDeclaration=function(node,parent,scope,context,file){var nodes=[];if(node.specifiers.length){for(var i=0;i<node.specifiers.length;i++){file.moduleFormatter.importSpecifier(node.specifiers[i],node,nodes,parent)}}else{file.moduleFormatter.importDeclaration(node,nodes,parent)}if(nodes.length===1){nodes[0]._blockHoist=node._blockHoist}return nodes};exports.ExportDeclaration=function(node,parent,scope,context,file){var nodes=[];var i;if(node.declaration){if(t.isVariableDeclaration(node.declaration)){var declar=node.declaration.declarations[0];declar.init=declar.init||t.identifier("undefined")}file.moduleFormatter.exportDeclaration(node,nodes,parent)}else if(node.specifiers){for(i=0;i<node.specifiers.length;i++){file.moduleFormatter.exportSpecifier(node.specifiers[i],node,nodes,parent)}}if(node._blockHoist){for(i=0;i<nodes.length;i++){nodes[i]._blockHoist=node._blockHoist}}return nodes}},{"../../../types":101}],60:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var util=require("../../../util");var t=require("../../../types");var hasDefaults=function(node){for(var i=0;i<node.params.length;i++){if(t.isAssignmentPattern(node.params[i]))return true}return false};var iifeVisitor={enter:function(node,parent,scope,context,state){if(t.isReferencedIdentifier(node,parent)&&scope.hasOwn(node.name)){state.iife=true;context.stop()}}};exports.Function=function(node,parent,scope){if(!hasDefaults(node))return;t.ensureBlock(node);var body=[];var argsIdentifier=t.identifier("arguments");argsIdentifier._ignoreAliasFunctions=true;var lastNonDefaultParam=0;var state={iife:false,scope:scope};for(var i=0;i<node.params.length;i++){var param=node.params[i];if(!t.isAssignmentPattern(param)){lastNonDefaultParam=+i+1;continue}var left=param.left;var right=param.right;node.params[i]=scope.generateUidIdentifier("x");if(!state.iife){if(t.isIdentifier(right)&&scope.hasOwn(right.name)){state.iife=true}else{traverse(right,iifeVisitor,scope,state)}}var defNode=util.template("default-parameter",{VARIABLE_NAME:left,DEFAULT_VALUE:right,ARGUMENT_KEY:t.literal(+i),ARGUMENTS:argsIdentifier},true);defNode._blockHoist=node.params.length-i;body.push(defNode)}node.params=node.params.slice(0,lastNonDefaultParam);if(state.iife){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}}},{"../../../traverse":97,"../../../types":101,"../../../util":104}],61:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");var hasRest=function(node){return t.isRestElement(node.params[node.params.length-1])};exports.Function=function(node,parent,scope){if(!hasRest(node))return;var rest=node.params.pop().argument;var argsId=t.identifier("arguments");argsId._ignoreAliasFunctions=true;var start=t.literal(node.params.length);var key=scope.generateUidIdentifier("key");var len=scope.generateUidIdentifier("len");var arrKey=key;var arrLen=len;if(node.params.length){arrKey=t.binaryExpression("-",key,start);arrLen=t.conditionalExpression(t.binaryExpression(">",len,start),t.binaryExpression("-",len,start),t.literal(0))}if(t.isPattern(rest)){var pattern=rest;rest=scope.generateUidIdentifier("ref");var restDeclar=t.variableDeclaration("var",[t.variableDeclarator(pattern,rest)]);restDeclar._blockHoist=node.params.length+1;node.body.body.unshift(restDeclar)}node.body.body.unshift(util.template("rest",{ARGUMENTS:argsId,ARRAY_KEY:arrKey,ARRAY_LEN:arrLen,START:start,ARRAY:rest,KEY:key,LEN:len}))}},{"../../../types":101,"../../../util":104}],62:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ObjectExpression=function(node,parent,scope,context,file){var hasComputed=false;for(var i=0;i<node.properties.length;i++){hasComputed=t.isProperty(node.properties[i],{computed:true,kind:"init"});if(hasComputed)break}if(!hasComputed)return;var initProps=[];var objId=scope.generateUidBasedOnNode(parent);var body=[];var container=t.functionExpression(null,[],t.blockStatement(body));container._aliasFunction=true;var callback=spec;if(file.isLoose("es6.properties.computed"))callback=loose;var result=callback(node,body,objId,initProps,file);if(result)return result;body.unshift(t.variableDeclaration("var",[t.variableDeclarator(objId,t.objectExpression(initProps))]));body.push(t.returnStatement(objId));return t.callExpression(container,[])};var loose=function(node,body,objId){for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];body.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,prop.computed),prop.value)))}};var spec=function(node,body,objId,initProps,file){var props=node.properties;var prop,key;for(var i=0;i<props.length;i++){prop=props[i];if(prop.kind!=="init")continue;key=prop.key;if(!prop.computed&&t.isIdentifier(key)){prop.key=t.literal(key.name)}}var broken=false;for(i=0;i<props.length;i++){prop=props[i];if(prop.computed){broken=true}if(prop.kind!=="init"||!broken||t.isLiteral(t.toComputedKey(prop,prop.key),{value:"__proto__"})){initProps.push(prop);props[i]=null}}for(i=0;i<props.length;i++){prop=props[i];if(!prop)continue;key=prop.key;var bodyNode;if(prop.computed&&t.isMemberExpression(key)&&t.isIdentifier(key.object,{name:"Symbol"})){bodyNode=t.assignmentExpression("=",t.memberExpression(objId,key,true),prop.value)}else{bodyNode=t.callExpression(file.addHelper("define-property"),[objId,key,prop.value])}body.push(t.expressionStatement(bodyNode))}if(body.length===1){var first=body[0].expression;if(t.isCallExpression(first)){first.arguments[0]=t.objectExpression(initProps);return first}}}},{"../../../types":101}],63:[function(require,module,exports){"use strict";var nameMethod=require("../../helpers/name-method");var t=require("../../../types");var _=require("lodash");exports.Property=function(node,parent,scope,context,file){if(node.method){node.method=false;nameMethod.property(node,file,scope)}if(node.shorthand){node.shorthand=false;node.key=t.removeComments(_.clone(node.key))}}},{"../../../types":101,"../../helpers/name-method":32,lodash:168}],64:[function(require,module,exports){"use strict";var t=require("../../../types");var _=require("lodash");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){for(var i=0;i<nodes.length;i++){if(t.isSpreadElement(nodes[i])){return true}}return false};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};for(var i=0;i<props.length;i++){var prop=props[i];if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,file))}else{_props.push(prop)}}push();return nodes};exports.ArrayExpression=function(node,parent,scope,context,file){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,file);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,scope,context,file){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.identifier("undefined");node.arguments=[];var nodes;if(args.length===1&&args[0].argument.name==="arguments"){nodes=[args[0].argument]}else{nodes=build(args,file)}var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){var temp=scope.generateTempBasedOnNode(callee.object);if(temp){callee.object=t.assignmentExpression("=",temp,callee.object);contextLiteral=temp}else{contextLiteral=callee.object}t.appendToMemberExpression(callee,t.identifier("apply"))}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,scope,context,file){var args=node.arguments;if(!hasSpread(args))return;var nativeType=t.isIdentifier(node.callee)&&_.contains(t.NATIVE_TYPE_NAMES,node.callee.name);var nodes=build(args,file);if(nativeType){nodes.unshift(t.arrayExpression([t.literal(null)]))}var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}if(nativeType){return t.newExpression(t.callExpression(t.memberExpression(file.addHelper("bind"),t.identifier("apply")),[node.callee,args]),[])}else{return t.callExpression(file.addHelper("apply-constructor"),[node.callee,args])}}},{"../../../types":101,lodash:168}],65:[function(require,module,exports){"use strict";var t=require("../../../types");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,scope,context,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];for(var i=0;i<quasi.quasis.length;i++){var elem=quasi.quasis[i];strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))}strings=t.arrayExpression(strings);raw=t.arrayExpression(raw);var templateName="tagged-template-literal";if(file.isLoose("es6.templateLiterals"))templateName+="-loose";args.push(t.callExpression(file.addHelper(templateName),[strings,raw]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];var i;for(i=0;i<node.quasis.length;i++){var elem=node.quasis[i];nodes.push(t.literal(elem.value.cooked));var expr=node.expressions.shift();if(expr)nodes.push(expr)}if(nodes.length>1){var last=nodes[nodes.length-1];if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());for(i=0;i<nodes.length;i++){root=buildBinaryExpression(root,nodes[i])}return root}else{return nodes[0]}}},{"../../../types":101}],66:[function(require,module,exports){"use strict";var rewritePattern=require("regexpu/rewrite-pattern");var _=require("lodash");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(regex.flags.indexOf("u")<0)return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:168,"regexpu/rewrite-pattern":184}],67:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.experimental=true;var container=function(parent,call,ret,file){if(t.isExpressionStatement(parent)&&!file.isConsequenceExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,scope,context,file){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){temp=scope.generateTempBasedOnNode(node.right);if(temp)value=temp}if(node.operator!=="="){value=t.binaryExpression(node.operator[0],util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object}),value)}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value,file)};exports.UnaryExpression=function(node,parent,scope,context,file){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true),file)};exports.CallExpression=function(node,parent,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp=scope.generateTempBasedOnNode(callee.object);var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})};exports.PrivateDeclaration=function(node){return t.variableDeclaration("const",node.declarations.map(function(id){return t.variableDeclarator(id,t.newExpression(t.identifier("WeakMap"),[]))}))}},{"../../../types":101,"../../../util":104}],68:[function(require,module,exports){"use strict";var buildComprehension=require("../../helpers/build-comprehension");var traverse=require("../../../traverse");var util=require("../../../util");var t=require("../../../types");exports.experimental=true;exports.ComprehensionExpression=function(node,parent,scope,context,file){var callback=array;if(node.generator)callback=generator;return callback(node,parent,scope,file)};var generator=function(node){var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);container._aliasFunction=true;body.push(buildComprehension(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])};var array=function(node,parent,scope,file){var uid=scope.generateUidBasedOnNode(parent,file);var container=util.template("array-comprehension-container",{KEY:uid});container.callee._aliasFunction=true;var block=container.callee.body;var body=block.body;if(traverse.hasType(node,scope,"YieldExpression",t.FUNCTION_TYPES)){container.callee.generator=true;container=t.yieldExpression(container,true)}var returnStatement=body.pop();body.push(buildComprehension(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container}},{"../../../traverse":97,"../../../types":101,"../../../util":104,"../../helpers/build-comprehension":29}],69:[function(require,module,exports){"use strict";exports.experimental=true;var build=require("../../helpers/build-binary-assignment-operator-transformer");var t=require("../../../types");var MATH_POW=t.memberExpression(t.identifier("Math"),t.identifier("pow"));build(exports,{operator:"**",build:function(left,right){return t.callExpression(MATH_POW,[left,right])}})},{"../../../types":101,"../../helpers/build-binary-assignment-operator-transformer":28}],70:[function(require,module,exports){"use strict";var t=require("../../../types");exports.experimental=true;exports.ObjectExpression=function(node,parent,scope,context,file){var hasSpread=false;var i;var prop;for(i=0;i<node.properties.length;i++){prop=node.properties[i];if(t.isSpreadProperty(prop)){hasSpread=true;break}}if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};for(i=0;i<node.properties.length;i++){prop=node.properties[i];if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}}push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(file.addHelper("extends"),args)}},{"../../../types":101}],71:[function(require,module,exports){module.exports={useStrict:require("./other/use-strict"),"validation.undeclaredVariableCheck":require("./validation/undeclared-variable-check"),"validation.noForInOfAssignment":require("./validation/no-for-in-of-assignment"),"validation.setters":require("./validation/setters"),"spec.blockScopedFunctions":require("./spec/block-scoped-functions"),"playground.malletOperator":require("./playground/mallet-operator"),"playground.methodBinding":require("./playground/method-binding"),"playground.memoizationOperator":require("./playground/memoization-operator"),"playground.objectGetterMemoization":require("./playground/object-getter-memoization"),react:require("./other/react"),_modulesSplit:require("./internal/modules-split"),"es7.comprehensions":require("./es7/comprehensions"),"es6.arrowFunctions":require("./es6/arrow-functions"),"es6.classes":require("./es6/classes"),asyncToGenerator:require("./other/async-to-generator"),bluebirdCoroutines:require("./other/bluebird-coroutines"),"es7.objectSpread":require("./es7/object-spread"),"es7.exponentiationOperator":require("./es7/exponentiation-operator"),"es6.spread":require("./es6/spread"),"es6.templateLiterals":require("./es6/template-literals"),"es5.properties.mutators":require("./es5/properties.mutators"),"es6.properties.shorthand":require("./es6/properties.shorthand"),"es6.properties.computed":require("./es6/properties.computed"),"es6.forOf":require("./es6/for-of"),"es6.unicodeRegex":require("./es6/unicode-regex"),"es7.abstractReferences":require("./es7/abstract-references"),"es6.constants":require("./es6/constants"),"es6.blockScoping":require("./es6/block-scoping"),"es6.blockScopingTDZ":require("./es6/block-scoping-tdz"),regenerator:require("./other/regenerator"),"es6.parameters.default":require("./es6/parameters.default"),"es6.parameters.rest":require("./es6/parameters.rest"),"es6.destructuring":require("./es6/destructuring"),selfContained:require("./other/self-contained"),"es6.modules":require("./es6/modules"),_blockHoist:require("./internal/block-hoist"),"spec.protoToAssign":require("./spec/proto-to-assign"),_declarations:require("./internal/declarations"),_aliasFunctions:require("./internal/alias-functions"),_moduleFormatter:require("./internal/module-formatter"),"spec.typeofSymbol":require("./spec/typeof-symbol"),"spec.undefinedToVoid":require("./spec/undefined-to-void"),"minification.propertyLiterals":require("./minification/property-literals"),"minification.memberExpressionLiterals":require("./minification/member-expression-literals")}},{"./es5/properties.mutators":51,"./es6/arrow-functions":52,"./es6/block-scoping":54,"./es6/block-scoping-tdz":53,"./es6/classes":55,"./es6/constants":56,"./es6/destructuring":57,"./es6/for-of":58,"./es6/modules":59,"./es6/parameters.default":60,"./es6/parameters.rest":61,"./es6/properties.computed":62,"./es6/properties.shorthand":63,"./es6/spread":64,"./es6/template-literals":65,"./es6/unicode-regex":66,"./es7/abstract-references":67,"./es7/comprehensions":68,"./es7/exponentiation-operator":69,"./es7/object-spread":70,"./internal/alias-functions":72,"./internal/block-hoist":73,"./internal/declarations":74,"./internal/module-formatter":75,"./internal/modules-split":76,"./minification/member-expression-literals":77,"./minification/property-literals":78,"./other/async-to-generator":79,"./other/bluebird-coroutines":80,"./other/react":81,"./other/regenerator":82,"./other/self-contained":83,"./other/use-strict":84,"./playground/mallet-operator":85,"./playground/memoization-operator":86,"./playground/method-binding":87,"./playground/object-getter-memoization":88,"./spec/block-scoped-functions":89,"./spec/proto-to-assign":90,"./spec/typeof-symbol":91,"./spec/undefined-to-void":92,"./validation/no-for-in-of-assignment":93,"./validation/setters":94,"./validation/undeclared-variable-check":95}],72:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var functionChildrenVisitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node)&&!node._aliasFunction){return context.skip()}if(node._ignoreAliasFunctions)return context.skip();var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=state.getArgumentsId}else if(t.isThisExpression(node)){getId=state.getThisId}else{return}if(t.isReferenced(node,parent))return getId()}};var functionVisitor={enter:function(node,parent,scope,context,state){if(!node._aliasFunction){if(t.isFunction(node)){return context.skip()}else{return}}traverse(node,functionChildrenVisitor,scope,state);return context.skip()}};var go=function(getBody,node,scope){var argumentsId;var thisId;var state={getArgumentsId:function(){return argumentsId=argumentsId||scope.generateUidIdentifier("arguments")},getThisId:function(){return thisId=thisId||scope.generateUidIdentifier("this")}};traverse(node,functionVisitor,scope,state);var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.thisExpression())}};exports.Program=function(node,parent,scope){go(function(){return node.body},node,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,scope){go(function(){t.ensureBlock(node);return node.body.body},node,scope)}},{"../../../traverse":97,"../../../types":101}],73:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var _=require("lodash");exports.BlockStatement=exports.Program={exit:function(node){var hasChange=false;for(var i=0;i<node.body.length;i++){var bodyNode=node.body[i];if(bodyNode&&bodyNode._blockHoist!=null)hasChange=true}if(!hasChange)return;useStrict.wrap(node,function(){var nodePriorities=_.groupBy(node.body,function(bodyNode){var priority=bodyNode._blockHoist;if(priority==null)priority=1;if(priority===true)priority=2;return priority});node.body=_.flatten(_.values(nodePriorities).reverse())})}}},{"../../helpers/use-strict":35,lodash:168}],74:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.secondPass=true;exports.BlockStatement=exports.Program=function(node){if(!node._declarations)return;var kinds={};var kind;useStrict.wrap(node,function(){for(var i in node._declarations){var declar=node._declarations[i];kind=declar.kind||"var";var declarNode=t.variableDeclarator(declar.id,declar.init);if(!declar.init){kinds[kind]=kinds[kind]||[];kinds[kind].push(declarNode)}else{node.body.unshift(t.variableDeclaration(kind,[declarNode]))}}for(kind in kinds){node.body.unshift(t.variableDeclaration(kind,kinds[kind]))}});node._declarations=null}},{"../../../types":101,"../../helpers/use-strict":35}],75:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");exports.ast={exit:function(ast,file){if(!file.transformers["es6.modules"].canRun())return;useStrict.wrap(ast.program,function(){ast.program.body=file.dynamicImports.concat(ast.program.body)}); if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../../helpers/use-strict":35}],76:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ExportDeclaration=function(node,parent,scope){var declar=node.declaration;if(node.default){if(t.isClassDeclaration(declar)){node.declaration=declar.id;return[declar,node]}else if(t.isClassExpression(declar)){var temp=scope.generateUidIdentifier("default");declar=t.variableDeclaration("var",[t.variableDeclarator(temp,declar)]);node.declaration=temp;return[declar,node]}else if(t.isFunctionDeclaration(declar)){node._blockHoist=2;node.declaration=declar.id;return[declar,node]}}else{if(t.isFunctionDeclaration(declar)){node.specifiers=[t.importSpecifier(declar.id,declar.id)];node.declaration=null;node._blockHoist=2;return[declar,node]}}}},{"../../../types":101}],77:[function(require,module,exports){"use strict";var t=require("../../../types");exports.MemberExpression=function(node){var prop=node.property;if(node.computed&&t.isLiteral(prop)&&t.isValidIdentifier(prop.value)){node.property=t.identifier(prop.value);node.computed=false}else if(!node.computed&&t.isIdentifier(prop)&&!t.isValidIdentifier(prop.name)){node.property=t.literal(prop.name);node.computed=true}}},{"../../../types":101}],78:[function(require,module,exports){"use strict";var t=require("../../../types");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&t.isValidIdentifier(key.value)){node.key=t.identifier(key.value);node.computed=false}else if(!node.computed&&t.isIdentifier(key)&&!t.isValidIdentifier(key.name)){node.key=t.literal(key.name)}}},{"../../../types":101}],79:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var bluebirdCoroutines=require("./bluebird-coroutines");exports.optional=true;exports.manipulateOptions=bluebirdCoroutines.manipulateOptions;exports.Function=function(node,parent,scope,context,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,file.addHelper("async-to-generator"),scope)}},{"../../helpers/remap-async-to-generator":33,"./bluebird-coroutines":80}],80:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var t=require("../../../types");exports.manipulateOptions=function(opts){opts.experimental=true;opts.blacklist.push("regenerator")};exports.optional=true;exports.Function=function(node,parent,scope,context,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,t.memberExpression(file.addImport("bluebird"),t.identifier("coroutine")),scope)}},{"../../../types":101,"../../helpers/remap-async-to-generator":33}],81:[function(require,module,exports){"use strict";var esutils=require("esutils");var t=require("../../../types");exports.JSXIdentifier=function(node){if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.JSXNamespacedName=function(node,parent,scope,context,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.JSXMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.JSXExpressionContainer=function(node){return node.expression};exports.JSXAttribute={exit:function(node){var value=node.value||t.literal(true);return t.inherits(t.property("init",node.name,value),node)}};var isCompatTag=function(tagName){return/^[a-z]|\-/.test(tagName)};exports.JSXOpeningElement={exit:function(node,parent,scope,context,file){var reactCompat=file.opts.reactCompat;var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(!reactCompat){if(tagName&&isCompatTag(tagName)){args.push(t.literal(tagName))}else{args.push(tagExpr)}}var attribs=node.attributes;if(attribs.length){attribs=buildJSXOpeningElementAttributes(attribs,file)}else{attribs=t.literal(null)}args.push(attribs);if(reactCompat){if(tagName&&isCompatTag(tagName)){return t.callExpression(t.memberExpression(t.memberExpression(t.identifier("React"),t.identifier("DOM")),tagExpr,t.isLiteral(tagExpr)),args)}}else{tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"))}return t.callExpression(tagExpr,args)}};var buildJSXOpeningElementAttributes=function(attribs,file){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(attribs.length){var prop=attribs.shift();if(t.isJSXSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){attribs=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}attribs=t.callExpression(file.addHelper("extends"),objs)}return attribs};exports.JSXElement={exit:function(node){var callExpr=node.openingElement;for(var i=0;i<node.children.length;i++){var child=node.children[i];if(t.isLiteral(child)&&typeof child.value==="string"){cleanJSXElementLiteralChild(child,callExpr.arguments);continue}else if(t.isJSXEmptyExpression(child)){continue}callExpr.arguments.push(child)}if(callExpr.arguments.length>=3){callExpr._prettyCall=true}return t.inherits(callExpr,node)}};var cleanJSXElementLiteralChild=function(child,args){var lines=child.value.split(/\r\n|\n|\r/);for(var i=0;i<lines.length;i++){var line=lines[i];var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){args.push(t.literal(trimmedLine))}}};var isCreateClass=function(call){if(!call||!t.isCallExpression(call))return false;var callee=call.callee;if(!t.isMemberExpression(callee))return false;var obj=callee.object;if(!t.isIdentifier(obj,{name:"React"}))return false;var prop=callee.property;if(!t.isIdentifier(prop,{name:"createClass"}))return false;var args=call.arguments;if(args.length!==1)return false;var first=args[0];if(!t.isObjectExpression(first))return;return true};var addDisplayName=function(id,call){if(!isCreateClass(call))return;var props=call.arguments[0].properties;var safe=true;for(var i=0;i<props.length;i++){var prop=props[i];if(t.isIdentifier(prop.key,{name:"displayName"})){safe=false;break}}if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../../types":101,esutils:166}],82:[function(require,module,exports){"use strict";var regenerator=require("regenerator-6to5");exports.ast={before:function(ast,file){regenerator.transform(ast,{includeRuntime:file.opts.includeRegenerator&&"if used"})}}},{"regenerator-6to5":176}],83:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var util=require("../../../util");var core=require("core-js/library");var t=require("../../../types");var _=require("lodash");var coreHas=function(node){return node.name!=="_"&&_.has(core,node.name)};var ALIASABLE_CONSTRUCTORS=["Symbol","Promise","Map","WeakMap","Set","WeakSet"];var astVisitor={enter:function(node,parent,scope,context,file){var prop;if(t.isMemberExpression(node)&&t.isReferenced(node,parent)){var obj=node.object;prop=node.property;if(!t.isReferenced(obj,node))return;if(!node.computed&&coreHas(obj)&&_.has(core[obj.name],prop.name)){context.skip();return t.prependToMemberExpression(node,file.get("coreIdentifier"))}}else if(t.isReferencedIdentifier(node,parent)&&!t.isMemberExpression(parent)&&_.contains(ALIASABLE_CONSTRUCTORS,node.name)&&!scope.get(node.name,true)){return t.memberExpression(file.get("coreIdentifier"),node)}else if(t.isCallExpression(node)){if(node.arguments.length)return;var callee=node.callee;if(!t.isMemberExpression(callee))return;if(!callee.computed)return;prop=callee.property;if(!t.isIdentifier(prop.object,{name:"Symbol"}))return;if(!t.isIdentifier(prop.property,{name:"iterator"}))return;return util.template("corejs-iterator",{CORE_ID:file.get("coreIdentifier"),VALUE:callee.object})}}};exports.optional=true;exports.ast={enter:function(ast,file){file.setDynamic("runtimeIdentifier",function(){return file.addImport("6to5-runtime/helpers","to5Helpers")});file.setDynamic("coreIdentifier",function(){return file.addImport("6to5-runtime/core-js","core")});file.setDynamic("regeneratorIdentifier",function(){return file.addImport("6to5-runtime/regenerator","regeneratorRuntime")})},after:function(ast,file){traverse(ast,astVisitor,null,file)}};exports.Identifier=function(node,parent,scope,context,file){if(node.name==="regeneratorRuntime"&&t.isReferenced(node,parent)){return file.get("regeneratorIdentifier")}}},{"../../../traverse":97,"../../../types":101,"../../../util":104,"core-js/library":155,lodash:168}],84:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.ast={exit:function(ast){if(!useStrict.has(ast.program)){ast.program.body.unshift(t.expressionStatement(t.literal("use strict")))}}};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,scope,context){context.skip()};exports.ThisExpression=function(node,parent,scope,context,file){throw file.errorWithNode(node,"Top level `this` is not allowed",ReferenceError)}},{"../../../types":101,"../../helpers/use-strict":35}],85:[function(require,module,exports){"use strict";var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");build(exports,{is:function(node,file){var is=t.isAssignmentExpression(node)&&node.operator==="||=";if(is){var left=node.left;if(!t.isMemberExpression(left)&&!t.isIdentifier(left)){throw file.errorWithNode(left,"Expected type MemeberExpression or Identifier")}return true}},build:function(node){return t.unaryExpression("!",node,true)}})},{"../../../types":101,"../../helpers/build-conditional-assignment-operator-transformer":30}],86:[function(require,module,exports){"use strict";var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");build(exports,{is:function(node){var is=t.isAssignmentExpression(node)&&node.operator==="?=";if(is)t.assertMemberExpression(node.left);return is},build:function(node,file){return t.unaryExpression("!",t.callExpression(t.memberExpression(file.addHelper("has-own"),t.identifier("call")),[node.object,node.property]),true)}})},{"../../../types":101,"../../helpers/build-conditional-assignment-operator-transformer":30}],87:[function(require,module,exports){"use strict";var t=require("../../../types");exports.BindMemberExpression=function(node,parent,scope){var object=node.object;var prop=node.property;var temp=scope.generateTempBasedOnNode(node.object);if(temp)object=temp;var call=t.callExpression(t.memberExpression(t.memberExpression(object,prop),t.identifier("bind")),[object].concat(node.arguments));if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,node.object),call])}else{return call}};exports.BindFunctionExpression=function(node,parent,scope,context,file){var buildCall=function(args){var param=scope.generateUidIdentifier("val");return t.functionExpression(null,[param],t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(param,node.callee),args))]))};var temp=scope.generateTemp(file,"args");return t.sequenceExpression([t.assignmentExpression("=",temp,t.arrayExpression(node.arguments)),buildCall(node.arguments.map(function(node,i){return t.memberExpression(temp,t.literal(i),true)}))])}},{"../../../types":101}],88:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node))return;if(t.isReturnStatement(node)&&node.argument){node.argument=t.memberExpression(t.callExpression(state.file.addHelper("define-property"),[t.thisExpression(),state.key,node.argument]),state.key,true)}}};exports.Property=exports.MethodDefinition=function(node,parent,scope,context,file){if(node.kind!=="memo")return;node.kind="get";var value=node.value;t.ensureBlock(value);var key=node.key;if(t.isIdentifier(key)&&!node.computed){key=t.literal(key.name)}var state={key:key,file:file};traverse(value,visitor,scope,state)}},{"../../../traverse":97,"../../../types":101}],89:[function(require,module,exports){"use strict";var t=require("../../../types");exports.BlockStatement=function(node,parent){if(t.isFunction(parent)||t.isExportDeclaration(parent)){return}for(var i=0;i<node.body.length;i++){var func=node.body[i];if(!t.isFunctionDeclaration(i))continue;var declar=t.variableDeclaration("let",[t.variableDeclarator(func.id,t.toExpression(func))]);declar._blockHoist=2;func.id=null;func.body[i]=declar}}},{"../../../types":101}],90:[function(require,module,exports){"use strict";var t=require("../../../types");var _=require("lodash");var isProtoKey=function(node){return t.isLiteral(t.toComputedKey(node,node.key),{value:"__proto__"})};var isProtoAssignmentExpression=function(node){var left=node.left;return t.isMemberExpression(left)&&t.isLiteral(t.toComputedKey(left,left.property),{value:"__proto__"})};var buildDefaultsCallExpression=function(expr,ref,file){return t.expressionStatement(t.callExpression(file.addHelper("defaults"),[ref,expr.right]))};exports.optional=true;exports.secondPass=true;exports.AssignmentExpression=function(node,parent,scope,context,file){if(!isProtoAssignmentExpression(node))return;var nodes=[];var left=node.left.object;var temp=scope.generateTempBasedOnNode(node.left.object);nodes.push(t.expressionStatement(t.assignmentExpression("=",temp,left)));nodes.push(buildDefaultsCallExpression(node,temp,file));if(temp)nodes.push(temp);return t.toSequenceExpression(nodes)};exports.ExpressionStatement=function(node,parent,scope,context,file){var expr=node.expression;if(!t.isAssignmentExpression(expr,{operator:"="}))return;if(isProtoAssignmentExpression(expr)){return buildDefaultsCallExpression(expr,expr.left.object,file)}};exports.ObjectExpression=function(node,parent,scope,context,file){var proto;for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(isProtoKey(prop)){proto=prop.value;_.pull(node.properties,prop)}}if(proto){var args=[t.objectExpression([]),proto];if(node.properties.length)args.push(node);return t.callExpression(file.addHelper("extends"),args)}}},{"../../../types":101,lodash:168}],91:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.UnaryExpression=function(node,parent,scope,context,file){context.skip();if(node.operator==="typeof"){var call=t.callExpression(file.addHelper("typeof"),[node.argument]);if(t.isIdentifier(node.argument)){var undefLiteral=t.literal("undefined");return t.conditionalExpression(t.binaryExpression("===",t.unaryExpression("typeof",node.argument),undefLiteral),undefLiteral,call)}else{return call}}}},{"../../../types":101}],92:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.Identifier=function(node,parent){if(node.name==="undefined"&&t.isReferenced(node,parent)){return t.unaryExpression("void",t.literal(0),true)}}},{"../../../types":101}],93:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,context,file){var left=node.left;if(t.isVariableDeclaration(left)){var declar=left.declarations[0];if(declar.init)throw file.errorWithNode(declar,"No assignments allowed in for-in/of head")}}},{"../../../types":101}],94:[function(require,module,exports){"use strict";exports.MethodDefinition=exports.Property=function(node,parent,scope,context,file){if(node.kind==="set"&&node.value.params.length!==1){throw file.errorWithNode(node.value,"Setters must have only one parameter")}}},{}],95:[function(require,module,exports){"use strict";exports.optional=true;exports.Identifier=function(node,parent,scope,context,file){if(!scope.has(node.name,true)){throw file.errorWithNode(node,"Reference to undeclared variable",ReferenceError)}}},{}],96:[function(require,module,exports){module.exports=["Set","Map","WeakMap","WeakSet","Proxy","Promise","Reflect","Symbol","System","__filename","__dirname","GLOBAL","global","module","require","Buffer","console","exports","process","setTimeout","clearTimeout","setInterval","clearInterval","setImmediate","clearImmediate","Array","Boolean","Date","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","Error","eval","EvalError","Function","hasOwnProperty","isFinite","isNaN","JSON","Map","Math","Number","Object","Proxy","Promise","parseInt","parseFloat","RangeError","ReferenceError","RegExp","Set","String","SyntaxError","TypeError","URIError","WeakMap","WeakSet","arguments","NaN","window","self"]},{}],97:[function(require,module,exports){"use strict";module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function TraversalContext(){this.shouldFlatten=false;this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false}TraversalContext.prototype.flatten=function(){this.shouldFlatten=true};TraversalContext.prototype.remove=function(){this.shouldRemove=true;this.shouldSkip=true};TraversalContext.prototype.skip=function(){this.shouldSkip=true};TraversalContext.prototype.stop=function(){this.shouldStop=true;this.shouldSkip=true};TraversalContext.prototype.reset=function(){this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false};function replaceNode(obj,key,node,result){var isArray=Array.isArray(result);var inheritTo=result;if(isArray)inheritTo=result[0];if(inheritTo)t.inheritsComments(inheritTo,node);obj[key]=result;if(isArray&&_.contains(t.STATEMENT_OR_BLOCK_KEYS,key)&&!t.isBlockStatement(obj)){t.ensureBlock(obj,key)}if(isArray){return true}}TraversalContext.prototype.enterNode=function(obj,key,node,enter,parent,scope,state){var result=enter(node,parent,scope,this,state);var flatten=false;if(result){flatten=replaceNode(obj,key,node,result);node=result;if(flatten){this.shouldFlatten=true}}if(this.shouldRemove){obj[key]=null;this.shouldFlatten=true}return node};TraversalContext.prototype.exitNode=function(obj,key,node,exit,parent,scope,state){var result=exit(node,parent,scope,this,state);var flatten=false;if(result){flatten=replaceNode(obj,key,node,result);node=result;if(flatten){this.shouldFlatten=true}}return node};TraversalContext.prototype.visitNode=function(obj,key,opts,scope,parent,state){this.reset();var node=obj[key];if(opts.blacklist&&opts.blacklist.indexOf(node.type)>-1){return}var ourScope=scope;if(!opts.noScope&&t.isScope(node)){ourScope=new Scope(node,parent,scope)}node=this.enterNode(obj,key,node,opts.enter,parent,ourScope,state);if(this.shouldSkip){return this.shouldStop}if(Array.isArray(node)){for(var i=0;i<node.length;i++){traverseNode(node[i],opts,ourScope,state)}}else{traverseNode(node,opts,ourScope,state);this.exitNode(obj,key,node,opts.exit,parent,ourScope,state)}return this.shouldStop};TraversalContext.prototype.visit=function(node,key,opts,scope,state){var nodes=node[key];if(!nodes)return;if(!Array.isArray(nodes)){return this.visitNode(node,key,opts,scope,node,state)}if(nodes.length===0){return}for(var i=0;i<nodes.length;i++){if(nodes[i]&&this.visitNode(nodes,i,opts,scope,node,state)){return true}}if(this.shouldFlatten){node[key]=_.flatten(node[key]);if(key==="body"){node[key]=_.compact(node[key])}}};function traverseNode(node,opts,scope,state){var keys=t.VISITOR_KEYS[node.type];if(!keys)return;var context=new TraversalContext;for(var i=0;i<keys.length;i++){if(context.visit(node,keys[i],opts,scope,state)){return}}}function traverse(parent,opts,scope,state){if(!parent)return;if(!opts.noScope&&!scope){if(parent.type!=="Program"&&parent.type!=="File"){throw new Error("Must pass a scope unless traversing a Program/File got a "+parent.type+" node")}}if(!opts)opts={};if(!opts.enter)opts.enter=_.noop;if(!opts.exit)opts.exit=_.noop;if(Array.isArray(parent)){for(var i=0;i<parent.length;i++){traverseNode(parent[i],opts,scope,state)}}else{traverseNode(parent,opts,scope,state)}}function clearNode(node){node._declarations=null;node.extendedRange=null;node._scopeInfo=null;node.tokens=null;node.range=null;node.start=null;node.end=null;node.loc=null;node.raw=null;if(Array.isArray(node.trailingComments)){clearComments(node.trailingComments)}if(Array.isArray(node.leadingComments)){clearComments(node.leadingComments)}}var clearVisitor={noScope:true,enter:clearNode};function clearComments(comments){for(var i=0;i<comments.length;i++){clearNode(comments[i])}}traverse.removeProperties=function(tree){clearNode(tree);traverse(tree,clearVisitor);return tree};function hasBlacklistedType(node,parent,scope,context,state){if(node.type===state.type){state.has=true;context.skip()}}traverse.hasType=function(tree,scope,type,blacklistTypes){if(_.contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;var state={has:false,type:type};traverse(tree,{blacklist:blacklistTypes,enter:hasBlacklistedType},scope,state);return state.has}},{"../types":101,"./scope":98,lodash:168}],98:[function(require,module,exports){"use strict";module.exports=Scope;var traverse=require("./index");var object=require("../helpers/object");var t=require("../types");var _=require("lodash");var FOR_KEYS=["left","init"];function Scope(block,parentBlock,parent,file){this.parent=parent;this.file=parent?parent.file:file;this.parentBlock=parentBlock;this.block=block;var info=this.getInfo();this.references=info.references;this.declarations=info.declarations;this.declarationKinds=info.declarationKinds}Scope.defaultDeclarations=require("./global-keys");Scope.prototype._add=function(node,references,throwOnDuplicate){if(!node)return;var ids=t.getIds(node,true);for(var key in ids){var id=ids[key];if(throwOnDuplicate&&references[key]){throw this.file.errorWithNode(id,"Duplicate declaration",TypeError)}references[key]=id}};Scope.prototype.generateTemp=function(file,name){var id=file.generateUidIdentifier(name||"temp",this);this.push({key:id.name,id:id});return id};Scope.prototype.generateUidIdentifier=function(name){return this.file.generateUidIdentifier(name,this)};Scope.prototype.generateUidBasedOnNode=function(parent){var node=parent;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}else if(t.isProperty(node)){node=node.key}var parts=[];var add=function(node){if(t.isMemberExpression(node)){add(node.object);add(node.property)}else if(t.isIdentifier(node)){parts.push(node.name)}else if(t.isLiteral(node)){parts.push(node.value)}else if(t.isCallExpression(node)){add(node.callee)}};add(node);var id=parts.join("$");id=id.replace(/^_/,"")||"ref";return this.file.generateUidIdentifier(id,this)};Scope.prototype.generateTempBasedOnNode=function(node){if(t.isIdentifier(node)&&this.has(node.name,true)){return null}var id=this.generateUidBasedOnNode(node);this.push({key:id.name,id:id});return id};var functionVariableVisitor={enter:function(node,parent,scope,context,state){if(t.isFor(node)){_.each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))state.add(declar)})}if(t.isFunction(node))return context.skip();if(state.blockId&&node===state.blockId)return;if(t.isDeclaration(node)&&!t.isBlockScoped(node)){state.add(node)}}};var programReferenceVisitor={enter:function(node,parent,scope,context,add){if(t.isReferencedIdentifier(node,parent)&&!scope.has(node.name)){add(node,true)}}};var blockVariableVisitor={enter:function(node,parent,scope,context,add){if(t.isBlockScoped(node)){add(node,false,t.isLet(node))}else if(t.isScope(node)){context.skip()}}};Scope.prototype.getInfo=function(){var parent=this.parent;var block=this.block;var self=this;if(block._scopeInfo)return block._scopeInfo;var info=block._scopeInfo={};var references=info.references=object();var declarations=info.declarations=object();var declarationKinds=info.declarationKinds={};var add=function(node,reference,throwOnDuplicate){self._add(node,references);if(!reference){self._add(node,declarations,throwOnDuplicate);self._add(node,declarationKinds[node.kind]=declarationKinds[node.kind]||object())}};if(parent&&t.isBlockStatement(block)&&t.isFor(parent.block,{body:block})){return info}if(t.isFor(block)){_.each(FOR_KEYS,function(key){var node=block[key];if(t.isBlockScoped(node))add(node,false,true)});if(t.isBlockStatement(block.body)){block=block.body}}if(t.isBlockStatement(block)||t.isProgram(block)){traverse(block,blockVariableVisitor,this,add)}if(t.isCatchClause(block)){add(block.param)}if(t.isComprehensionExpression(block)){add(block)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,functionVariableVisitor,this,{blockId:block.id,add:add})}if(t.isFunctionExpression(block)&&block.id){if(!t.isProperty(this.parentBlock,{method:true})){add(block.id)}}if(t.isProgram(block)){traverse(block,programReferenceVisitor,this,add)}if(t.isFunction(block)){_.each(block.params,function(param){add(param)})}return info};Scope.prototype.push=function(opts){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[opts.key]={kind:opts.kind,id:opts.id,init:opts.init}}else{throw new TypeError("cannot add a declaration here in node type "+block.type)}};Scope.prototype.add=function(node){var scope=this.getFunctionParent();scope._add(node,scope.references)};Scope.prototype.getFunctionParent=function(){var scope=this;while(scope.parent&&!t.isFunction(scope.block)){scope=scope.parent}return scope};Scope.prototype.getAllOfKind=function(kind){var ids=object();var scope=this;do{_.defaults(ids,scope.declarationKinds[kind]);scope=scope.parent}while(scope);return ids};Scope.prototype.get=function(id,decl){return id&&(this.getOwn(id,decl)||this.parentGet(id,decl))};Scope.prototype.getOwn=function(id,decl){var refs=this.references;if(decl)refs=this.declarations;return _.has(refs,id)&&refs[id]};Scope.prototype.parentGet=function(id,decl){return this.parent&&this.parent.get(id,decl)};Scope.prototype.has=function(id,decl){return id&&(this.hasOwn(id,decl)||this.parentHas(id,decl))||_.contains(Scope.defaultDeclarations,id)};Scope.prototype.hasOwn=function(id,decl){return!!this.getOwn(id,decl)};Scope.prototype.parentHas=function(id,decl){return this.parent&&this.parent.has(id,decl)}},{"../helpers/object":25,"../types":101,"./global-keys":96,"./index":97,lodash:168}],99:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],PrivateDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function","Expression"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function","Expression"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class","Expression"],ForOfStatement:["Statement","For","Scope","Loop"],ForInStatement:["Statement","For","Scope","Loop"],ForStatement:["Statement","For","Scope","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],AssignmentPattern:["Pattern"],Property:["UserWhitespacable"],JSXElement:["UserWhitespacable","Expression"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],BindFunctionExpression:["Expression"],BindMemberExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression","Scope"],ConditionalExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],UpdateExpression:["Expression"],VirtualPropertyExpression:["Expression"],JSXEmptyExpression:["Expression"],JSXMemberExpression:["Expression"],YieldExpression:["Expression"]}},{}],100:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrowFunctionExpression:["params","body"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],FunctionDeclaration:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],MethodDefinition:["key","value","computed","kind"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],WithStatement:["object","body"],YieldExpression:["argument","delegate"]}},{}],101:[function(require,module,exports){"use strict";var toFastProperties=require("../helpers/to-fast-properties");var esutils=require("esutils");var object=require("../helpers/object");var Node=require("./node");var _=require("lodash");var t=exports;t.NATIVE_TYPE_NAMES=["Array","Object","Number","Boolean","Date","Array","String"];function registerType(type,skipAliasCheck){var is=t["is"+type]=function(node,opts){return t.is(type,node,opts,skipAliasCheck)};t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}}t.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];t.VISITOR_KEYS=require("./visitor-keys");t.ALIAS_KEYS=require("./alias-keys");t.FLIPPED_ALIAS_KEYS={};_.each(t.VISITOR_KEYS,function(keys,type){registerType(type,true)});_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=t.FLIPPED_ALIAS_KEYS[alias]=t.FLIPPED_ALIAS_KEYS[alias]||[];types.push(type)})});_.each(t.FLIPPED_ALIAS_KEYS,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;registerType(type,false)});t.is=function(type,node,opts,skipAliasCheck){if(!node)return;var typeMatches=type===node.type;if(!typeMatches&&!skipAliasCheck){var aliases=t.FLIPPED_ALIAS_KEYS[type];if(typeof aliases!=="undefined"){typeMatches=aliases.indexOf(node.type)>-1}}if(!typeMatches){return false}if(typeof opts!=="undefined"){return t.shallowEqual(node,opts) }return true};t.BUILDER_KEYS=_.defaults(require("./builder-keys"),t.VISITOR_KEYS);_.each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node=new Node;node.start=null;node.type=type;_.each(keys,function(key,i){node[key]=args[i]});return node}});t.toComputedKey=function(node,key){if(!node.computed){if(t.isIdentifier(key))key=t.literal(key.name)}return key};t.isFalsyExpression=function(node){if(t.isLiteral(node)){return!node.value}else if(t.isIdentifier(node)){return node.name==="undefined"}return false};t.toSequenceExpression=function(nodes,scope){var exprs=[];_.each(nodes,function(node){if(t.isExpression(node)){exprs.push(node)}if(t.isExpressionStatement(node)){exprs.push(node.expression)}else if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){scope.push({kind:node.kind,key:declar.id.name,id:declar.id});exprs.push(t.assignmentExpression("=",declar.id,declar.init))})}});if(exprs.length===1){return exprs[0]}else{return t.sequenceExpression(exprs)}};t.shallowEqual=function(actual,expected){var keys=Object.keys(expected);var key;for(var i=0;i<keys.length;i++){key=keys[i];if(actual[key]!==expected[key])return false}return true};t.appendToMemberExpression=function(member,append,computed){member.object=t.memberExpression(member.object,member.property,member.computed);member.property=append;member.computed=!!computed;return member};t.prependToMemberExpression=function(member,append){member.object=t.memberExpression(append,member.object);return member};t.isReferenced=function(node,parent){if(t.isMemberExpression(parent)){if(parent.property===node&&parent.computed){return true}else if(parent.object===node){return true}else{return false}}if(t.isProperty(parent)){return parent.key===node&&parent.computed}if(t.isVariableDeclarator(parent)){return parent.id!==node}if(t.isFunction(parent)){for(var i=0;i<parent.params.length;i++){var param=parent.params[i];if(param===node)return false}return parent.id!==node}if(t.isClass(parent)){return parent.id!==node}if(t.isMethodDefinition(parent)){return parent.key===node&&parent.computed}if(t.isLabeledStatement(parent)){return false}if(t.isCatchClause(parent)){return parent.param!==node}if(t.isRestElement(parent)){return false}if(t.isAssignmentPattern(parent)){return parent.right!==node}if(t.isPattern(parent)){return false}if(t.isImportSpecifier(parent)){return false}if(t.isImportBatchSpecifier(parent)){return false}if(t.isPrivateDeclaration(parent)){return false}return true};t.isReferencedIdentifier=function(node,parent){return t.isIdentifier(node)&&t.isReferenced(node,parent)};t.isValidIdentifier=function(name){return _.isString(name)&&esutils.keyword.isIdentifierName(name)&&!esutils.keyword.isReservedWordES6(name,true)};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name+"";name=name.replace(/[^a-zA-Z0-9$_]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});if(!t.isValidIdentifier(name)){name="_"+name}return name||"_"};t.ensureBlock=function(node,key){key=key||"body";node[key]=t.toBlock(node[key],node)};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}else if(t.isAssignmentExpression(node)){return t.expressionStatement(node)}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};exports.toExpression=function(node){if(t.isExpressionStatement(node)){node=node.expression}if(t.isClass(node)){node.type="ClassExpression"}else if(t.isFunction(node)){node.type="FunctionExpression"}if(t.isExpression(node)){return node}else{throw new Error("cannot turn "+node.type+" to an expression")}};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(t.isEmptyStatement(node)){node=[]}if(!Array.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getIds=function(node,map,ignoreTypes){var search=[].concat(node);var ids=object();while(search.length){var id=search.shift();if(!id)continue;if(ignoreTypes&&ignoreTypes.indexOf(id.type)>=0)continue;var nodeKeys=t.getIds.nodes[id.type];var arrKeys=t.getIds.arrays[id.type];var i,key;if(t.isIdentifier(id)){ids[id.name]=id}else if(t.isExportDeclaration(id)){if(t.isDeclaration(node.declaration)){search.push(node.declaration)}}else if(nodeKeys){for(i=0;i<nodeKeys.length;i++){key=nodeKeys[i];if(id[key]){search.push(id[key]);break}}}else if(arrKeys){for(i=0;i<arrKeys.length;i++){key=arrKeys[i];search=search.concat(id[key]||[])}}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:["left"],ImportBatchSpecifier:["name"],ImportSpecifier:["name","id"],ExportSpecifier:["name","id"],VariableDeclarator:["id"],FunctionDeclaration:["id"],ClassDeclaration:["id"],MemeberExpression:["object"],SpreadElement:["argument"],RestElement:["argument"],Property:["value"],ComprehensionBlock:["left"],AssignmentPattern:["left"]};t.getIds.arrays={PrivateDeclaration:["declarations"],ComprehensionExpression:["blocks"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isBlockScoped=function(node){return t.isFunctionDeclaration(node)||t.isLet(node)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.COMMENT_KEYS=["leadingComments","trailingComments"];t.removeComments=function(child){_.each(t.COMMENT_KEYS,function(key){delete child[key]});return child};t.inheritsComments=function(child,parent){_.each(t.COMMENT_KEYS,function(key){child[key]=_.uniq(_.compact([].concat(child[key],parent[key])))});return child};t.inherits=function(child,parent){child.range=parent.range;child.start=parent.start;child.loc=parent.loc;child.end=parent.end;t.inheritsComments(child,parent);return child};t.getLastStatements=function(node){var nodes=[];var add=function(node){nodes=nodes.concat(t.getLastStatements(node))};if(t.isIfStatement(node)){add(node.consequent);add(node.alternate)}else if(t.isFor(node)||t.isWhile(node)){add(node.body)}else if(t.isProgram(node)||t.isBlockStatement(node)){add(node.body[node.body.length-1])}else if(node){nodes.push(node)}return nodes};t.getSpecifierName=function(specifier){return specifier.name||specifier.id};t.getSpecifierId=function(specifier){if(specifier.default){return t.identifier("default")}else{return specifier.id}};t.isSpecifierDefault=function(specifier){return specifier.default||t.isIdentifier(specifier.id)&&specifier.id.name==="default"};toFastProperties(t);toFastProperties(t.VISITOR_KEYS)},{"../helpers/object":25,"../helpers/to-fast-properties":26,"./alias-keys":99,"./builder-keys":100,"./node":102,"./visitor-keys":103,esutils:166,lodash:168}],102:[function(require,module,exports){"use strict";module.exports=Node;var acorn=require("acorn-6to5");var oldNode=acorn.Node;acorn.Node=Node;function Node(){oldNode.apply(this)}},{"acorn-6to5":105}],103:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateDeclaration:["declarations"],Program:["body"],Property:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],AnyTypeAnnotation:[],ArrayTypeAnnotation:[],BooleanTypeAnnotation:[],ClassProperty:["key"],DeclareClass:[],DeclareFunction:[],DeclareModule:[],DeclareVariable:[],FunctionTypeAnnotation:[],FunctionTypeParam:[],GenericTypeAnnotation:[],InterfaceExtends:[],InterfaceDeclaration:[],IntersectionTypeAnnotation:[],NullableTypeAnnotation:[],NumberTypeAnnotation:[],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],TupleTypeAnnotation:[],TypeofTypeAnnotation:[],TypeAlias:[],TypeAnnotation:[],TypeParameterDeclaration:[],TypeParameterInstantiation:[],ObjectTypeAnnotation:[],ObjectTypeCallProperty:[],ObjectTypeIndexer:[],ObjectTypeProperty:[],QualifiedTypeIdentifier:[],UnionTypeAnnotation:[],VoidTypeAnnotation:[],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","closingElement","children"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes"],JSXSpreadAttribute:["argument"]}},{}],104:[function(require,module,exports){(function(Buffer,__dirname){"use strict";require("./patch");var estraverse=require("estraverse");var codeFrame=require("./helpers/code-frame");var traverse=require("./traverse");var debug=require("debug/node");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var _=require("lodash");exports.inherits=util.inherits;exports.debug=debug("6to5");exports.canCompile=function(filename,altExts){var exts=altExts||exports.canCompile.EXTENSIONS;var ext=path.extname(filename);return _.contains(exts,ext)};exports.canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];exports.isInteger=function(i){return _.isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp(/.^/);if(Array.isArray(val))val=val.join("|");if(_.isString(val))return new RegExp(val);if(_.isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(_.isString(val))return exports.list(val);if(Array.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,computed,method){var alias;if(t.isIdentifier(key)){alias=key.name;if(computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(_.cloneDeep(key)))}var map;if(_.has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(computed){map._computed=true}map[kind]=method};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);_.each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);if(!map.get&&!map.set){map.writable=t.literal(true)}map.enumerable=t.literal(true);map.configurable=t.literal(true);_.each(map,function(node,key){if(key[0]==="_")return;node=_.clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};var templateVisitor={enter:function(node,parent,scope,context,nodes){if(t.isIdentifier(node)&&_.has(nodes,node.name)){return nodes[node.name]}}};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=_.cloneDeep(template);if(!_.isEmpty(nodes)){traverse(template,templateVisitor,null,nodes)}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){return node.expression}else{return node}};exports.repeat=function(width,cha){cha=cha||" ";var result="";for(var i=0;i<width;i++){result+=cha}return result};exports.normaliseAst=function(ast,comments,tokens){if(ast&&ast.type==="Program"){return t.file(ast,comments||[],tokens||[])}else{throw new Error("Not a valid ast?")}};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowImportExportEverywhere:opts.allowImportExportEverywhere,allowReturnOutsideFunction:true,ecmaVersion:opts.experimental?7:6,playground:opts.playground,strictMode:true,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=exports.normaliseAst(ast,comments,tokens);if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=codeFrame(code,loc.line,loc.column+1);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/transformation/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://github.com/6to5/6to5/issues")}_.each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":198,"./helpers/code-frame":24,"./patch":27,"./traverse":97,"./types":101,"acorn-6to5":105,buffer:122,"debug/node":157,estraverse:162,fs:120,lodash:168,path:129,util:146}],105:[function(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.11.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,curPosition()]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(){lastEnd=tokEnd;readToken();return new Token}getToken.jumpTo=function(pos,exprAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokExprAllowed=!!exprAllowed;skipSpace()};getToken.current=function(){return new Token};if(typeof Symbol!=="undefined"){getToken[Symbol.iterator]=function(){return{next:function(){var token=getToken();return{done:token.type===_eof,value:token}}}}}getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokContext,tokExprAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inType;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=curPosition();inFunction=inGenerator=inAsync=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _jsxName={type:"jsxName"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_template={type:"template"};var _ellipsis={type:"...",beforeExpr:true};var _backQuote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _jsxText={type:"jsxText"};var _paamayimNekudotayim={type:"::",beforeExpr:true};var _at={type:"@"};var _hash={type:"#"};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:11,beforeExpr:true,rightAssociative:true};var _jsxTagStart={type:"jsxTagStart"},_jsxTagEnd={type:"jsxTagEnd"};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,paamayimNekudotayim:_paamayimNekudotayim,exponent:_exponent,at:_at,hash:_hash,arrow:_arrow,template:_template,star:_star,assign:_assign,backQuote:_backQuote,dollarBraceL:_dollarBraceL};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];var isReservedWord3=function anonymous(str){switch(str.length){case 6:switch(str){case"double":case"export":case"import":case"native":case"public":case"static":case"throws":return true}return false;case 4:switch(str){case"byte":case"char":case"enum":case"goto":case"long":return true}return false;case 5:switch(str){case"class":case"final":case"float":case"short":case"super":return true}return false;case 7:switch(str){case"boolean":case"extends":case"package":case"private":return true}return false;case 9:switch(str){case"interface":case"protected":case"transient":return true}return false;case 8:switch(str){case"abstract":case"volatile":return true}return false;case 10:return str==="implements";case 3:return str==="int";case 12:return str==="synchronized"}};var isReservedWord5=function anonymous(str){switch(str.length){case 5:switch(str){case"class":case"super":case"const":return true}return false;case 6:switch(str){case"export":case"import":return true}return false;case 4:return str==="enum";case 7:return str==="extends"}};var isStrictReservedWord=function anonymous(str){switch(str.length){case 9:switch(str){case"interface":case"protected":return true}return false;case 7:switch(str){case"package":case"private":return true}return false;case 6:switch(str){case"public":case"static":return true}return false;case 10:return str==="implements";case 3:return str==="let";case 5:return str==="yield"}};var isStrictBadIdWord=function anonymous(str){switch(str){case"eval":case"arguments":return true}return false};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=function anonymous(str){switch(str.length){case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 7:switch(str){case"default":case"finally":return true}return false;case 10:return str==="instanceof"}};var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=function anonymous(str){switch(str.length){case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":case"const":case"class":case"yield":return true}return false;case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":case"export":case"import":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":case"let":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 7:switch(str){case"default":case"finally":case"extends":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 10:return str==="instanceof"}};var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var decimalNumber=/^\d+$/;var hexNumber=/^[\da-fA-F]+$/;var newline=/[\n\r\u2028\u2029]/;function isNewLine(code){return code===10||code===13||code===8232||code==8233}var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(line,col){this.line=line;this.column=col}Position.prototype.offset=function(n){return new Position(this.line,this.column+n)};function curPosition(){return new Position(tokCurLine,tokPos-tokLineStart)}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokType=_eof;tokContext=[b_stat];tokExprAllowed=true;inType=strict=false;if(tokPos===0&&options.allowHashBang&&input.slice(0,2)==="#!"){skipLineComment(2)}}var b_stat={token:"{",isExpr:false},b_expr={token:"{",isExpr:true},b_tmpl={token:"${",isExpr:true};var p_stat={token:"(",isExpr:false},p_expr={token:"(",isExpr:true};var q_tmpl={token:"`",isExpr:true},f_expr={token:"function",isExpr:true};var j_oTag={token:"<tag",isExpr:false},j_cTag={token:"</tag",isExpr:false},j_expr={token:"<tag>...</tag>",isExpr:true};function curTokContext(){return tokContext[tokContext.length-1]}function braceIsBlock(prevType){var parent;if(prevType===_colon&&(parent=curTokContext()).token=="{")return!parent.isExpr;if(prevType===_return)return newline.test(input.slice(lastEnd,tokStart));if(prevType===_else||prevType===_semi||prevType===_eof)return true;if(prevType==_braceL)return curTokContext()===b_stat;return!tokExprAllowed}function finishToken(type,val){tokEnd=tokPos;if(options.locations)tokEndLoc=curPosition();var prevType=tokType,preserveSpace=false;tokType=type;tokVal=val;if(type===_parenR||type===_braceR){var out=tokContext.pop();if(out===b_tmpl){preserveSpace=tokExprAllowed=true}else if(out===b_stat&&curTokContext()===f_expr){tokContext.pop();tokExprAllowed=false}else{tokExprAllowed=!(out&&out.isExpr)}}else if(type===_braceL){switch(curTokContext()){case j_oTag:tokContext.push(b_expr);break;case j_expr:tokContext.push(b_tmpl);break;default:tokContext.push(braceIsBlock(prevType)?b_stat:b_expr)}tokExprAllowed=true}else if(type===_dollarBraceL){tokContext.push(b_tmpl);tokExprAllowed=true }else if(type==_parenL){var statementParens=prevType===_if||prevType===_for||prevType===_with||prevType===_while;tokContext.push(statementParens?p_stat:p_expr);tokExprAllowed=true}else if(type==_incDec){}else if(type.keyword&&prevType==_dot){tokExprAllowed=false}else if(type==_function){if(curTokContext()!==b_stat){tokContext.push(f_expr)}tokExprAllowed=false}else if(type===_backQuote){if(curTokContext()===q_tmpl){tokContext.pop()}else{tokContext.push(q_tmpl);preserveSpace=true}tokExprAllowed=false}else if(type===_jsxTagStart){tokContext.push(j_expr);tokContext.push(j_oTag);tokExprAllowed=false}else if(type===_jsxTagEnd){var out=tokContext.pop();if(out===j_oTag&&prevType===_slash||out===j_cTag){tokContext.pop();preserveSpace=tokExprAllowed=curTokContext()===j_expr}else{preserveSpace=tokExprAllowed=true}}else if(type===_jsxText){preserveSpace=tokExprAllowed=true}else if(type===_slash&&prevType===_jsxTagStart){tokContext.length-=2;tokContext.push(j_cTag);tokExprAllowed=false}else{tokExprAllowed=type.beforeExpr}if(!preserveSpace)skipSpace()}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&curPosition();var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&curPosition())}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&curPosition();var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&curPosition())}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.playground&&next===63){tokPos+=2;return finishToken(_dotQuestion)}else if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokExprAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(options.playground&&input.charCodeAt(tokPos+2)===61)return finishOp(_assign,3);return finishOp(code===124?_logicalOR:_logicalAND,2)}if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(!inType&&next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(!inType){if(tokExprAllowed&&code===60){++tokPos;return finishToken(_jsxTagStart)}if(code===62){var context=curTokContext();if(context===j_oTag||context===j_cTag){++tokPos;return finishToken(_jsxTagEnd)}}}if(next===61)size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR);case 63:++tokPos;return finishToken(_question);case 64:if(options.playground){++tokPos;return finishToken(_at)}case 35:if(options.playground){++tokPos;return finishToken(_hash)}case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_paamayimNekudotayim)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_backQuote)}else{return false}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(){tokStart=tokPos;if(options.locations)tokStartLoc=curPosition();if(tokPos>=inputLen)return finishToken(_eof);var context=curTokContext();if(context===q_tmpl){return readTmplToken()}if(context===j_expr){return readJSXToken()}var code=input.charCodeAt(tokPos);if(context===j_oTag||context===j_cTag){if(isIdentifierStart(code))return readJSXWord()}else if(context===j_expr){return readJSXToken()}else{if(isIdentifierStart(code)||code===92)return readWord()}var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("￿","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){var isJSX=curTokContext()===j_oTag;var out="",chunkStart=++tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote)break;if(ch===92&&!isJSX){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(ch===38&&isJSX){out+=input.slice(chunkStart,tokPos);out+=readJSXEntity();chunkStart=tokPos}else{if(isNewLine(ch))raise(tokStart,"Unterminated string constant");++tokPos}}out+=input.slice(chunkStart,tokPos++);return finishToken(_string,out)}function readTmplToken(){var out="",chunkStart=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated template");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123){if(tokPos===tokStart&&tokType===_template){if(ch===36){tokPos+=2;return finishToken(_dollarBraceL)}else{++tokPos;return finishToken(_backQuote)}}out+=input.slice(chunkStart,tokPos);return finishToken(_template,out)}if(ch===92){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(isNewLine(ch)){out+=input.slice(chunkStart,tokPos);++tokPos;if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;out+="\n"}else{out+=String.fromCharCode(ch)}if(options.locations){++tokCurLine;tokLineStart=tokPos}chunkStart=tokPos}else{++tokPos}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readJSXEntity(){var str="",count=0,entity;var ch=input[tokPos];if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=input[tokPos++];if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readJSXToken(){var out="",start=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated JSX contents");var ch=input.charCodeAt(tokPos);switch(ch){case 123:case 60:if(tokPos===start){return getTokenFromCode(ch)}return finishToken(_jsxText,out);case 38:out+=readJSXEntity();break;default:++tokPos;if(isNewLine(ch)){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return" ";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&&quote!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word="",first=true,chunkStart=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)){++tokPos}else if(ch===92){containsEsc=true;word+=input.slice(chunkStart,tokPos);if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr;chunkStart=tokPos}else{break}first=false}return word+input.slice(chunkStart,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function readJSXWord(){var ch,start=tokPos;do{ch=input.charCodeAt(++tokPos)}while(isIdentifierChar(ch)||ch===45);return finishToken(_jsxName,input.slice(start,tokPos))}function next(){if(options.onToken)options.onToken(new Token);lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;if(tokType!==_num&&tokType!==_string)return;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new exports.Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new exports.Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function finishNodeAt(node,type,pos){if(options.locations){node.loc.end=pos[1];pos=pos[0]}node.type=type;node.end=pos;if(options.ranges)node.range[1]=pos;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function isContextual(name){return tokType===_name&&tokVal===name}function eatContextual(name){return tokVal===name&&eat(_name)}function expectContextual(name){if(!eatContextual(name))unexpected()}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":case"VirtualPropertyExpression":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.kind!=="init")raise(prop.key.start,"Object pattern can't contain getter or setter");toAssignable(prop.value)}break;case"ArrayExpression":node.type="ArrayPattern";toAssignableList(node.elements);break;case"AssignmentExpression":if(node.operator==="="){node.type="AssignmentPattern"}else{raise(node.left.end,"Only '=' operator can be used for specifying default value.")}break;default:raise(node.start,"Assigning to rvalue")}}return node}function toAssignableList(exprList){if(exprList.length){for(var i=0;i<exprList.length-1;i++){toAssignable(exprList[i])}var last=exprList[exprList.length-1];switch(last.type){case"RestElement":break;case"SpreadElement":last.type="RestElement";var arg=last.argument;toAssignable(arg);if(arg.type!=="Identifier"&&arg.type!=="ArrayPattern")unexpected(arg.start);break;default:toAssignable(last)}}return exprList}function parseSpread(refShorthandDefaultPos){var node=startNode();next();node.argument=parseMaybeAssign(refShorthandDefaultPos);return finishNode(node,"SpreadElement")}function parseRest(){var node=startNode();next();node.argument=tokType===_name||tokType===_bracketL?parseAssignableAtom():unexpected();return finishNode(node,"RestElement")}function parseAssignableAtom(){if(options.ecmaVersion<6)return parseIdent();switch(tokType){case _name:return parseIdent();case _bracketL:var node=startNode();next();node.elements=parseAssignableList(_bracketR,true);return finishNode(node,"ArrayPattern");case _braceL:return parseObj(true);default:unexpected()}}function parseAssignableList(close,allowEmpty){var elts=[],first=true;while(!eat(close)){first?first=false:expect(_comma);if(tokType===_ellipsis){elts.push(parseAssignableListItemTypes(parseRest()));expect(close);break}var elem;if(allowEmpty&&tokType===_comma){elem=null}else{var left=parseAssignableAtom();parseAssignableListItemTypes(left);elem=parseMaybeDefault(null,left)}elts.push(elem)}return elts}function parseAssignableListItemTypes(param){if(eat(_question)){param.optional=true}if(tokType===_colon){param.typeAnnotation=parseTypeAnnotation()}finishNode(param,param.type);return param}function parseMaybeDefault(startPos,left){left=left||parseAssignableAtom();if(!eat(_eq))return left;var node=startPos?startNodeAt(startPos):startNode();node.operator="=";node.left=left;node.right=parseMaybeAssign();return finishNode(node,"AssignmentPattern")}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break;case"RestElement":return checkFunctionParam(param.argument,nameHash)}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return;var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,(isBinding?"Binding ":"Assigning to ")+expr.name+" in strict mode");break;case"MemberExpression":if(isBinding)raise(expr.start,"Binding to member expression");break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"AssignmentPattern":checkLVal(expr.left);break;case"SpreadProperty":case"VirtualPropertyExpression":break;case"RestElement":checkLVal(expr.argument);break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement(true,true);node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}next();return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(declaration,topLevel){var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _function:if(!declaration&&options.ecmaVersion>=6)unexpected();return parseFunctionStatement(node);case _class:if(!declaration)unexpected();return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _let:case _const:if(!declaration)unexpected();case _var:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:case _import:if(!topLevel&&!options.allowImportExportEverywhere)raise(tokStart,"'import' and 'export' may only appear at the top level");return starttype===_import?parseImport(node):parseExport(node);default:var maybeName=tokVal,expr=parseExpression();if(options.ecmaVersion>=7&&starttype===_name&&maybeName==="async"&&tokType===_function&&!canInsertSemicolon()){next();var func=parseFunctionStatement(node);func.async=true;return func}if(starttype===_name&&expr.type==="Identifier"){if(eat(_colon)){return parseLabeledStatement(node,maybeName,expr)}if(options.ecmaVersion>=7&&expr.name==="private"&&tokType===_name){return parsePrivate(node)}else if(expr.name==="declare"){if(tokType===_class||tokType===_name||tokType===_function||tokType===_var){return parseDeclare(node)}}else if(tokType===_name){if(expr.name==="interface"){return parseInterface(node)}else if(expr.name==="type"){return parseTypeAlias(node)}}}if(expr.type==="FunctionExpression"&&expr.async){if(expr.id){expr.type="FunctionDeclaration";return expr}else{unexpected(expr.start+"async function ".length)}}return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();expect(_while);node.test=parseParenExpression();if(options.ecmaVersion>=6)eat(_semi);else semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&isContextual("of"))&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var refShorthandDefaultPos={start:0};var init=parseExpression(true,refShorthandDefaultPos); if(tokType===_in||options.ecmaVersion>=6&&isContextual("of")){toAssignable(init);checkLVal(init);return parseForIn(node,init)}else if(refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement(false);node.alternate=eat(_else)?parseStatement(false):null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement(true))}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseAssignableAtom();checkLVal(clause.param,true);expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement(false);return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement(true);labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement(true);node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=parseAssignableAtom();checkLVal(decl.id,true);if(tokType===_colon){decl.id.typeAnnotation=parseTypeAnnotation();finishNode(decl.id,decl.id.type)}decl.init=eat(_eq)?parseMaybeAssign(noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn,refShorthandDefaultPos);if(tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn,refShorthandDefaultPos));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn,refShorthandDefaultPos,afterLeftParse){var failOnShorthandAssign;if(!refShorthandDefaultPos){refShorthandDefaultPos={start:0};failOnShorthandAssign=true}else{failOnShorthandAssign=false}var start=storeCurrentPos();var left=parseMaybeConditional(noIn,refShorthandDefaultPos);if(afterLeftParse)afterLeftParse(left);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;refShorthandDefaultPos.start=0;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}else if(failOnShorthandAssign&&refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return left}function parseMaybeConditional(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprOps(noIn,refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;if(eat(_question)){var node=startNodeAt(start);if(options.playground&&eat(_eq)){var left=node.left=toAssignable(expr);if(left.type!=="MemberExpression")raise(left.start,"You can only use member expressions in memoization assignment");node.right=parseMaybeAssign(noIn);node.operator="?=";return finishNode(node,"AssignmentExpression")}node.test=expr;node.consequent=parseMaybeAssign();expect(_colon);node.alternate=parseMaybeAssign(noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeUnary(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseExprOp(expr,start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,op.rightAssociative?prec-1:prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(refShorthandDefaultPos){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate;node.operator=tokVal;node.prefix=true;next();node.argument=parseMaybeUnary();if(refShorthandDefaultPos&&refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,update?"UpdateExpression":"UnaryExpression")}var start=storeCurrentPos();var expr=parseExprSubscripts(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprAtom(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseSubscripts(expr,start)}function parseSubscripts(base,start,noCalls){if(options.playground&&eat(_hash)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return parseSubscripts(finishNode(node,"BindMemberExpression"),start,noCalls)}else if(eat(_paamayimNekudotayim)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_backQuote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(refShorthandDefaultPos){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _at:var start=storeCurrentPos();var node=startNode();var thisNode=startNode();next();node.object=finishNode(thisNode,"ThisExpression");node.property=parseSubscripts(parseIdent(),start);node.computed=false;return finishNode(node,"MemberExpression");case _yield:if(inGenerator)return parseYield();case _name:var start=storeCurrentPos();var node=startNode();var id=parseIdent(tokType!==_name);if(options.ecmaVersion>=7){if(id.name==="async"){if(tokType===_parenL){next();var exprList;if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(eat(_arrow)){return parseArrowExpression(node,exprList,true)}else{node.callee=id;node.arguments=exprList;return parseSubscripts(finishNode(node,"CallExpression"),start)}}else if(tokType===_name){id=parseIdent();if(eat(_arrow)){return parseArrowExpression(node,[id],true)}return id}if(tokType===_function&&!canInsertSemicolon()){next();return parseFunction(node,false,true)}}else if(id.name==="await"){if(inAsync)return parseAwait(node)}}if(eat(_arrow)){return parseArrowExpression(node,[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _jsxText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:return parseParenAndDistinguishExpression();case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true,refShorthandDefaultPos);return finishNode(node,"ArrayExpression");case _braceL:return parseObj(false,refShorthandDefaultPos);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _backQuote:return parseTemplate();case _hash:return parseBindFunctionExpression();case _jsxTagStart:return parseJSXElement();default:unexpected()}}function parseBindFunctionExpression(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return finishNode(node,"BindFunctionExpression")}function parseParenAndDistinguishExpression(){var start=storeCurrentPos(),val;if(options.ecmaVersion>=6){next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(startNodeAt(start),true)}var innerStart=storeCurrentPos(),exprList=[],first=true;var refShorthandDefaultPos={start:0},spreadStart,innerParenStart,typeStart;var parseParenItem=function(node){if(tokType===_colon){typeStart=typeStart||tokStart;node.returnType=parseTypeAnnotation()}return node};while(tokType!==_parenR){first?first=false:expect(_comma);if(tokType===_ellipsis){spreadStart=tokStart;exprList.push(parseParenItem(parseRest()));break}else{if(tokType===_parenL&&!innerParenStart){innerParenStart=tokStart}exprList.push(parseMaybeAssign(false,refShorthandDefaultPos,parseParenItem))}}var innerEnd=storeCurrentPos();expect(_parenR);if(eat(_arrow)){if(innerParenStart)unexpected(innerParenStart);return parseArrowExpression(startNodeAt(start),exprList)}if(!exprList.length)unexpected(lastStart);if(typeStart)unexpected(typeStart);if(spreadStart)unexpected(spreadStart);if(refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(exprList.length>1){val=startNodeAt(innerStart);val.expressions=exprList;finishNodeAt(val,"SequenceExpression",innerEnd)}else{val=exprList[0]}}else{val=parseParenExpression()}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;return finishNode(par,"ParenthesizedExpression")}else{return val}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplateElement(){var elem=startNode();elem.value={raw:input.slice(tokStart,tokEnd),cooked:tokVal};next();elem.tail=tokType===_backQuote;return finishNode(elem,"TemplateElement")}function parseTemplate(){var node=startNode();next();node.expressions=[];var curElt=parseTemplateElement();node.quasis=[curElt];while(!curElt.tail){expect(_dollarBraceL);node.expressions.push(parseExpression());expect(_braceR);node.quasis.push(curElt=parseTemplateElement())}next();return finishNode(node,"TemplateLiteral")}function parseObj(isPattern,refShorthandDefaultPos){var node=startNode(),first=true,propHash={};node.properties=[];next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),start,isGenerator=false,isAsync=false;if(options.ecmaVersion>=7&&tokType===_ellipsis){prop=parseSpread();prop.type="SpreadProperty";node.properties.push(prop);continue}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern){start=storeCurrentPos()}else{isGenerator=eat(_star)}}if(options.ecmaVersion>=7&&isContextual("async")){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){prop.key=asyncId}else{isAsync=true;parsePropertyName(prop)}}else{parsePropertyName(prop)}var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration();if(tokType!==_parenL)unexpected()}if(eat(_colon)){prop.value=isPattern?parseMaybeDefault(start):parseMaybeAssign(false,refShorthandDefaultPos);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){if(isPattern)unexpected();prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set"||options.playground&&prop.key.name==="memo")&&(tokType!=_comma&&tokType!=_braceR)){if(isGenerator||isAsync||isPattern)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";if(isPattern){prop.value=parseMaybeDefault(start,prop.key)}else if(tokType===_eq&&refShorthandDefaultPos){if(!refShorthandDefaultPos.start)refShorthandDefaultPos.start=tokStart;prop.value=parseMaybeDefault(start,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else unexpected();prop.value.typeParameters=typeParameters;checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}return finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;if(options.ecmaVersion>=6){node.generator=false;node.expression=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseFunctionParams(node){expect(_parenL);node.params=parseAssignableList(_parenR,false);if(tokType===_colon){node.returnType=parseTypeAnnotation()}}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);node.params=toAssignableList(params,true);parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseMaybeAssign();node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash)}}function parsePrivate(node){node.declarations=[];do{node.declarations.push(parseIdent())}while(eat(_comma));semicolon();return finishNode(node,"PrivateDeclaration")}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}node.superClass=eat(_extends)?parseExprSubscripts():null;if(node.superClass&&isRelational("<")){node.superTypeParameters=parseTypeParameterInstantiation()}if(isContextual("implements")){next();node.implements=parseClassImplements()}var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){if(eat(_semi))continue;var method=startNode();if(options.ecmaVersion>=7&&isContextual("private")){next();classBody.body.push(parsePrivate(method));continue}var isGenerator=eat(_star);var isAsync=false;parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="static"){if(isGenerator||isAsync)unexpected();method["static"]=true;isGenerator=eat(_star);parsePropertyName(method)}else{method["static"]=false}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="async"){isAsync=true;parsePropertyName(method)}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")||options.playground&&method.key.name==="memo"){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}if(tokType===_colon){method.typeAnnotation=parseTypeAnnotation();semicolon();classBody.body.push(finishNode(method,"ClassProperty"))}else{var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration()}method.value=parseMethod(isGenerator,isAsync);method.value.typeParameters=typeParameters;classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseClassImplements(){var implemented=[];do{var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}implemented.push(finishNode(node,"ClassImplements"))}while(eat(_comma));return implemented}function parseExprList(close,allowTrailingComma,allowEmpty,refShorthandDefaultPos){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma){elts.push(null)}else{if(tokType===_ellipsis)elts.push(parseSpread(refShorthandDefaultPos));else elts.push(parseMaybeAssign(false,refShorthandDefaultPos))}}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||isContextual("async")){node.declaration=parseStatement(true);node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){var declar=node.declaration=parseMaybeAssign(true);if(declar.id){if(declar.type==="FunctionExpression"){declar.type="FunctionDeclaration"}else if(declar.type==="ClassExpression"){declar.type="ClassDeclaration"}}node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(eatContextual("from")){node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);node.name=eatContextual("as")?parseIdent(true):null;nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom()}else{node.specifiers=parseImportSpecifiers();expectContextual("from");node.source=tokType===_string?parseExprAtom():unexpected()}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}if(tokType===_star){var node=startNode();next();expectContextual("as");node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);node.name=eatContextual("as")?parseIdent():null;checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseMaybeAssign()}return finishNode(node,"YieldExpression")}function parseAwait(node){if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseMaybeAssign(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=parseAssignableAtom();checkLVal(block.left,true);expectContextual("of");block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedJSXName(object){if(object.type==="JSXIdentifier"){return object.name}if(object.type==="JSXNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="JSXMemberExpression"){return getQualifiedJSXName(object.object)+"."+getQualifiedJSXName(object.property)}}function parseJSXIdentifier(){var node=startNode();if(tokType===_jsxName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"JSXIdentifier")}function parseJSXNamespacedName(){var start=storeCurrentPos();var name=parseJSXIdentifier();if(!eat(_colon))return name;var node=startNodeAt(start);node.namespace=name;node.name=parseJSXIdentifier();return finishNode(node,"JSXNamespacedName")}function parseJSXElementName(){var start=storeCurrentPos();var node=parseJSXNamespacedName();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseJSXIdentifier();node=finishNode(newNode,"JSXMemberExpression")}return node}function parseJSXAttributeValue(){switch(tokType){case _braceL:var node=parseJSXExpressionContainer();if(node.expression.type==="JSXEmptyExpression"){raise(node.start,"JSX attributes must only be assigned a non-empty "+"expression")}return node;case _jsxTagStart:return parseJSXElement();case _jsxText:case _string:return parseExprAtom();default:raise(tokStart,"JSX value should be either an expression or a quoted JSX text")}}function parseJSXEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"JSXEmptyExpression")}function parseJSXExpressionContainer(){var node=startNode();next();node.expression=tokType===_braceR?parseJSXEmptyExpression():parseExpression();expect(_braceR);return finishNode(node,"JSXExpressionContainer")}function parseJSXAttribute(){var node=startNode();if(eat(_braceL)){expect(_ellipsis);node.argument=parseMaybeAssign();expect(_braceR);return finishNode(node,"JSXSpreadAttribute")}node.name=parseJSXNamespacedName();node.value=eat(_eq)?parseJSXAttributeValue():null;return finishNode(node,"JSXAttribute")}function parseJSXOpeningElementAt(start){var node=startNodeAt(start);node.attributes=[];node.name=parseJSXElementName();while(tokType!==_slash&&tokType!==_jsxTagEnd){node.attributes.push(parseJSXAttribute())}node.selfClosing=eat(_slash);expect(_jsxTagEnd);return finishNode(node,"JSXOpeningElement")}function parseJSXClosingElementAt(start){var node=startNodeAt(start);node.name=parseJSXElementName();expect(_jsxTagEnd);return finishNode(node,"JSXClosingElement")}function parseJSXElementAt(start){var node=startNodeAt(start);var children=[];var openingElement=parseJSXOpeningElementAt(start);var closingElement=null;if(!openingElement.selfClosing){contents:for(;;){switch(tokType){case _jsxTagStart:start=storeCurrentPos();next();if(eat(_slash)){closingElement=parseJSXClosingElementAt(start);break contents}children.push(parseJSXElementAt(start));break;case _jsxText:children.push(parseExprAtom());break;case _braceL:children.push(parseJSXExpressionContainer());break;default:unexpected()}}if(getQualifiedJSXName(closingElement.name)!==getQualifiedJSXName(openingElement.name)){raise(closingElement.start,"Expected corresponding JSX closing tag for <"+getQualifiedJSXName(openingElement.name)+">")}}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"JSXElement")}function isRelational(op){return tokType===_relational&&tokVal===op}function expectRelational(op){if(isRelational(op)){next()}else{unexpected()}}function parseJSXElement(){var start=storeCurrentPos();next();return parseJSXElementAt(start)}function parseDeclareClass(node){next();parseInterfaceish(node,true);return finishNode(node,"DeclareClass")}function parseDeclareFunction(node){next();var id=node.id=parseIdent();var typeNode=startNode();var typeContainer=startNode();if(isRelational("<")){typeNode.typeParameters=parseTypeParameterDeclaration()}else{typeNode.typeParameters=null}expect(_parenL);var tmp=parseFunctionTypeParams();typeNode.params=tmp.params;typeNode.rest=tmp.rest;expect(_parenR);expect(_colon);typeNode.returnType=parseType();typeContainer.typeAnnotation=finishNode(typeNode,"FunctionTypeAnnotation");id.typeAnnotation=finishNode(typeContainer,"TypeAnnotation");finishNode(id,id.type);semicolon();return finishNode(node,"DeclareFunction")}function parseDeclare(node){if(tokType===_class){return parseDeclareClass(node)}else if(tokType===_function){return parseDeclareFunction(node)}else if(tokType===_var){return parseDeclareVariable(node)}else if(isContextual("module")){return parseDeclareModule(node)}else{unexpected()}}function parseDeclareVariable(node){next();node.id=parseTypeAnnotatableIdentifier();semicolon();return finishNode(node,"DeclareVariable")}function parseDeclareModule(node){next();if(tokType===_string){node.id=parseExprAtom()}else{node.id=parseIdent()}var bodyNode=node.body=startNode();var body=bodyNode.body=[];expect(_braceL);while(tokType!==_braceR){var node2=startNode();next();body.push(parseDeclare(node2))}expect(_braceR);finishNode(bodyNode,"BlockStatement");return finishNode(node,"DeclareModule")}function parseInterfaceish(node,allowStatic){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}node.extends=[];if(eat(_extends)){do{node.extends.push(parseInterfaceExtends())}while(eat(_comma))}node.body=parseObjectType(allowStatic)}function parseInterfaceExtends(){var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}return finishNode(node,"InterfaceExtends")}function parseInterface(node){parseInterfaceish(node,false);return finishNode(node,"InterfaceDeclaration")}function parseTypeAlias(node){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}expect(_eq);node.right=parseType();semicolon();return finishNode(node,"TypeAlias")}function parseTypeParameterDeclaration(){var node=startNode();node.params=[];expectRelational("<");while(!isRelational(">")){node.params.push(parseIdent());if(!isRelational(">")){expect(_comma)}}expectRelational(">");return finishNode(node,"TypeParameterDeclaration")}function parseTypeParameterInstantiation(){var node=startNode(),oldInType=inType;node.params=[];inType=true;expectRelational("<");while(!isRelational(">")){node.params.push(parseType()); if(!isRelational(">")){expect(_comma)}}expectRelational(">");inType=oldInType;return finishNode(node,"TypeParameterInstantiation")}function parseObjectPropertyKey(){return tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function parseObjectTypeIndexer(node,isStatic){node.static=isStatic;expect(_bracketL);node.id=parseObjectPropertyKey();expect(_colon);node.key=parseType();expect(_bracketR);expect(_colon);node.value=parseType();return finishNode(node,"ObjectTypeIndexer")}function parseObjectTypeMethodish(node){node.params=[];node.rest=null;node.typeParameters=null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}expect(_parenL);while(tokType===_name){node.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){node.rest=parseFunctionTypeParam()}expect(_parenR);expect(_colon);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}function parseObjectTypeMethod(start,isStatic,key){var node=startNodeAt(start);node.value=parseObjectTypeMethodish(startNodeAt(start));node.static=isStatic;node.key=key;node.optional=false;return finishNode(node,"ObjectTypeProperty")}function parseObjectTypeCallProperty(node,isStatic){var valueNode=startNode();node.static=isStatic;node.value=parseObjectTypeMethodish(valueNode);return finishNode(node,"ObjectTypeCallProperty")}function parseObjectType(allowStatic){var nodeStart=startNode();var node;var optional=false;var property;var propertyKey;var propertyTypeAnnotation;var token;var isStatic;nodeStart.callProperties=[];nodeStart.properties=[];nodeStart.indexers=[];expect(_braceL);while(tokType!==_braceR){var start=storeCurrentPos();node=startNode();if(allowStatic&&isContextual("static")){next();isStatic=true}if(tokType===_bracketL){nodeStart.indexers.push(parseObjectTypeIndexer(node,isStatic))}else if(tokType===_parenL||isRelational("<")){nodeStart.callProperties.push(parseObjectTypeCallProperty(node,allowStatic))}else{if(isStatic&&tokType===_colon){propertyKey=parseIdent()}else{propertyKey=parseObjectPropertyKey()}if(isRelational("<")||tokType===_parenL){nodeStart.properties.push(parseObjectTypeMethod(start,isStatic,propertyKey))}else{if(eat(_question)){optional=true}expect(_colon);node.key=propertyKey;node.value=parseType();node.optional=optional;node.static=isStatic;nodeStart.properties.push(finishNode(node,"ObjectTypeProperty"))}}if(!eat(_semi)&&tokType!==_braceR){unexpected()}}expect(_braceR);return finishNode(nodeStart,"ObjectTypeAnnotation")}function parseGenericType(start,id){var node=startNodeAt(start);node.typeParameters=null;node.id=id;while(eat(_dot)){var node2=startNodeAt(start);node2.qualification=node.id;node2.id=parseIdent();node.id=finishNode(node2,"QualifiedTypeIdentifier")}if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}return finishNode(node,"GenericTypeAnnotation")}function parseVoidType(){var node=startNode();expect(keywordTypes["void"]);return finishNode(node,"VoidTypeAnnotation")}function parseTypeofType(){var node=startNode();expect(keywordTypes["typeof"]);node.argument=parsePrimaryType();return finishNode(node,"TypeofTypeAnnotation")}function parseTupleType(){var node=startNode();node.types=[];expect(_bracketL);while(tokPos<inputLen&&tokType!==_bracketR){node.types.push(parseType());if(tokType===_bracketR)break;expect(_comma)}expect(_bracketR);return finishNode(node,"TupleTypeAnnotation")}function parseFunctionTypeParam(){var optional=false;var node=startNode();node.name=parseIdent();if(eat(_question)){optional=true}expect(_colon);node.optional=optional;node.typeAnnotation=parseType();return finishNode(node,"FunctionTypeParam")}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(tokType===_name){ret.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){ret.rest=parseFunctionTypeParam()}return ret}function identToTypeAnnotation(start,node,id){switch(id.name){case"any":return finishNode(node,"AnyTypeAnnotation");case"bool":case"boolean":return finishNode(node,"BooleanTypeAnnotation");case"number":return finishNode(node,"NumberTypeAnnotation");case"string":return finishNode(node,"StringTypeAnnotation");default:return parseGenericType(start,id)}}function parsePrimaryType(){var typeIdentifier=null;var params=null;var returnType=null;var start=storeCurrentPos();var node=startNode();var rest=null;var tmp;var typeParameters;var token;var type;var isGroupedType=false;switch(tokType){case _name:return identToTypeAnnotation(start,node,parseIdent());case _braceL:return parseObjectType();case _bracketL:return parseTupleType();case _relational:if(tokVal==="<"){node.typeParameters=parseTypeParameterDeclaration();expect(_parenL);tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}case _parenL:next();var tmpId;if(tokType!==_parenR&&tokType!==_ellipsis){if(tokType===_name){}else{isGroupedType=true}}if(isGroupedType){if(tmpId&&_parenR){type=tmpId}else{type=parseType();expect(_parenR)}if(eat(_arrow)){raise(node,"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType")}return type}tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();node.typeParameters=null;return finishNode(node,"FunctionTypeAnnotation");case _string:node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"StringLiteralTypeAnnotation");default:if(tokType.keyword){switch(tokType.keyword){case"void":return parseVoidType();case"typeof":return parseTypeofType()}}}unexpected()}function parsePostfixType(){var node=startNode();var type=node.elementType=parsePrimaryType();if(tokType===_bracketL){expect(_bracketL);expect(_bracketR);return finishNode(node,"ArrayTypeAnnotation")}return type}function parsePrefixType(){var node=startNode();if(eat(_question)){node.typeAnnotation=parsePrefixType();return finishNode(node,"NullableTypeAnnotation")}return parsePostfixType()}function parseIntersectionType(){var node=startNode();var type=parsePrefixType();node.types=[type];while(eat(_bitwiseAND)){node.types.push(parsePrefixType())}return node.types.length===1?type:finishNode(node,"IntersectionTypeAnnotation")}function parseUnionType(){var node=startNode();var type=parseIntersectionType();node.types=[type];while(eat(_bitwiseOR)){node.types.push(parseIntersectionType())}return node.types.length===1?type:finishNode(node,"UnionTypeAnnotation")}function parseType(){var oldInType=inType;inType=true;var type=parseUnionType();inType=oldInType;return type}function parseTypeAnnotation(){var node=startNode();var oldInType=inType;inType=true;expect(_colon);node.typeAnnotation=parseType();inType=oldInType;return finishNode(node,"TypeAnnotation")}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var node=startNode();var ident=parseIdent();var isOptionalParam=false;if(canBeOptionalParam&&eat(_question)){expect(_question);isOptionalParam=true}if(requireTypeAnnotation||tokType===_colon){ident.typeAnnotation=parseTypeAnnotation();finishNode(ident,ident.type)}if(isOptionalParam){ident.optional=true;finishNode(ident,ident.type)}return ident}})},{}],106:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Printable").field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("Node").bases("Printable").field("type",isString);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]).field("comments",or([or(def("Block"),def("Line"))],null),defaults["null"],true);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp));def("Block").bases("Printable").build("loc","value").field("value",isString);def("Line").bases("Printable").build("loc","value").field("value",isString)},{"../lib/shared":117,"../lib/types":118}],107:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":118,"./core":106}],108:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("PropertyPattern").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("value",def("Function")).field("computed",isBoolean,defaults["false"]);def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("key").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]).field("implements",[def("ClassImplements")],defaults.emptyArray);def("ClassImplements").bases("Node").build("id").field("id",def("Identifier")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":117,"../lib/types":118,"./core":106}],109:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":117,"../lib/types":118,"./core":106}],110:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("Type").bases("Node");def("AnyTypeAnnotation").bases("Type");def("VoidTypeAnnotation").bases("Type");def("NumberTypeAnnotation").bases("Type");def("StringTypeAnnotation").bases("Type");def("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",isString).field("raw",isString);def("BooleanTypeAnnotation").bases("Type");def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",def("Type"));def("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",def("Type"));def("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[def("FunctionTypeParam")]).field("returnType",def("Type")).field("rest",or(def("FunctionTypeParam"),null)).field("typeParameters",or(def("TypeParameterDeclaration"),null));def("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",def("Identifier")).field("typeAnnotation",def("Type")).field("optional",isBoolean);def("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",def("Type"));def("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[def("ObjectTypeProperty")]).field("indexers",[def("ObjectTypeIndexer")],defaults.emptyArray).field("callProperties",[def("ObjectTypeCallProperty")],defaults.emptyArray);def("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",or(def("Literal"),def("Identifier"))).field("value",def("Type")).field("optional",isBoolean);def("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",def("Identifier")).field("key",def("Type")).field("value",def("Type"));def("ObjectTypeCallProperty").bases("Node").build("value").field("value",def("FunctionTypeAnnotation")).field("static",isBoolean,false);def("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("id",def("Identifier"));def("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("MemberTypeAnnotation").bases("Type").build("object","property").field("object",def("Identifier")).field("property",or(def("MemberTypeAnnotation"),def("GenericTypeAnnotation")));def("UnionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",def("Type"));def("Identifier").field("typeAnnotation",or(def("TypeAnnotation"),null),defaults["null"]);def("TypeParameterDeclaration").bases("Node").build("params").field("params",[def("Identifier")]);def("TypeParameterInstantiation").bases("Node").build("params").field("params",[def("Type")]);def("Function").field("returnType",or(def("TypeAnnotation"),null),defaults["null"]).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]);def("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",def("TypeAnnotation")).field("static",isBoolean,false);def("ClassImplements").field("typeParameters",or(def("TypeParameterInstantiation"),null),defaults["null"]);def("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]).field("body",def("ObjectTypeAnnotation")).field("extends",[def("InterfaceExtends")]);def("InterfaceExtends").bases("Node").build("id").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null)).field("right",def("Type"));def("TupleTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("DeclareVariable").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareFunction").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareClass").bases("InterfaceDeclaration").build("id");def("DeclareModule").bases("Statement").build("id","body").field("id",or(def("Identifier"),def("Literal"))).field("body",def("BlockStatement"))},{"../lib/shared":117,"../lib/types":118,"./core":106}],111:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":117,"../lib/types":118,"./core":106}],112:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property }return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":119,assert:121}],113:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true);if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":115,"./scope":116,"./types":118,assert:121,util:146}],114:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this);this._visiting=false;this._changeReported=false}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){return PathVisitor.fromMethodsObject(methods).visit(node)};var PVp=PathVisitor.prototype;var recursiveVisitWarning=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");PVp.visit=function(){assert.ok(!this._visiting,recursiveVisitWarning);this._visiting=true;this._changeReported=false;var argc=arguments.length;var args=new Array(argc);for(var i=0;i<argc;++i){args[i]=arguments[i]}if(!(args[0]instanceof NodePath)){args[0]=new NodePath({root:args[0]}).get("root")}this.reset.apply(this,args);try{return this.visitWithoutReset(args[0])}finally{this._visiting=false}};PVp.reset=function(path){};PVp.visitWithoutReset=function(path){if(this instanceof this.Context){return this.visitor.visitWithoutReset(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{return context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{return visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visitWithoutReset,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visitWithoutReset(childPaths[i])}}return path.value}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};PVp.reportChanged=function(){this._changeReported=true};PVp.wasChangeReported=function(){return this._changeReported};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName);var path=this.currentPath;return path&&path.value};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};sharedContextProtoMethods.visit=function visit(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return PathVisitor.fromMethodsObject(newVisitor||this.visitor).visitWithoutReset(path)};sharedContextProtoMethods.reportChanged=function reportChanged(){this.visitor.reportChanged()};module.exports=PathVisitor},{"./node-path":113,"./types":118,assert:121}],115:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":118,assert:121}],116:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":113,"./types":118,assert:121}],117:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":118}],118:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName) };Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:121}],119:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":106,"./def/e4x":107,"./def/es6":108,"./def/es7":109,"./def/fb-harmony":110,"./def/mozilla":111,"./lib/equiv":112,"./lib/node-path":113,"./lib/path-visitor":114,"./lib/types":118}],120:[function(require,module,exports){},{}],121:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(util.isPrimitive(a)||util.isPrimitive(b)){return a===b}var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return false;if(aIsArgs){a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}var ka=objectKeys(a),kb=objectKeys(b),key,i;if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":146}],122:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}if(length>0&&length<=Buffer.poolSize)buf.parent=rootParent;return buf}function SlowBuffer(subject,encoding,noZero){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding,noZero);var buf=new Buffer(subject,encoding,noZero);delete buf.parent;return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length,2);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;if(length<0||offset<0||offset>this.length)throw new RangeError("attempt to write outside buffer bounds");var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i]&127)}return ret}function binarySlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;return val};Buffer.prototype.readUIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256))val+=this[offset+--byteLength]*mul;return val};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256))val+=this[offset+--i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(target_start>=target.length)target_start=target.length;if(!target_start)target_start=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||source.length===0)return 0;if(target_start<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=source.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}return len};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new RangeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer }}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUIntLE=BP.readUIntLE;arr.readUIntBE=BP.readUIntBE;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readIntLE=BP.readIntLE;arr.readIntBE=BP.readIntBE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUIntLE=BP.writeUIntLE;arr.writeUIntBE=BP.writeUIntBE;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeIntLE=BP.writeIntLE;arr.writeIntBE=BP.writeIntBE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z\-]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){var codePoint,length=string.length;var leadSurrogate=null;units=units||Infinity;var bytes=[];var i=0;for(;i<length;i++){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(leadSurrogate){if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}else{codePoint=leadSurrogate-55296<<10|codePoint-56320|65536;leadSurrogate=null}}else{if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}else{leadSurrogate=codePoint;continue}}}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=null}if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<2097152){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length,unitSize){if(unitSize)length-=length%unitSize;for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":123,ieee754:124,"is-array":125}],123:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;if(code===SLASH||code===SLASH_URL_SAFE)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],124:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.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)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],125:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],126:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],127:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],128:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],129:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:130}],130:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;function drainQueue(){if(draining){return}draining=true;var currentQueue;var len=queue.length;while(len){currentQueue=queue;queue=[];var i=-1;while(++i<len){currentQueue[i]()}len=queue.length}draining=false}process.nextTick=function(fun){queue.push(fun);if(!draining){setTimeout(drainQueue,0)}};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],131:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":132}],132:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":134,"./_stream_writable":136,_process:130,"core-util-is":137,inherits:127}],133:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":135,"core-util-is":137,inherits:127}],134:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause")};function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:130,buffer:122,"core-util-is":137,events:126,inherits:127,isarray:128,stream:142,"string_decoder/":143}],135:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false; this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":132,"core-util-is":137,inherits:127}],136:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":132,_process:130,buffer:122,"core-util-is":137,inherits:127,stream:142}],137:[function(require,module,exports){(function(Buffer){function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:122}],138:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":133}],139:[function(require,module,exports){var Stream=require("stream");exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":132,"./lib/_stream_passthrough.js":133,"./lib/_stream_readable.js":134,"./lib/_stream_transform.js":135,"./lib/_stream_writable.js":136,stream:142}],140:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":135}],141:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":136}],142:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:126,inherits:127,"readable-stream/duplex.js":131,"readable-stream/passthrough.js":138,"readable-stream/readable.js":139,"readable-stream/transform.js":140,"readable-stream/writable.js":141}],143:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:122}],144:[function(require,module,exports){exports.isatty=function(){return false};function ReadStream(){throw new Error("tty.ReadStream is not implemented")}exports.ReadStream=ReadStream;function WriteStream(){throw new Error("tty.ReadStream is not implemented")}exports.WriteStream=WriteStream},{}],145:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],146:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":145,_process:130,inherits:127}],147:[function(require,module,exports){"use strict";var escapeStringRegexp=require("escape-string-regexp");var ansiStyles=require("ansi-styles");var stripAnsi=require("strip-ansi");var hasAnsi=require("has-ansi");var supportsColor=require("supports-color");var defineProps=Object.defineProperties;var chalk=module.exports;function build(_styles){var builder=function builder(){return applyStyle.apply(builder,arguments)};builder._styles=_styles;builder.__proto__=proto;return builder}var styles=function(){var ret={};ansiStyles.grey=ansiStyles.gray;Object.keys(ansiStyles).forEach(function(key){ansiStyles[key].closeRe=new RegExp(escapeStringRegexp(ansiStyles[key].close),"g");ret[key]={get:function(){return build(this._styles.concat(key))}}});return ret}();var proto=defineProps(function chalk(){},styles);function applyStyle(){var args=arguments;var argsLen=args.length;var str=argsLen!==0&&String(arguments[0]);if(argsLen>1){for(var a=1;a<argsLen;a++){str+=" "+args[a]}}if(!chalk.enabled||!str){return str}var nestedStyles=this._styles;for(var i=0;i<nestedStyles.length;i++){var code=ansiStyles[nestedStyles[i]];str=code.open+str.replace(code.closeRe,code.open)+code.close}return str}function init(){var ret={};Object.keys(styles).forEach(function(name){ret[name]={get:function(){return build([name])}}});return ret}defineProps(chalk,init());chalk.styles=ansiStyles;chalk.hasColor=hasAnsi;chalk.stripColor=stripAnsi;chalk.supportsColor=supportsColor;if(chalk.enabled===undefined){chalk.enabled=chalk.supportsColor}},{"ansi-styles":148,"escape-string-regexp":149,"has-ansi":150,"strip-ansi":152,"supports-color":154}],148:[function(require,module,exports){"use strict";var styles=module.exports;var codes={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]};Object.keys(codes).forEach(function(key){var val=codes[key];var style=styles[key]={};style.open="["+val[0]+"m";style.close="["+val[1]+"m"})},{}],149:[function(require,module,exports){"use strict";var matchOperatorsRe=/[|\\{}()[\]^$+*?.]/g;module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}return str.replace(matchOperatorsRe,"\\$&")}},{}],150:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex");var re=new RegExp(ansiRegex().source);module.exports=re.test.bind(re)},{"ansi-regex":151}],151:[function(require,module,exports){"use strict";module.exports=function(){return/\u001b\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]/g}},{}],152:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex")();module.exports=function(str){return typeof str==="string"?str.replace(ansiRegex,""):str}},{"ansi-regex":153}],153:[function(require,module,exports){arguments[4][151][0].apply(exports,arguments)},{dup:151}],154:[function(require,module,exports){(function(process){"use strict";module.exports=function(){if(process.argv.indexOf("--no-color")!==-1){return false}if(process.argv.indexOf("--color")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:130}],155:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&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(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){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]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict; function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},DOT,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);AllSymbols[tag]=true;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(key);return result}})}(safeSymbol("tag"),{},{},true);!function(RegExpProto,isFinite,tmp,NAME){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1},E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapfn=arguments[1],that=arguments[2],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames");if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}});if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){var _RegExp=RegExp;RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(RegExp);setSpecies(Array)}(RegExp[PROTOTYPE],isFinite,{},"name");isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&&notify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){return iter.o=undefined,iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;entry.p=entry.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&DESC&&new WeakMap([[Object.freeze(tmp),7]]).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return desc.get?desc.get.call(receiver):desc.value;return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc){if(desc.writable===false)return false;if(desc.set)return desc.set.call(receiver,V),true}if(isObject(proto=getPrototypeOf(target)))return reflectSet(proto,propertyKey,V,receiver);desc=getOwnDescriptor(receiver,propertyKey)||descriptor(0);desc.value=V;return defineProperty(receiver,propertyKey,desc),true}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList);!function(DICT){Dict=function(iterable){var dict=create(null);if(iterable!=undefined){if(isIterable(iterable)){for(var iter=getIterator(iterable),step,value;!(step=iter.next()).done;){value=step.value;dict[value[0]]=value[1]}}else assign(dict,iterable)}return dict};Dict[PROTOTYPE]=null;function DictIterator(iterated,kind){set(this,ITER,{o:toObject(iterated),a:getKeys(iterated),i:0,k:kind})}createIterator(DictIterator,DICT,function(){var iter=this[ITER],O=iter.o,keys=iter.a,kind=iter.k,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!has(O,key=keys[iter.i++]));if(kind==KEY)return iterResult(0,key);if(kind==VALUE)return iterResult(0,O[key]);return iterResult(0,[key,O[key]])});function createDictIter(kind){return function(it){return new DictIterator(it,kind)}}function createDictMethod(type){var isMap=type==1,isEvery=type==4;return function(object,callbackfn,that){var f=ctx(callbackfn,that,3),O=toObject(object),result=isMap||type==7||type==2?new(generic(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(isMap)result[key]=res;else if(res)switch(type){case 2:result[key]=val;break;case 3:return true;case 5:return val;case 6:return key;case 7:result[res[0]]=res[1]}else if(isEvery)return false}}return type==3||isEvery?isEvery:result}}function createDictReduce(isTurn){return function(object,mapfn,init){assertFunction(mapfn);var O=toObject(object),keys=getKeys(O),length=keys.length,i=0,memo,key,result;if(isTurn)memo=init==undefined?new(generic(this,Dict)):Object(init);else if(arguments.length<3){assert(length,REDUCE_ERROR);memo=O[keys[i++]]}else memo=Object(init);while(length>i)if(has(O,key=keys[i++])){result=mapfn(memo,O[key],key,object);if(isTurn){if(result===false)break}else memo=result}return memo}}var findKey=createDictMethod(6);function includes(object,el){return(el==el?keyOf(object,el):findKey(object,sameNaN))!==undefined}var dictMethods={keys:createDictIter(KEY),values:createDictIter(VALUE),entries:createDictIter(KEY+VALUE),forEach:createDictMethod(0),map:createDictMethod(1),filter:createDictMethod(2),some:createDictMethod(3),every:createDictMethod(4),find:createDictMethod(5),findKey:findKey,mapPairs:createDictMethod(7),reduce:createDictReduce(false),turn:createDictReduce(true),keyOf:keyOf,includes:includes,has:has,get:get,set:createDefiner(0),isDict:function(it){return isObject(it)&&getPrototypeOf(it)===Dict[PROTOTYPE]}};if(REFERENCE_GET)for(var key in dictMethods)!function(fn){function method(){for(var args=[this],i=0;i<arguments.length;)args.push(arguments[i++]);return invoke(fn,args)}fn[REFERENCE_GET]=function(){return method}}(dictMethods[key]);$define(GLOBAL+FORCED,{Dict:assignHidden(Dict,dictMethods)})}("Dict");!function(ENTRIES,FN){function $for(iterable,entries){if(!(this instanceof $for))return new $for(iterable,entries);this[ITER]=getIterator(iterable);this[ENTRIES]=!!entries}createIterator($for,"Wrapper",function(){return this[ITER].next()});var $forProto=$for[PROTOTYPE];setIterator($forProto,function(){return this[ITER]});function createChainIterator(next){function Iter(I,fn,that){this[ITER]=getIterator(I);this[ENTRIES]=I[ENTRIES];this[FN]=ctx(fn,that,I[ENTRIES]?2:1)}createIterator(Iter,"Chain",next,$forProto);setIterator(Iter[PROTOTYPE],returnThis);return Iter}var MapIter=createChainIterator(function(){var step=this[ITER].next();return step.done?step:iterResult(0,stepCall(this[FN],step.value,this[ENTRIES]))});var FilterIter=createChainIterator(function(){for(;;){var step=this[ITER].next();if(step.done||stepCall(this[FN],step.value,this[ENTRIES]))return step}});assignHidden($forProto,{of:function(fn,that){forOf(this,this[ENTRIES],fn,that)},array:function(fn,that){var result=[];forOf(fn!=undefined?this.map(fn,that):this,false,push,result);return result},filter:function(fn,that){return new FilterIter(this,fn,that)},map:function(fn,that){return new MapIter(this,fn,that)}});$for.isIterable=isIterable;$for.getIterator=getIterator;$define(GLOBAL+FORCED,{$for:$for})}("entries",safeSymbol("fn"));!function(_,toLocaleString){core._=path._=path._||{};$define(PROTO+FORCED,FUNCTION,{part:part,only:function(numberArguments,that){var fn=assertFunction(this),n=toLength(numberArguments),isThat=arguments.length>1;return function(){var length=min(n,arguments.length),args=Array(length),i=0;while(length>i)args[i]=arguments[i++];return invoke(fn,args,isThat?that:this)}}});function tie(key){var that=this,bound={};return hidden(that,_,function(key){if(key===undefined||!(key in that))return toLocaleString.call(that);return has(bound,key)?bound[key]:bound[key]=ctx(that[key],that,-1)})[_](key)}hidden(path._,TO_STRING,function(){return _});hidden(ObjectProto,_,tie);DESC||hidden(ArrayProto,_,tie)}(DESC?uid("tie"):TO_LOCALE,ObjectProto[TO_LOCALE]);!function(){function define(target,mixin){var keys=ownKeys(toObject(mixin)),length=keys.length,i=0,key;while(length>i)defineProperty(target,key=keys[i++],getOwnDescriptor(mixin,key));return target}$define(STATIC+FORCED,OBJECT,{isObject:isObject,classof:classof,define:define,make:function(proto,mixin){return define(create(proto),mixin)}})}();$define(PROTO+FORCED,ARRAY,{turn:function(fn,target){assertFunction(fn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;while(length>index)if(fn(memo,O[index],index++,this)===false)break;return memo}});if(framework)ArrayUnscopables.turn=true;!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(numberMethods){function NumberIterator(iterated){set(this,ITER,{l:toLength(iterated),i:0})}createIterator(NumberIterator,NUMBER,function(){var iter=this[ITER],i=iter.i++;return i<iter.l?iterResult(0,i):iterResult(1)});defineIterator(Number,NUMBER,function(){return new NumberIterator(this)});numberMethods.random=function(lim){var a=+this,b=lim==undefined?0:+lim,m=min(a,b);return random()*(max(a,b)-m)+m};forEach.call(array("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,"+"acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(key){var fn=Math[key];if(fn)numberMethods[key]=function(){var args=[+this],i=0;while(arguments.length>i)args.push(arguments[i++]);return invoke(fn,args)}});$define(PROTO+FORCED,NUMBER,numberMethods)}({});!function(){var escapeHTMLDict={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"},unescapeHTMLDict={},key;for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]]=key;$define(PROTO+FORCED,STRING,{escapeHTML:createReplacer(/[&<>"']/g,escapeHTMLDict),unescapeHTML:createReplacer(/&(?:amp|lt|gt|quot|apos);/g,unescapeHTMLDict)})}();!function(formatRegExp,flexioRegExp,locales,current,SECONDS,MINUTES,HOURS,MONTH,YEAR){function createFormat(prefix){return function(template,locale){var that=this,dict=locales[has(locales,locale)?locale:current];function get(unit){return that[prefix+unit]()}return String(template).replace(formatRegExp,function(part){switch(part){case"s":return get(SECONDS);case"ss":return lz(get(SECONDS));case"m":return get(MINUTES);case"mm":return lz(get(MINUTES));case"h":return get(HOURS);case"hh":return lz(get(HOURS));case"D":return get(DATE);case"DD":return lz(get(DATE));case"W":return dict[0][get("Day")];case"N":return get(MONTH)+1;case"NN":return lz(get(MONTH)+1);case"M":return dict[2][get(MONTH)];case"MM":return dict[1][get(MONTH)];case"Y":return get(YEAR);case"YY":return lz(get(YEAR)%100)}return part})}}function lz(num){return num>9?num:"0"+num}function addLocale(lang,locale){function split(index){var result=[];forEach.call(array(locale.months),function(it){result.push(it.replace(flexioRegExp,"$"+index))});return result}locales[lang]=[array(locale.weekdays),split(1),split(2)];return core}$define(PROTO+FORCED,DATE,{format:createFormat("get"),formatUTC:createFormat("getUTC")});addLocale(current,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"});addLocale("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});core.locale=function(locale){return has(locales,locale)?current=locale:current};core.addLocale=addLocale}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear")}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),false)},{}],156:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false}}for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true}}return false}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:158}],157:[function(require,module,exports){(function(process){var tty=require("tty");var util=require("util");exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=[6,2,3,4,5,1];var fd=parseInt(process.env.DEBUG_FD,10)||2;var stream=1===fd?process.stdout:2===fd?process.stderr:createWritableStdioStream(fd);function useColors(){var debugColors=(process.env.DEBUG_COLORS||"").trim().toLowerCase();if(0===debugColors.length){return tty.isatty(fd)}else{return"0"!==debugColors&&"no"!==debugColors&&"false"!==debugColors&&"disabled"!==debugColors}}var inspect=4===util.inspect.length?function(v,colors){return util.inspect(v,void 0,void 0,colors)}:function(v,colors){return util.inspect(v,{colors:colors})};exports.formatters.o=function(v){return inspect(v,this.useColors).replace(/\s*\n\s*/g," ")};function formatArgs(){var args=arguments;var useColors=this.useColors;var name=this.namespace;if(useColors){var c=this.color;args[0]=" [9"+c+"m"+name+" "+""+args[0]+"[3"+c+"m"+" +"+exports.humanize(this.diff)+""}else{args[0]=(new Date).toUTCString()+" "+name+" "+args[0]}return args}function log(){return stream.write(util.format.apply(this,arguments)+"\n")}function save(namespaces){if(null==namespaces){delete process.env.DEBUG}else{process.env.DEBUG=namespaces}}function load(){return process.env.DEBUG}function createWritableStdioStream(fd){var stream;var tty_wrap=process.binding("tty_wrap");switch(tty_wrap.guessHandleType(fd)){case"TTY":stream=new tty.WriteStream(fd);stream._type="tty";if(stream._handle&&stream._handle.unref){stream._handle.unref()}break;case"FILE":var fs=require("fs");stream=new fs.SyncWriteStream(fd,{autoClose:false});stream._type="fs";break;case"PIPE":case"TCP":var net=require("net");stream=new net.Socket({fd:fd,readable:false,writable:true});stream.readable=false;stream.read=null;stream._type="pipe";if(stream._handle&&stream._handle.unref){stream._handle.unref()}break;default:throw new Error("Implement me. Unknown stream file type!")}stream.fd=fd;stream._isStdio=true;return stream}exports.enable(load())}).call(this,require("_process"))},{"./debug":156,_process:130,fs:120,net:120,tty:144,util:146}],158:[function(require,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){var match=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"h":return n*h;case"minutes":case"minute":case"m":return n*m;case"seconds":case"second":case"s":return n*s;case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],159:[function(require,module,exports){"use strict";var repeating=require("repeating");var INDENT_RE=/^(?:( )+|\t+)/;function getMostUsed(indents){var result=0;var maxUsed=0;var maxWeight=0;for(var n in indents){var indent=indents[n];var u=indent[0];var w=indent[1];if(u>maxUsed||u===maxUsed&&w>maxWeight){maxUsed=u;maxWeight=w;result=+n}}return result}module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}var tabs=0;var spaces=0;var prev=0;var indents={};var current;var isIndent;str.split(/\n/g).forEach(function(line){if(!line){return}var indent;var matches=line.match(INDENT_RE);if(!matches){indent=0}else{indent=matches[0].length;if(matches[1]){spaces++}else{tabs++}}var diff=indent-prev;prev=indent;if(diff){isIndent=diff>0;current=indents[isIndent?diff:-diff];if(current){current[0]++}else{current=indents[diff]=[1,0]}}else if(current){current[1]+=+isIndent}});var amount=getMostUsed(indents);var type;var actual;if(!amount){type=null;actual=""}else if(spaces>=tabs){type="space";actual=repeating(" ",amount)}else{type="tab";actual=repeating(" ",amount)}return{amount:amount,type:type,indent:actual}}},{repeating:160}],160:[function(require,module,exports){"use strict";var isFinite=require("is-finite");module.exports=function(str,n){if(typeof str!=="string"){throw new TypeError("Expected a string as the first argument")}if(n<0||!isFinite(n)){throw new TypeError("Expected a finite positive number")}var ret="";do{if(n&1){ret+=str}str+=str}while(n=n>>1);return ret}},{"is-finite":161}],161:[function(require,module,exports){"use strict";module.exports=Number.isFinite||function(val){if(typeof val!=="number"||val!==val||val===Infinity||val===-Infinity){return false}return true}},{}],162:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function clone(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.1-dev";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})},{}],163:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],164:[function(require,module,exports){(function(){"use strict";var Regex,NON_ASCII_WHITESPACES;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")}; function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}NON_ASCII_WHITESPACES=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&NON_ASCII_WHITESPACES.indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],165:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":164}],166:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":163,"./code":164,"./keyword":165}],167:[function(require,module,exports){function combine(){return new RegExp("("+[].slice.call(arguments).map(function(e){var e=e.toString();return"(?:"+e.substring(1,e.length-1)+")"}).join("|")+")")}function makeTester(rx){var s=rx.toString();return new RegExp("^"+s.substring(1,s.length-1)+"$")}var pattern={string1:/"(?:(?:\\\n|\\"|[^"\n]))*?"/,string2:/'(?:(?:\\\n|\\'|[^'\n]))*?'/,comment1:/\/\*[\s\S]*?\*\//,comment2:/\/\/.*?\n/,whitespace:/\s+/,keyword:/\b(?:var|let|for|if|else|in|class|function|return|with|case|break|switch|export|new|while|do|throw|catch)\b/,regexp:/\/(?:(?:\\\/|[^\n\/]))*?\//,name:/[a-zA-Z_\$][a-zA-Z_\$0-9]*/,number:/\d+(?:\.\d+)?(?:e[+-]?\d+)?/,parens:/[\(\)]/,curly:/[{}]/,square:/[\[\]]/,punct:/[;.:\?\^%<>=!&|+\-,~]/};var match=combine(pattern.string1,pattern.string2,pattern.comment1,pattern.comment2,pattern.regexp,pattern.whitespace,pattern.name,pattern.number,pattern.parens,pattern.curly,pattern.square,pattern.punct);var tester={};for(var k in pattern){tester[k]=makeTester(pattern[k])}module.exports=function(str,doNotThrow){return str.split(match).filter(function(e,i){if(i%2)return true;if(e!==""){if(!doNotThrow)throw new Error("invalid token:"+JSON.stringify(e));return true}})};module.exports.type=function(e){for(var type in pattern)if(tester[type].test(e))return type;return"invalid"}},{}],168:[function(require,module,exports){(function(global){(function(){var undefined;var VERSION="3.0.0";var BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,REARG_FLAG=128,ARY_FLAG=256;var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...";var HOT_COUNT=150,HOT_SPAN=16;var LAZY_FILTER_FLAG=0,LAZY_MAP_FLAG=1,LAZY_WHILE_FLAG=2;var FUNC_ERROR_TEXT="Expected a function";var PLACEHOLDER="__lodash_placeholder__";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]",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]";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reFuncName=/^\s*function[ \n\r\t]+\w/;var reHexPrefix=/^0[xX]/;var reHostCtor=/^\[object .+?Constructor\]$/;var reLatin1=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;var reNoMatch=/($^)/;var reRegExpChars=/[.*+?^${}()|[\]\/\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source);var reThis=/\bthis\b/;var reUnescapedString=/['\n\r\u2028\u2029\\]/g;var reWords=function(){var upper="[A-Z\\xc0-\\xd6\\xd8-\\xde]",lower="[a-z\\xdf-\\xf6\\xf8-\\xff]+";return RegExp(upper+"{2,}(?="+upper+lower+")|"+upper+"?"+lower+"|"+upper+"+|[0-9]+","g")}();var whitespace=" \f "+"\n\r\u2028\u2029"+" ᠎              ";var contextProps=["Array","ArrayBuffer","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Math","Number","Object","RegExp","Set","String","_","clearTimeout","document","isFinite","parseInt","setTimeout","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","window","WinRTError"];var templateCounter=-1;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[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=false;var debounceOptions={leading:false,maxWait:0,trailing:false};var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss"};var htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","`":"&#96;"};var htmlUnescapes={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&#96;":"`"};var objectTypes={"function":true,object:true};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"};var root=objectTypes[typeof window]&&window!==(this&&this.window)?window:this;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports;function baseCompareAscending(value,other){if(value!==other){var valIsReflexive=value===value,othIsReflexive=other===other;if(value>other||!valIsReflexive||typeof value=="undefined"&&othIsReflexive){return 1}if(value<other||!othIsReflexive||typeof other=="undefined"&&valIsReflexive){return-1}}return 0}function baseIndexOf(array,value,fromIndex){if(value!==value){return indexOfNaN(array,fromIndex)}var index=(fromIndex||0)-1,length=array.length;while(++index<length){if(array[index]===value){return index}}return-1}function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value}return array}function baseToString(value){if(typeof value=="string"){return value}return value==null?"":value+""}function charAtCallback(string){return string.charCodeAt(0)}function charsLeftIndex(string,chars){var index=-1,length=string.length;while(++index<length&&chars.indexOf(string.charAt(index))>-1){}return index}function charsRightIndex(string,chars){var index=string.length;while(index--&&chars.indexOf(string.charAt(index))>-1){}return index}function compareAscending(object,other){return baseCompareAscending(object.criteria,other.criteria)||object.index-other.index}function compareMultipleAscending(object,other){var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length;while(++index<length){var result=baseCompareAscending(objCriteria[index],othCriteria[index]);if(result){return result}}return object.index-other.index}function deburrLetter(letter){return deburredLetters[letter]}function escapeHtmlChar(chr){return htmlEscapes[chr]}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function indexOfNaN(array,fromIndex,fromRight){var length=array.length,index=fromRight?fromIndex||length:(fromIndex||0)-1;while(fromRight?index--:++index<length){var other=array[index];if(other!==other){return index}}return-1}function isObjectLike(value){return value&&typeof value=="object"||false}function isSpace(charCode){return charCode<=160&&(charCode>=9&&charCode<=13)||charCode==32||charCode==160||charCode==5760||charCode==6158||charCode>=8192&&(charCode<=8202||charCode==8232||charCode==8233||charCode==8239||charCode==8287||charCode==12288||charCode==65279)}function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){if(array[index]===placeholder){array[index]=PLACEHOLDER;result[++resIndex]=index}}return result}function sortedUniq(array,iteratee){var seen,index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(!index||seen!==computed){seen=computed;result[++resIndex]=value}}return result}function trimmedLeftIndex(string){var index=-1,length=string.length;while(++index<length&&isSpace(string.charCodeAt(index))){}return index}function trimmedRightIndex(string){var index=string.length;while(index--&&isSpace(string.charCodeAt(index))){}return index}function unescapeHtmlChar(chr){return htmlUnescapes[chr]}function runInContext(context){context=context?_.defaults(root.Object(),context,_.pick(root,contextProps)):root;var Array=context.Array,Date=context.Date,Error=context.Error,Function=context.Function,Math=context.Math,Number=context.Number,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;var arrayProto=Array.prototype,objectProto=Object.prototype;var document=(document=context.window)&&document.document;var fnToString=Function.prototype.toString;var getLength=baseProperty("length");var hasOwnProperty=objectProto.hasOwnProperty;var idCounter=0;var objToString=objectProto.toString;var oldDash=context._;var reNative=RegExp("^"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var ArrayBuffer=isNative(ArrayBuffer=context.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,ceil=Math.ceil,clearTimeout=context.clearTimeout,floor=Math.floor,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,propertyIsEnumerable=objectProto.propertyIsEnumerable,Set=isNative(Set=context.Set)&&Set,setTimeout=context.setTimeout,splice=arrayProto.splice,Uint8Array=isNative(Uint8Array=context.Uint8Array)&&Uint8Array,unshift=arrayProto.unshift,WeakMap=isNative(WeakMap=context.WeakMap)&&WeakMap;var Float64Array=function(){try{var func=isNative(func=context.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}();var nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate,nativeIsFinite=context.isFinite,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,nativeNow=isNative(nativeNow=Date.now)&&nativeNow,nativeNumIsFinite=isNative(nativeNumIsFinite=Number.isFinite)&&nativeNumIsFinite,nativeParseInt=context.parseInt,nativeRandom=Math.random;var NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,POSITIVE_INFINITY=Number.POSITIVE_INFINITY;var MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;var FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0;var MAX_SAFE_INTEGER=Math.pow(2,53)-1;var metaMap=WeakMap&&new WeakMap;function lodash(value){if(isObjectLike(value)&&!isArray(value)){if(value instanceof LodashWrapper){return value}if(hasOwnProperty.call(value,"__wrapped__")){return new LodashWrapper(value.__wrapped__,value.__chain__,arrayCopy(value.__actions__))}}return new LodashWrapper(value)}function LodashWrapper(value,chainAll,actions){this.__actions__=actions||[];this.__chain__=!!chainAll;this.__wrapped__=value}var support=lodash.support={};(function(x){support.funcDecomp=!isNative(context.WinRTError)&&reThis.test(runInContext);support.funcNames=typeof Function.name=="string";try{support.dom=document.createDocumentFragment().nodeType===11}catch(e){support.dom=false}try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=true}})(0,0);lodash.templateSettings={escape:reEscape,evaluate:reEvaluate,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function LazyWrapper(value){this.actions=null;this.dir=1;this.dropCount=0;this.filtered=false;this.iteratees=null;this.takeCount=POSITIVE_INFINITY;this.views=null;this.wrapped=value}function lazyClone(){var actions=this.actions,iteratees=this.iteratees,views=this.views,result=new LazyWrapper(this.wrapped);result.actions=actions?arrayCopy(actions):null;result.dir=this.dir;result.dropCount=this.dropCount;result.filtered=this.filtered;result.iteratees=iteratees?arrayCopy(iteratees):null;result.takeCount=this.takeCount;result.views=views?arrayCopy(views):null;return result}function lazyReverse(){var filtered=this.filtered,result=filtered?new LazyWrapper(this):this.clone();result.dir=this.dir*-1;result.filtered=filtered;return result}function lazyValue(){var array=this.wrapped.value();if(!isArray(array)){return baseWrapperValue(array,this.actions)}var dir=this.dir,isRight=dir<0,length=array.length,view=getView(0,length,this.views),start=view.start,end=view.end,dropCount=this.dropCount,takeCount=nativeMin(end-start,this.takeCount-dropCount),index=isRight?end:start-1,iteratees=this.iteratees,iterLength=iteratees?iteratees.length:0,resIndex=0,result=[];outer:while(length--&&resIndex<takeCount){index+=dir;var iterIndex=-1,value=array[index];while(++iterIndex<iterLength){var data=iteratees[iterIndex],iteratee=data.iteratee,computed=iteratee(value,index,array),type=data.type;if(type==LAZY_MAP_FLAG){value=computed}else if(!computed){if(type==LAZY_FILTER_FLAG){continue outer}else{break outer}}}if(dropCount){dropCount--}else{result[resIndex++]=value}}return isRight?result.reverse():result}function MapCache(){this.__data__={}}function mapDelete(key){return this.has(key)&&delete this.__data__[key]}function mapGet(key){return key=="__proto__"?undefined:this.__data__[key]}function mapHas(key){return key!="__proto__"&&hasOwnProperty.call(this.__data__,key)}function mapSet(key,value){if(key!="__proto__"){this.__data__[key]=value}return this}function SetCache(values){var length=values?values.length:0;this.data={hash:nativeCreate(null),set:new Set};while(length--){this.push(values[length])}}function cacheIndexOf(cache,value){var data=cache.data,result=typeof value=="string"||isObject(value)?data.set.has(value):data.hash[value];return result?0:-1}function cachePush(value){var data=this.data;if(typeof value=="string"||isObject(value)){data.set.add(value)}else{data.hash[value]=true}}function arrayCopy(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index]}return array}function arrayEach(array,iteratee){var index=-1,length=array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break}}return array}function arrayEachRight(array,iteratee){var length=array.length;while(length--){if(iteratee(array[length],length,array)===false){break}}return array}function arrayEvery(array,predicate){var index=-1,length=array.length;while(++index<length){if(!predicate(array[index],index,array)){return false}}return true}function arrayFilter(array,predicate){var index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[++resIndex]=value}}return result}function arrayMap(array,iteratee){var index=-1,length=array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array)}return result}function arrayMax(array){var index=-1,length=array.length,result=NEGATIVE_INFINITY;while(++index<length){var value=array[index];if(value>result){result=value}}return result}function arrayMin(array){var index=-1,length=array.length,result=POSITIVE_INFINITY;while(++index<length){var value=array[index];if(value<result){result=value}}return result}function arrayReduce(array,iteratee,accumulator,initFromArray){var index=-1,length=array.length;if(initFromArray&&length){accumulator=array[++index]}while(++index<length){accumulator=iteratee(accumulator,array[index],index,array)}return accumulator}function arrayReduceRight(array,iteratee,accumulator,initFromArray){var length=array.length;if(initFromArray&&length){accumulator=array[--length]}while(length--){accumulator=iteratee(accumulator,array[length],length,array)}return accumulator}function arraySome(array,predicate){var index=-1,length=array.length;while(++index<length){if(predicate(array[index],index,array)){return true}}return false}function assignDefaults(objectValue,sourceValue){return typeof objectValue=="undefined"?sourceValue:objectValue}function assignOwnDefaults(objectValue,sourceValue,key,object){return typeof objectValue=="undefined"||!hasOwnProperty.call(object,key)?sourceValue:objectValue}function baseAssign(object,source,customizer){var props=keys(source);if(!customizer){return baseCopy(source,object,props)}var index=-1,length=props.length;while(++index<length){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);if((result===result?result!==value:value===value)||typeof value=="undefined"&&!(key in object)){object[key]=result}}return object}function baseAt(collection,props){var index=-1,length=collection.length,isArr=isLength(length),propsLength=props.length,result=Array(propsLength);while(++index<propsLength){var key=props[index];if(isArr){key=parseFloat(key);result[index]=isIndex(key,length)?collection[key]:undefined}else{result[index]=collection[key]}}return result}function baseCopy(source,object,props){if(!props){props=object;object={}}var index=-1,length=props.length;while(++index<length){var key=props[index];object[key]=source[key]}return object}function baseBindAll(object,methodNames){var index=-1,length=methodNames.length;while(++index<length){var key=methodNames[index];object[key]=createWrapper(object[key],BIND_FLAG,object)}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;if(type=="function"){return typeof thisArg!="undefined"&&isBindable(func)?bindCallback(func,thisArg,argCount):func}if(func==null){return identity}return type=="object"?baseMatches(func,!argCount):baseProperty(argCount?baseToString(func):func)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer){result=object?customizer(value,key,object):customizer(value)}if(typeof result!="undefined"){return result}if(!isObject(value)){return value}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return arrayCopy(value,result)}}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag==objectTag||tag==argsTag||isFunc&&!object){result=initCloneObject(isFunc?{}:value);if(!isDeep){return baseCopy(value,result,keys(value))}}else{return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{}}}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}stackA.push(value);stackB.push(result);(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)});return result}var baseCreate=function(){function Object(){}return function(prototype){if(isObject(prototype)){Object.prototype=prototype;var result=new Object;Object.prototype=null}return result||context.Object()}}();function baseDelay(func,wait,args,fromIndex){if(!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}return setTimeout(function(){func.apply(undefined,baseSlice(args,fromIndex))},wait)}function baseDifference(array,values){var length=array?array.length:0,result=[];if(!length){return result}var index=-1,indexOf=getIndexOf(),isCommon=indexOf==baseIndexOf,cache=isCommon&&values.length>=200&&createCache(values),valuesLength=values.length;if(cache){indexOf=cacheIndexOf;isCommon=false;values=cache}outer:while(++index<length){var value=array[index];if(isCommon&&value===value){var valuesIndex=valuesLength;while(valuesIndex--){if(values[valuesIndex]===value){continue outer}}result.push(value)}else if(indexOf(values,value)<0){result.push(value)}}return result}function baseEach(collection,iteratee){var length=collection?collection.length:0;if(!isLength(length)){return baseForOwn(collection,iteratee)}var index=-1,iterable=toObject(collection);while(++index<length){if(iteratee(iterable[index],index,iterable)===false){break}}return collection}function baseEachRight(collection,iteratee){var length=collection?collection.length:0;if(!isLength(length)){return baseForOwnRight(collection,iteratee)}var iterable=toObject(collection);while(length--){if(iteratee(iterable[length],length,iterable)===false){break}}return collection}function baseEvery(collection,predicate){var result=true;baseEach(collection,function(value,index,collection){result=!!predicate(value,index,collection);return result});return result}function baseFilter(collection,predicate){var result=[];baseEach(collection,function(value,index,collection){if(predicate(value,index,collection)){result.push(value)}});return result}function baseFind(collection,predicate,eachFunc,retKey){var result;eachFunc(collection,function(value,key,collection){if(predicate(value,key,collection)){result=retKey?key:value;return false}});return result}function baseFlatten(array,isDeep,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index];if(isObjectLike(value)&&isLength(value.length)&&(isArray(value)||isArguments(value))){if(isDeep){value=baseFlatten(value,isDeep,isStrict)}var valIndex=-1,valLength=value.length;result.length+=valLength;while(++valIndex<valLength){result[++resIndex]=value[valIndex]}}else if(!isStrict){result[++resIndex]=value}}return result}function baseFor(object,iteratee,keysFunc){var index=-1,iterable=toObject(object),props=keysFunc(object),length=props.length;while(++index<length){var key=props[index];if(iteratee(iterable[key],key,iterable)===false){break}}return object}function baseForRight(object,iteratee,keysFunc){var iterable=toObject(object),props=keysFunc(object),length=props.length;while(length--){var key=props[length];if(iteratee(iterable[key],key,iterable)===false){break}}return object}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return baseForRight(object,iteratee,keys)}function baseFunctions(object,props){var index=-1,length=props.length,resIndex=-1,result=[];while(++index<length){var key=props[index];if(isFunction(object[key])){result[++resIndex]=key}}return result}function baseInvoke(collection,methodName,args){var index=-1,isFunc=typeof methodName=="function",length=collection?collection.length:0,result=isLength(length)?Array(length):[];baseEach(collection,function(value){var func=isFunc?methodName:value!=null&&value[methodName];result[++index]=func?func.apply(value,args):undefined});return result}function baseIsEqual(value,other,customizer,isWhere,stackA,stackB){if(value===other){return value!==0||1/value==1/other}var valType=typeof value,othType=typeof other;if(valType!="function"&&valType!="object"&&othType!="function"&&othType!="object"||value==null||other==null){return value!==value&&other!==other}return baseIsEqualDeep(value,other,baseIsEqual,customizer,isWhere,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;if(!objIsArr){objTag=objToString.call(object);if(objTag==argsTag){objTag=objectTag}else if(objTag!=objectTag){objIsArr=isTypedArray(object)}}if(!othIsArr){othTag=objToString.call(other);if(othTag==argsTag){othTag=objectTag}else if(othTag!=objectTag){othIsArr=isTypedArray(other)}}var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!(objIsArr||objIsObj)){return equalByTag(object,other,objTag)}var valWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(valWrapped||othWrapped){return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isWhere,stackA,stackB)}if(!isSameTag){return false}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==object){return stackB[length]==other}}stackA.push(object);stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isWhere,stackA,stackB);stackA.pop();stackB.pop();return result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){var length=props.length;if(object==null){return!length}var index=-1,noCustomizer=!customizer;while(++index<length){if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!hasOwnProperty.call(object,props[index])){return false}}index=-1;while(++index<length){var key=props[index];if(noCustomizer&&strictCompareFlags[index]){var result=hasOwnProperty.call(object,key)}else{var objValue=object[key],srcValue=values[index];result=customizer?customizer(objValue,srcValue,key):undefined;if(typeof result=="undefined"){result=baseIsEqual(srcValue,objValue,customizer,true)}}if(!result){return false}}return true}function baseMap(collection,iteratee){var result=[];baseEach(collection,function(value,key,collection){result.push(iteratee(value,key,collection))});return result}function baseMatches(source,isCloned){var props=keys(source),length=props.length;if(length==1){var key=props[0],value=source[key];if(isStrictComparable(value)){return function(object){return object!=null&&value===object[key]&&hasOwnProperty.call(object,key)}}}if(isCloned){source=baseClone(source,true)}var values=Array(length),strictCompareFlags=Array(length);while(length--){value=source[props[length]];values[length]=value;strictCompareFlags[length]=isStrictComparable(value)}return function(object){return baseIsMatch(object,props,values,strictCompareFlags)}}function baseMerge(object,source,customizer,stackA,stackB){var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));(isSrcArr?arrayEach:baseForOwn)(source,function(srcValue,key,source){if(isObjectLike(srcValue)){stackA||(stackA=[]);stackB||(stackB=[]);return baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB)}var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=typeof result=="undefined";if(isCommon){result=srcValue}if((isSrcArr||typeof result!="undefined")&&(isCommon||(result===result?result!==value:value===value))){object[key]=result}});return object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){var length=stackA.length,srcValue=source[key];while(length--){if(stackA[length]==srcValue){object[key]=stackB[length];return}}var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=typeof result=="undefined";if(isCommon){result=srcValue;if(isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))){result=isArray(value)?value:value?arrayCopy(value):[]}else if(isPlainObject(srcValue)||isArguments(srcValue)){result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}}}stackA.push(srcValue);stackB.push(result);if(isCommon){object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB)}else if(result===result?result!==value:value===value){object[key]=result}}function baseProperty(key){return function(object){return object==null?undefined:object[key]}}function basePullAt(array,indexes){var length=indexes.length,result=baseAt(array,indexes);indexes.sort(baseCompareAscending);while(length--){var index=parseFloat(indexes[length]);if(index!=previous&&isIndex(index)){var previous=index; splice.call(array,index,1)}}return result}function baseRandom(min,max){return min+floor(nativeRandom()*(max-min+1))}function baseReduce(collection,iteratee,accumulator,initFromCollection,eachFunc){eachFunc(collection,function(value,index,collection){accumulator=initFromCollection?(initFromCollection=false,value):iteratee(accumulator,value,index,collection)});return accumulator}var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func};function baseSlice(array,start,end){var index=-1,length=array.length;start=start==null?0:+start||0;if(start<0){start=-start>length?0:length+start}end=typeof end=="undefined"||end>length?length:+end||0;if(end<0){end+=length}length=start>end?0:end-start;var result=Array(length);while(++index<length){result[index]=array[index+start]}return result}function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return!result});return!!result}function baseUniq(array,iteratee){var index=-1,indexOf=getIndexOf(),length=array.length,isCommon=indexOf==baseIndexOf,isLarge=isCommon&&length>=200,seen=isLarge&&createCache(),result=[];if(seen){indexOf=cacheIndexOf;isCommon=false}else{isLarge=false;seen=iteratee?[]:result}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(isCommon&&value===value){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer}}if(iteratee){seen.push(computed)}result.push(value)}else if(indexOf(seen,computed)<0){if(iteratee||isLarge){seen.push(computed)}result.push(value)}}return result}function baseValues(object,props){var index=-1,length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}function baseWrapperValue(value,actions){var result=value;if(result instanceof LazyWrapper){result=result.value()}var index=-1,length=actions.length;while(++index<length){var args=[result],action=actions[index];push.apply(args,action.args);result=action.func.apply(action.thisArg,args)}return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(typeof value=="number"&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){while(low<high){var mid=low+high>>>1,computed=array[mid];if(retHighest?computed<=value:computed<value){low=mid+1}else{high=mid}}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=typeof value=="undefined";while(low<high){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN){var setLow=isReflexive||retHighest}else if(valIsUndef){setLow=isReflexive&&(retHighest||typeof computed!="undefined")}else{setLow=retHighest?computed<=value:computed<value}if(setLow){low=mid+1}else{high=mid}}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}if(!bufferSlice){bufferClone=!(ArrayBuffer&&Uint8Array)?constant(null):function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}if(byteLength!=offset){view=new Uint8Array(result,offset);view.set(new Uint8Array(buffer,offset))}return result}}function composeArgs(args,partials,holders){var holdersLength=holders.length,argsIndex=-1,argsLength=nativeMax(args.length-holdersLength,0),leftIndex=-1,leftLength=partials.length,result=Array(argsLength+leftLength);while(++leftIndex<leftLength){result[leftIndex]=partials[leftIndex]}while(++argsIndex<holdersLength){result[holders[argsIndex]]=args[argsIndex]}while(argsLength--){result[leftIndex++]=args[argsIndex++]}return result}function composeArgsRight(args,partials,holders){var holdersIndex=-1,holdersLength=holders.length,argsIndex=-1,argsLength=nativeMax(args.length-holdersLength,0),rightIndex=-1,rightLength=partials.length,result=Array(argsLength+rightLength);while(++argsIndex<argsLength){result[argsIndex]=args[argsIndex]}var pad=argsIndex;while(++rightIndex<rightLength){result[pad+rightIndex]=partials[rightIndex]}while(++holdersIndex<holdersLength){result[pad+holders[holdersIndex]]=args[argsIndex++]}return result}function createAggregator(setter,initializer){return function(collection,iteratee,thisArg){var result=initializer?initializer():{};iteratee=getCallback(iteratee,thisArg,3);if(isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];setter(result,value,iteratee(value,index,collection),collection)}}else{baseEach(collection,function(value,key,collection){setter(result,value,iteratee(value,key,collection),collection)})}return result}}function createAssigner(assigner){return function(){var length=arguments.length,object=arguments[0];if(length<2||object==null){return object}if(length>3&&isIterateeCall(arguments[1],arguments[2],arguments[3])){length=2}if(length>3&&typeof arguments[length-2]=="function"){var customizer=bindCallback(arguments[--length-1],arguments[length--],5)}else if(length>2&&typeof arguments[length-1]=="function"){customizer=arguments[--length]}var index=0;while(++index<length){var source=arguments[index];if(source){assigner(object,source,customizer)}}return object}}function createBindWrapper(func,thisArg){var Ctor=createCtorWrapper(func);function wrapper(){return(this instanceof wrapper?Ctor:func).apply(thisArg,arguments)}return wrapper}var createCache=!(nativeCreate&&Set)?constant(null):function(values){return new SetCache(values)};function createCompounder(callback){return function(string){var index=-1,array=words(deburr(string)),length=array.length,result="";while(++index<length){result=callback(result,array[index],index)}return result}}function createCtorWrapper(Ctor){return function(){var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,arguments);return isObject(result)?result:thisBinding}}function createExtremum(arrayFunc,isMin){return function(collection,iteratee,thisArg){if(thisArg&&isIterateeCall(collection,iteratee,thisArg)){iteratee=null}var func=getCallback(),noIteratee=iteratee==null;if(!(func===baseCallback&&noIteratee)){noIteratee=false;iteratee=func(iteratee,thisArg,3)}if(noIteratee){var isArr=isArray(collection);if(!isArr&&isString(collection)){iteratee=charAtCallback}else{return arrayFunc(isArr?collection:toIterable(collection))}}return extremumBy(collection,iteratee,isMin)}}function createHybridWrapper(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurry=bitmask&CURRY_FLAG,isCurryBound=bitmask&CURRY_BOUND_FLAG,isCurryRight=bitmask&CURRY_RIGHT_FLAG;var Ctor=!isBindKey&&createCtorWrapper(func),key=func;function wrapper(){var length=arguments.length,index=length,args=Array(length);while(index--){args[index]=arguments[index]}if(partials){args=composeArgs(args,partials,holders)}if(partialsRight){args=composeArgsRight(args,partialsRight,holdersRight)}if(isCurry||isCurryRight){var placeholder=wrapper.placeholder,argsHolders=replaceHolders(args,placeholder);length-=argsHolders.length;if(length<arity){var newArgPos=argPos?arrayCopy(argPos):null,newArity=nativeMax(arity-length,0),newsHolders=isCurry?argsHolders:null,newHoldersRight=isCurry?null:argsHolders,newPartials=isCurry?args:null,newPartialsRight=isCurry?null:args;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG;bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG);if(!isCurryBound){bitmask&=~(BIND_FLAG|BIND_KEY_FLAG)}var result=createHybridWrapper(func,bitmask,thisArg,newPartials,newsHolders,newPartialsRight,newHoldersRight,newArgPos,ary,newArity);result.placeholder=placeholder;return result}}var thisBinding=isBind?thisArg:this;if(isBindKey){func=thisBinding[key]}if(argPos){args=reorder(args,argPos)}if(isAry&&ary<args.length){args.length=ary}return(this instanceof wrapper?Ctor||createCtorWrapper(func):func).apply(thisBinding,args)}return wrapper}function createPad(string,length,chars){var strLength=string.length;length=+length;if(strLength>=length||!nativeIsFinite(length)){return""}var padLength=length-strLength;chars=chars==null?" ":baseToString(chars);return repeat(chars,ceil(padLength/chars.length)).slice(0,padLength)}function createPartialWrapper(func,bitmask,thisArg,partials){var isBind=bitmask&BIND_FLAG,Ctor=createCtorWrapper(func);function wrapper(){var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(argsLength+leftLength);while(++leftIndex<leftLength){args[leftIndex]=partials[leftIndex]}while(argsLength--){args[leftIndex++]=arguments[++argsIndex]}return(this instanceof wrapper?Ctor:func).apply(isBind?thisArg:this,args)}return wrapper}function createWrapper(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}var length=partials?partials.length:0;if(!length){bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG);partials=holders=null}length-=holders?holders.length:0;if(bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=null}var data=!isBindKey&&getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&data!==true){mergeData(newData,data);bitmask=newData[1];arity=newData[9]}newData[9]=arity==null?isBindKey?0:func.length:nativeMax(arity-length,0)||0;if(bitmask==BIND_FLAG){var result=createBindWrapper(newData[0],newData[2])}else if((bitmask==PARTIAL_FLAG||bitmask==(BIND_FLAG|PARTIAL_FLAG))&&!newData[4].length){result=createPartialWrapper.apply(null,newData)}else{result=createHybridWrapper.apply(null,newData)}var setter=data?baseSetData:setData;return setter(result,newData)}function equalArrays(array,other,equalFunc,customizer,isWhere,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=true;if(arrLength!=othLength&&!(isWhere&&othLength>arrLength)){return false}while(result&&++index<arrLength){var arrValue=array[index],othValue=other[index];result=undefined;if(customizer){result=isWhere?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)}if(typeof result=="undefined"){if(isWhere){var othIndex=othLength;while(othIndex--){othValue=other[othIndex];result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB);if(result){break}}}else{result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB)}}}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:object==0?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==baseToString(other)}return false}function equalObjects(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isWhere){return false}var hasCtor,index=-1;while(++index<objLength){var key=objProps[index],result=hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined;if(customizer){result=isWhere?customizer(othValue,objValue,key):customizer(objValue,othValue,key)}if(typeof result=="undefined"){result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isWhere,stackA,stackB)}}if(!result){return false}hasCtor||(hasCtor=key=="constructor")}if(!hasCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&("constructor"in object&&"constructor"in other)&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)){return false}}return true}function extremumBy(collection,iteratee,isMin){var exValue=isMin?POSITIVE_INFINITY:NEGATIVE_INFINITY,computed=exValue,result=computed;baseEach(collection,function(value,index,collection){var current=iteratee(value,index,collection);if((isMin?current<computed:current>computed)||current===exValue&&current===result){computed=current;result=value}});return result}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;result=result===callback?baseCallback:result;return argCount?result(func,thisArg,argCount):result}var getData=!metaMap?noop:function(func){return metaMap.get(func)};function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;result=result===indexOf?baseIndexOf:result;return collection?result(collection,target,fromIndex):result}function getView(start,end,transforms){var index=-1,length=transforms?transforms.length:0;while(++index<length){var data=transforms[index],size=data.size;switch(data.type){case"drop":start+=size;break;case"dropRight":end-=size;break;case"take":end=nativeMin(end,start+size);break;case"takeRight":start=nativeMax(start,end-size);break}}return{start:start,end:end}}function initCloneArray(array){var length=array.length,result=new array.constructor(length);if(length&&typeof array[0]=="string"&&hasOwnProperty.call(array,"index")){result.index=array.index;result.input=array.input}return result}function initCloneObject(object){var Ctor=object.constructor;if(!(typeof Ctor=="function"&&Ctor instanceof Ctor)){Ctor=Object}return new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isBindable(func){var support=lodash.support,result=!(support.funcNames?func.name:support.funcDecomp);if(!result){var source=fnToString.call(func);if(!support.funcNames){result=!reFuncName.test(source)}if(!result){result=reThis.test(source)||isNative(func);baseSetData(func,result)}}return result}function isIndex(value,length){value=+value;length=length==null?MAX_SAFE_INTEGER:length;return value>-1&&value%1==0&&value<length}function isIterateeCall(value,index,object){if(!isObject(object)){return false}var type=typeof index;if(type=="number"){var length=object.length,prereq=isLength(length)&&isIndex(index,length)}else{prereq=type=="string"&&index in value}return prereq&&object[index]===value}function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isStrictComparable(value){return value===value&&(value===0?1/value>0:!isObject(value))}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask;var arityFlags=ARY_FLAG|REARG_FLAG,bindFlags=BIND_FLAG|BIND_KEY_FLAG,comboFlags=arityFlags|bindFlags|CURRY_BOUND_FLAG|CURRY_RIGHT_FLAG;var isAry=bitmask&ARY_FLAG&&!(srcBitmask&ARY_FLAG),isRearg=bitmask&REARG_FLAG&&!(srcBitmask&REARG_FLAG),argPos=(isRearg?data:source)[7],ary=(isAry?data:source)[8];var isCommon=!(bitmask>=REARG_FLAG&&srcBitmask>bindFlags)&&!(bitmask>bindFlags&&srcBitmask>=REARG_FLAG);var isCombo=newBitmask>=arityFlags&&newBitmask<=comboFlags&&(bitmask<REARG_FLAG||(isRearg||isAry)&&argPos.length<=ary);if(!(isCommon||isCombo)){return data}if(srcBitmask&BIND_FLAG){data[2]=source[2];newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG}var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):arrayCopy(value);data[4]=partials?replaceHolders(data[3],PLACEHOLDER):arrayCopy(source[4])}value=source[5];if(value){partials=data[5];data[5]=partials?composeArgsRight(partials,value,source[6]):arrayCopy(value);data[6]=partials?replaceHolders(data[5],PLACEHOLDER):arrayCopy(source[6])}value=source[7];if(value){data[7]=arrayCopy(value)}if(srcBitmask&ARY_FLAG){data[8]=data[8]==null?source[8]:nativeMin(data[8],source[8])}if(data[9]==null){data[9]=source[9]}data[0]=source[0];data[1]=newBitmask;return data}function pickByArray(object,props){object=toObject(object);var index=-1,length=props.length,result={};while(++index<length){var key=props[index];if(key in object){result[key]=object[key]}}return result}function pickByCallback(object,predicate){var result={};baseForIn(object,function(value,key,object){if(predicate(value,key,object)){result[key]=value}});return result}function reorder(array,indexes){var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=arrayCopy(array);while(length--){var index=indexes[length];array[length]=isIndex(index,arrLength)?oldArray[index]:undefined}return array}var setData=function(){var count=0,lastCalled=0;return function(key,value){var stamp=now(),remaining=HOT_SPAN-(stamp-lastCalled);lastCalled=stamp;if(remaining>0){if(++count>=HOT_COUNT){return key}}else{count=0}return baseSetData(key,value)}}();function shimIsPlainObject(value){var Ctor,support=lodash.support;if(!(isObjectLike(value)&&objToString.call(value)==objectTag)||!hasOwnProperty.call(value,"constructor")&&(Ctor=value.constructor,typeof Ctor=="function"&&!(Ctor instanceof Ctor))){return false}var result;baseForIn(value,function(subValue,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}function shimKeys(object){var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support;var allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object));var index=-1,result=[];while(++index<propsLength){var key=props[index];if(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key)){result.push(key)}}return result}function toIterable(value){if(value==null){return[]}if(!isLength(value.length)){return values(value)}return isObject(value)?value:Object(value)}function toObject(value){return isObject(value)?value:Object(value)}function chunk(array,size,guard){if(guard?isIterateeCall(array,size,guard):size==null){size=1}else{size=nativeMax(+size||1,1)}var index=0,length=array?array.length:0,resIndex=-1,result=Array(ceil(length/size));while(index<length){result[++resIndex]=baseSlice(array,index,index+=size)}return result}function compact(array){var index=-1,length=array?array.length:0,resIndex=-1,result=[];while(++index<length){var value=array[index];if(value){result[++resIndex]=value}}return result}function difference(){var index=-1,length=arguments.length;while(++index<length){var value=arguments[index];if(isArray(value)||isArguments(value)){break}}return baseDifference(value,baseFlatten(arguments,false,true,++index))}function drop(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}return baseSlice(array,n<0?0:n)}function dropRight(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}n=length-(+n||0);return baseSlice(array,0,n<0?0:n)}function dropRightWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}predicate=getCallback(predicate,thisArg,3);while(length--&&predicate(array[length],length,array)){}return baseSlice(array,0,length+1)}function dropWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}var index=-1;predicate=getCallback(predicate,thisArg,3);while(++index<length&&predicate(array[index],index,array)){}return baseSlice(array,index)}function findIndex(array,predicate,thisArg){var index=-1,length=array?array.length:0;predicate=getCallback(predicate,thisArg,3);while(++index<length){if(predicate(array[index],index,array)){return index}}return-1}function findLastIndex(array,predicate,thisArg){var length=array?array.length:0;predicate=getCallback(predicate,thisArg,3);while(length--){if(predicate(array[length],length,array)){return length}}return-1}function first(array){return array?array[0]:undefined}function flatten(array,isDeep,guard){var length=array?array.length:0;if(guard&&isIterateeCall(array,isDeep,guard)){isDeep=false}return length?baseFlatten(array,isDeep):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,true):[]}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1}if(typeof fromIndex=="number"){fromIndex=fromIndex<0?nativeMax(length+fromIndex,0):fromIndex||0}else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex)}function initial(array){return dropRight(array,1)}function intersection(){var args=[],argsIndex=-1,argsLength=arguments.length,caches=[],indexOf=getIndexOf(),isCommon=indexOf==baseIndexOf;while(++argsIndex<argsLength){var value=arguments[argsIndex];if(isArray(value)||isArguments(value)){args.push(value);caches.push(isCommon&&value.length>=120&&createCache(argsIndex&&value))}}argsLength=args.length;var array=args[0],index=-1,length=array?array.length:0,result=[],seen=caches[0];outer:while(++index<length){value=array[index];if((seen?cacheIndexOf(seen,value):indexOf(result,value))<0){argsIndex=argsLength;while(--argsIndex){var cache=caches[argsIndex];if((cache?cacheIndexOf(cache,value):indexOf(args[argsIndex],value))<0){continue outer}}if(seen){seen.push(value)}result.push(value)}}return result}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1}var index=length;if(typeof fromIndex=="number"){index=(fromIndex<0?nativeMax(length+fromIndex,0):nativeMin(fromIndex||0,length-1))+1}else if(fromIndex){index=binaryIndex(array,value,true)-1;var other=array[index];return(value===value?value===other:other!==other)?index:-1}if(value!==value){return indexOfNaN(array,index,true)}while(index--){if(array[index]===value){return index}}return-1}function pull(){var array=arguments[0];if(!(array&&array.length)){return array}var index=0,indexOf=getIndexOf(),length=arguments.length;while(++index<length){var fromIndex=0,value=arguments[index];while((fromIndex=indexOf(array,value,fromIndex))>-1){splice.call(array,fromIndex,1)}}return array}function pullAt(array){return basePullAt(array||[],baseFlatten(arguments,false,false,1))}function remove(array,predicate,thisArg){var index=-1,length=array?array.length:0,result=[];predicate=getCallback(predicate,thisArg,3);while(++index<length){var value=array[index];if(predicate(value,index,array)){result.push(value);splice.call(array,index--,1);length--}}return result}function rest(array){return drop(array,1)}function slice(array,start,end){var length=array?array.length:0;if(!length){return[]}if(end&&typeof end!="number"&&isIterateeCall(array,start,end)){start=0;end=length}return baseSlice(array,start,end)}function sortedIndex(array,value,iteratee,thisArg){var func=getCallback(iteratee);return func===baseCallback&&iteratee==null?binaryIndex(array,value):binaryIndexBy(array,value,func(iteratee,thisArg,1))}function sortedLastIndex(array,value,iteratee,thisArg){var func=getCallback(iteratee);return func===baseCallback&&iteratee==null?binaryIndex(array,value,true):binaryIndexBy(array,value,func(iteratee,thisArg,1),true)}function take(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}return baseSlice(array,0,n<0?0:n)}function takeRight(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}n=length-(+n||0);return baseSlice(array,n<0?0:n)}function takeRightWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}predicate=getCallback(predicate,thisArg,3);while(length--&&predicate(array[length],length,array)){}return baseSlice(array,length+1)}function takeWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}var index=-1;predicate=getCallback(predicate,thisArg,3);while(++index<length&&predicate(array[index],index,array)){}return baseSlice(array,0,index)}function union(){return baseUniq(baseFlatten(arguments,false,true))}function uniq(array,isSorted,iteratee,thisArg){var length=array?array.length:0;if(!length){return[]}if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=iteratee;iteratee=isIterateeCall(array,isSorted,thisArg)?null:isSorted;isSorted=false}var func=getCallback();if(!(func===baseCallback&&iteratee==null)){iteratee=func(iteratee,thisArg,3)}return isSorted&&getIndexOf()==baseIndexOf?sortedUniq(array,iteratee):baseUniq(array,iteratee)}function unzip(array){var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);while(++index<length){result[index]=arrayMap(array,baseProperty(index))}return result}function without(array){return baseDifference(array,baseSlice(arguments,1))}function xor(){var index=-1,length=arguments.length;while(++index<length){var array=arguments[index];if(isArray(array)||isArguments(array)){var result=result?baseDifference(result,array).concat(baseDifference(array,result)):array}}return result?baseUniq(result):[]}function zip(){var length=arguments.length,array=Array(length);while(length--){array[length]=arguments[length]}return unzip(array)}function zipObject(props,values){var index=-1,length=props?props.length:0,result={};if(length&&!values&&!isArray(props[0])){values=[]}while(++index<length){var key=props[index];if(values){result[key]=values[index]}else if(key){result[key[0]]=key[1]}}return result}function chain(value){var result=lodash(value);result.__chain__=true;return result}function tap(value,interceptor,thisArg){interceptor.call(thisArg,value);return value}function thru(value,interceptor,thisArg){return interceptor.call(thisArg,value)}function wrapperChain(){return chain(this)}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){return new LodashWrapper(value.reverse())}return this.thru(function(value){return value.reverse()})}function wrapperToString(){return this.value()+""}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function at(collection){var length=collection?collection.length:0;if(isLength(length)){collection=toIterable(collection)}return baseAt(collection,baseFlatten(arguments,false,false,1))}function includes(collection,target,fromIndex){var length=collection?collection.length:0;if(!isLength(length)){collection=values(collection);length=collection.length}if(!length){return false}if(typeof fromIndex=="number"){fromIndex=fromIndex<0?nativeMax(length+fromIndex,0):fromIndex||0}else{fromIndex=0}return typeof collection=="string"||!isArray(collection)&&isString(collection)?fromIndex<length&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:result[key]=1});function every(collection,predicate,thisArg){var func=isArray(collection)?arrayEvery:baseEvery;if(typeof predicate!="function"||typeof thisArg!="undefined"){predicate=getCallback(predicate,thisArg,3)}return func(collection,predicate)}function filter(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;predicate=getCallback(predicate,thisArg,3);return func(collection,predicate)}function find(collection,predicate,thisArg){if(isArray(collection)){var index=findIndex(collection,predicate,thisArg);return index>-1?collection[index]:undefined}predicate=getCallback(predicate,thisArg,3);return baseFind(collection,predicate,baseEach)}function findLast(collection,predicate,thisArg){predicate=getCallback(predicate,thisArg,3);return baseFind(collection,predicate,baseEachRight)}function findWhere(collection,source){return find(collection,matches(source))}function forEach(collection,iteratee,thisArg){return typeof iteratee=="function"&&typeof thisArg=="undefined"&&isArray(collection)?arrayEach(collection,iteratee):baseEach(collection,bindCallback(iteratee,thisArg,3))}function forEachRight(collection,iteratee,thisArg){return typeof iteratee=="function"&&typeof thisArg=="undefined"&&isArray(collection)?arrayEachRight(collection,iteratee):baseEachRight(collection,bindCallback(iteratee,thisArg,3))}var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value)}else{result[key]=[value]}});var indexBy=createAggregator(function(result,value,key){result[key]=value});function invoke(collection,methodName){return baseInvoke(collection,methodName,baseSlice(arguments,2))}function map(collection,iteratee,thisArg){var func=isArray(collection)?arrayMap:baseMap;iteratee=getCallback(iteratee,thisArg,3);return func(collection,iteratee)}var max=createExtremum(arrayMax);var min=createExtremum(arrayMin,true);var partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]});function pluck(collection,key){return map(collection,property(key))}function reduce(collection,iteratee,accumulator,thisArg){var func=isArray(collection)?arrayReduce:baseReduce;return func(collection,getCallback(iteratee,thisArg,4),accumulator,arguments.length<3,baseEach)}function reduceRight(collection,iteratee,accumulator,thisArg){var func=isArray(collection)?arrayReduceRight:baseReduce;return func(collection,getCallback(iteratee,thisArg,4),accumulator,arguments.length<3,baseEachRight)}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;predicate=getCallback(predicate,thisArg,3);return func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function sample(collection,n,guard){if(guard?isIterateeCall(collection,n,guard):n==null){collection=toIterable(collection);var length=collection.length;return length>0?collection[baseRandom(0,length-1)]:undefined}var result=shuffle(collection);result.length=nativeMin(n<0?0:+n||0,result.length);return result}function shuffle(collection){collection=toIterable(collection);var index=-1,length=collection.length,result=Array(length);while(++index<length){var rand=baseRandom(0,index);if(index!=rand){result[index]=result[rand]}result[rand]=collection[index]}return result}function size(collection){var length=collection?collection.length:0;return isLength(length)?length:keys(collection).length}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;if(typeof predicate!="function"||typeof thisArg!="undefined"){predicate=getCallback(predicate,thisArg,3)}return func(collection,predicate)}function sortBy(collection,iteratee,thisArg){var index=-1,length=collection?collection.length:0,result=isLength(length)?Array(length):[];if(thisArg&&isIterateeCall(collection,iteratee,thisArg)){iteratee=null}iteratee=getCallback(iteratee,thisArg,3);baseEach(collection,function(value,key,collection){result[++index]={criteria:iteratee(value,key,collection),index:index,value:value} });return baseSortBy(result,compareAscending)}function sortByAll(collection){var args=arguments;if(args.length>3&&isIterateeCall(args[1],args[2],args[3])){args=[collection,args[1]]}var index=-1,length=collection?collection.length:0,props=baseFlatten(args,false,false,1),result=isLength(length)?Array(length):[];baseEach(collection,function(value,key,collection){var length=props.length,criteria=Array(length);while(length--){criteria[length]=value==null?undefined:value[props[length]]}result[++index]={criteria:criteria,index:index,value:value}});return baseSortBy(result,compareMultipleAscending)}function where(collection,source){return filter(collection,matches(source))}var now=nativeNow||function(){return(new Date).getTime()};function after(n,func){if(!isFunction(func)){if(isFunction(n)){var temp=n;n=func;func=temp}else{throw new TypeError(FUNC_ERROR_TEXT)}}n=nativeIsFinite(n=+n)?n:0;return function(){if(--n<1){return func.apply(this,arguments)}}}function ary(func,n,guard){if(guard&&isIterateeCall(func,n,guard)){n=null}n=func&&n==null?func.length:nativeMax(+n||0,0);return createWrapper(func,ARY_FLAG,null,null,null,null,n)}function before(n,func){var result;if(!isFunction(func)){if(isFunction(n)){var temp=n;n=func;func=temp}else{throw new TypeError(FUNC_ERROR_TEXT)}}return function(){if(--n>0){result=func.apply(this,arguments)}else{func=null}return result}}function bind(func,thisArg){var bitmask=BIND_FLAG;if(arguments.length>2){var partials=baseSlice(arguments,2),holders=replaceHolders(partials,bind.placeholder);bitmask|=PARTIAL_FLAG}return createWrapper(func,bitmask,thisArg,partials,holders)}function bindAll(object){return baseBindAll(object,arguments.length>1?baseFlatten(arguments,false,false,1):functions(object))}function bindKey(object,key){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(arguments.length>2){var partials=baseSlice(arguments,2),holders=replaceHolders(partials,bindKey.placeholder);bitmask|=PARTIAL_FLAG}return createWrapper(key,bitmask,object,partials,holders)}function curry(func,arity,guard){if(guard&&isIterateeCall(func,arity,guard)){arity=null}var result=createWrapper(func,CURRY_FLAG,null,null,null,null,null,arity);result.placeholder=curry.placeholder;return result}function curryRight(func,arity,guard){if(guard&&isIterateeCall(func,arity,guard)){arity=null}var result=createWrapper(func,CURRY_RIGHT_FLAG,null,null,null,null,null,arity);result.placeholder=curryRight.placeholder;return result}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,maxWait=false,trailing=true;if(!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}wait=wait<0?0:wait;if(options===true){var leading=true;trailing=false}else if(isObject(options)){leading=options.leading;maxWait="maxWait"in options&&nativeMax(+options.maxWait||0,wait);trailing="trailing"in options?options.trailing:trailing}function cancel(){if(timeoutId){clearTimeout(timeoutId)}if(maxTimeoutId){clearTimeout(maxTimeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined}function delayed(){var remaining=wait-(now()-stamp);if(remaining<=0||remaining>wait){if(maxTimeoutId){clearTimeout(maxTimeoutId)}var isCalled=trailingCall;maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}else{timeoutId=setTimeout(delayed,remaining)}}function maxDelayed(){if(timeoutId){clearTimeout(timeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined;if(trailing||maxWait!==wait){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}function debounced(){args=arguments;stamp=now();thisArg=this;trailingCall=trailing&&(timeoutId||!leading);if(maxWait===false){var leadingCall=leading&&!timeoutId}else{if(!maxTimeoutId&&!leading){lastCalled=stamp}var remaining=maxWait-(stamp-lastCalled),isCalled=remaining<=0||remaining>maxWait;if(isCalled){if(maxTimeoutId){maxTimeoutId=clearTimeout(maxTimeoutId)}lastCalled=stamp;result=func.apply(thisArg,args)}else if(!maxTimeoutId){maxTimeoutId=setTimeout(maxDelayed,remaining)}}if(isCalled&&timeoutId){timeoutId=clearTimeout(timeoutId)}else if(!timeoutId&&wait!==maxWait){timeoutId=setTimeout(delayed,wait)}if(leadingCall){isCalled=true;result=func.apply(thisArg,args)}if(isCalled&&!timeoutId&&!maxTimeoutId){args=thisArg=null}return result}debounced.cancel=cancel;return debounced}function defer(func){return baseDelay(func,1,arguments,1)}function delay(func,wait){return baseDelay(func,wait,arguments,2)}function flow(){var funcs=arguments,length=funcs.length;if(!length){return function(){}}if(!arrayEvery(funcs,isFunction)){throw new TypeError(FUNC_ERROR_TEXT)}return function(){var index=0,result=funcs[index].apply(this,arguments);while(++index<length){result=funcs[index].call(this,result)}return result}}function flowRight(){var funcs=arguments,fromIndex=funcs.length-1;if(fromIndex<0){return function(){}}if(!arrayEvery(funcs,isFunction)){throw new TypeError(FUNC_ERROR_TEXT)}return function(){var index=fromIndex,result=funcs[index].apply(this,arguments);while(index--){result=funcs[index].call(this,result)}return result}}function memoize(func,resolver){if(!isFunction(func)||resolver&&!isFunction(resolver)){throw new TypeError(FUNC_ERROR_TEXT)}var memoized=function(){var cache=memoized.cache,key=resolver?resolver.apply(this,arguments):arguments[0];if(cache.has(key)){return cache.get(key)}var result=func.apply(this,arguments);cache.set(key,result);return result};memoized.cache=new memoize.Cache;return memoized}function negate(predicate){if(!isFunction(predicate)){throw new TypeError(FUNC_ERROR_TEXT)}return function(){return!predicate.apply(this,arguments)}}function once(func){return before(func,2)}function partial(func){var partials=baseSlice(arguments,1),holders=replaceHolders(partials,partial.placeholder);return createWrapper(func,PARTIAL_FLAG,null,partials,holders)}function partialRight(func){var partials=baseSlice(arguments,1),holders=replaceHolders(partials,partialRight.placeholder);return createWrapper(func,PARTIAL_RIGHT_FLAG,null,partials,holders)}function rearg(func){var indexes=baseFlatten(arguments,false,false,1);return createWrapper(func,REARG_FLAG,null,null,null,indexes)}function throttle(func,wait,options){var leading=true,trailing=true;if(!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}if(options===false){leading=false}else if(isObject(options)){leading="leading"in options?!!options.leading:leading;trailing="trailing"in options?!!options.trailing:trailing}debounceOptions.leading=leading;debounceOptions.maxWait=+wait;debounceOptions.trailing=trailing;return debounce(func,wait,debounceOptions)}function wrap(value,wrapper){wrapper=wrapper==null?identity:wrapper;return createWrapper(wrapper,PARTIAL_FLAG,null,[value],[])}function clone(value,isDeep,customizer,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=customizer;customizer=isIterateeCall(value,isDeep,thisArg)?null:isDeep;isDeep=false}customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,isDeep,customizer)}function cloneDeep(value,customizer,thisArg){customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,true,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag||false}var isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag||false};function isBoolean(value){return value===true||value===false||isObjectLike(value)&&objToString.call(value)==boolTag||false}function isDate(value){return isObjectLike(value)&&objToString.call(value)==dateTag||false}function isElement(value){return value&&value.nodeType===1&&isObjectLike(value)&&objToString.call(value).indexOf("Element")>-1||false}if(!support.dom){isElement=function(value){return value&&value.nodeType===1&&isObjectLike(value)&&!isPlainObject(value)||false}}function isEmpty(value){if(value==null){return true}var length=value.length;if(isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))){return!length}return!keys(value).length}function isEqual(value,other,customizer,thisArg){customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,3);if(!customizer&&isStrictComparable(value)&&isStrictComparable(other)){return value===other}var result=customizer?customizer(value,other):undefined;return typeof result=="undefined"?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)&&typeof value.message=="string"&&objToString.call(value)==errorTag||false}var isFinite=nativeNumIsFinite||function(value){return typeof value=="number"&&nativeIsFinite(value)};function isFunction(value){return typeof value=="function"||false}if(isFunction(/x/)||Uint8Array&&!isFunction(Uint8Array)){isFunction=function(value){return objToString.call(value)==funcTag}}function isObject(value){var type=typeof value;return type=="function"||value&&type=="object"||false}function isMatch(object,source,customizer,thisArg){var props=keys(source),length=props.length;customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,3);if(!customizer&&length==1){var key=props[0],value=source[key];if(isStrictComparable(value)){return object!=null&&value===object[key]&&hasOwnProperty.call(object,key)}}var values=Array(length),strictCompareFlags=Array(length);while(length--){value=values[length]=source[props[length]];strictCompareFlags[length]=isStrictComparable(value)}return baseIsMatch(object,props,values,strictCompareFlags,customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(value==null){return false}if(objToString.call(value)==funcTag){return reNative.test(fnToString.call(value))}return isObjectLike(value)&&reHostCtor.test(value)||false}function isNull(value){return value===null}function isNumber(value){return typeof value=="number"||isObjectLike(value)&&objToString.call(value)==numberTag||false}var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&objToString.call(value)==objectTag)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};function isRegExp(value){return isObjectLike(value)&&objToString.call(value)==regexpTag||false}function isString(value){return typeof value=="string"||isObjectLike(value)&&objToString.call(value)==stringTag||false}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&typedArrayTags[objToString.call(value)]||false}function isUndefined(value){return typeof value=="undefined"}function toArray(value){var length=value?value.length:0;if(!isLength(length)){return values(value)}if(!length){return[]}return arrayCopy(value)}function toPlainObject(value){return baseCopy(value,keysIn(value))}var assign=createAssigner(baseAssign);function create(prototype,properties,guard){var result=baseCreate(prototype);if(guard&&isIterateeCall(prototype,properties,guard)){properties=null}return properties?baseCopy(properties,result,keys(properties)):result}function defaults(object){if(object==null){return object}var args=arrayCopy(arguments);args.push(assignDefaults);return assign.apply(undefined,args)}function findKey(object,predicate,thisArg){predicate=getCallback(predicate,thisArg,3);return baseFind(object,predicate,baseForOwn,true)}function findLastKey(object,predicate,thisArg){predicate=getCallback(predicate,thisArg,3);return baseFind(object,predicate,baseForOwnRight,true)}function forIn(object,iteratee,thisArg){if(typeof iteratee!="function"||typeof thisArg!="undefined"){iteratee=bindCallback(iteratee,thisArg,3)}return baseFor(object,iteratee,keysIn)}function forInRight(object,iteratee,thisArg){iteratee=bindCallback(iteratee,thisArg,3);return baseForRight(object,iteratee,keysIn)}function forOwn(object,iteratee,thisArg){if(typeof iteratee!="function"||typeof thisArg!="undefined"){iteratee=bindCallback(iteratee,thisArg,3)}return baseForOwn(object,iteratee)}function forOwnRight(object,iteratee,thisArg){iteratee=bindCallback(iteratee,thisArg,3);return baseForRight(object,iteratee,keys)}function functions(object){return baseFunctions(object,keysIn(object))}function has(object,key){return object?hasOwnProperty.call(object,key):false}function invert(object,multiValue,guard){if(guard&&isIterateeCall(object,multiValue,guard)){multiValue=null}var index=-1,props=keys(object),length=props.length,result={};while(++index<length){var key=props[index],value=object[key];if(multiValue){if(hasOwnProperty.call(result,value)){result[value].push(key)}else{result[value]=[key]}}else{result[value]=key}}return result}var keys=!nativeKeys?shimKeys:function(object){if(object){var Ctor=object.constructor,length=object.length}if(typeof Ctor=="function"&&Ctor.prototype===object||typeof object!="function"&&(length&&isLength(length))){return shimKeys(object)}return isObject(object)?nativeKeys(object):[]};function keysIn(object){if(object==null){return[]}if(!isObject(object)){object=Object(object)}var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;var Ctor=object.constructor,index=-1,isProto=typeof Ctor=="function"&&Ctor.prototype==object,result=Array(length),skipIndexes=length>0;while(++index<length){result[index]=index+""}for(var key in object){if(!(skipIndexes&&isIndex(key,length))&&!(key=="constructor"&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key)}}return result}function mapValues(object,iteratee,thisArg){var result={};iteratee=getCallback(iteratee,thisArg,3);baseForOwn(object,function(value,key,object){result[key]=iteratee(value,key,object)});return result}var merge=createAssigner(baseMerge);function omit(object,predicate,thisArg){if(object==null){return{}}if(typeof predicate!="function"){var props=arrayMap(baseFlatten(arguments,false,false,1),String);return pickByArray(object,baseDifference(keysIn(object),props))}predicate=bindCallback(predicate,thisArg,3);return pickByCallback(object,function(value,key,object){return!predicate(value,key,object)})}function pairs(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){var key=props[index];result[index]=[key,object[key]]}return result}function pick(object,predicate,thisArg){if(object==null){return{}}return typeof predicate=="function"?pickByCallback(object,bindCallback(predicate,thisArg,3)):pickByArray(object,baseFlatten(arguments,false,false,1))}function result(object,key,defaultValue){var value=object==null?undefined:object[key];if(typeof value=="undefined"){value=defaultValue}return isFunction(value)?value.call(object):value}function transform(object,iteratee,accumulator,thisArg){var isArr=isArray(object)||isTypedArray(object);iteratee=getCallback(iteratee,thisArg,4);if(accumulator==null){if(isArr||isObject(object)){var Ctor=object.constructor;if(isArr){accumulator=isArray(object)?new Ctor:[]}else{accumulator=baseCreate(typeof Ctor=="function"&&Ctor.prototype)}}else{accumulator={}}}(isArr?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object)});return accumulator}function values(object){return baseValues(object,keys(object))}function valuesIn(object){return baseValues(object,keysIn(object))}function random(min,max,floating){if(floating&&isIterateeCall(min,max,floating)){max=floating=null}var noMin=min==null,noMax=max==null;if(floating==null){if(noMax&&typeof min=="boolean"){floating=min;min=1}else if(typeof max=="boolean"){floating=max;noMax=true}}if(noMin&&noMax){max=1;noMax=false}min=+min||0;if(noMax){max=min;min=0}else{max=+max||0}if(floating||min%1||max%1){var rand=nativeRandom();return nativeMin(min+rand*(max-min+parseFloat("1e-"+((rand+"").length-1))),max)}return baseRandom(min,max)}var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return index?result+word.charAt(0).toUpperCase()+word.slice(1):word});function capitalize(string){string=baseToString(string);return string&&string.charAt(0).toUpperCase()+string.slice(1)}function deburr(string){string=baseToString(string);return string&&string.replace(reLatin1,deburrLetter)}function endsWith(string,target,position){string=baseToString(string);target=target+"";var length=string.length;position=(typeof position=="undefined"?length:nativeMin(position<0?0:+position||0,length))-target.length;return position>=0&&string.indexOf(target,position)==position}function escape(string){string=baseToString(string);return string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){string=baseToString(string);return string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,"\\$&"):string}var kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()});function pad(string,length,chars){string=baseToString(string);length=+length;var strLength=string.length;if(strLength>=length||!nativeIsFinite(length)){return string}var mid=(length-strLength)/2,leftLength=floor(mid),rightLength=ceil(mid);chars=createPad("",rightLength,chars);return chars.slice(0,leftLength)+string+chars}function padLeft(string,length,chars){string=baseToString(string);return string&&createPad(string,length,chars)+string}function padRight(string,length,chars){string=baseToString(string);return string&&string+createPad(string,length,chars)}function parseInt(string,radix,guard){if(guard&&isIterateeCall(string,radix,guard)){radix=0}return nativeParseInt(string,radix)}if(nativeParseInt(whitespace+"08")!=8){parseInt=function(string,radix,guard){if(guard?isIterateeCall(string,radix,guard):radix==null){radix=0}else if(radix){radix=+radix}string=trim(string);return nativeParseInt(string,radix||(reHexPrefix.test(string)?16:10))}}function repeat(string,n){var result="";string=baseToString(string);n=+n;if(n<1||!string||!nativeIsFinite(n)){return result}do{if(n%2){result+=string}n=floor(n/2);string+=string}while(n);return result}var snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()});function startsWith(string,target,position){string=baseToString(string);position=position==null?0:nativeMin(position<0?0:+position||0,string.length);return string.lastIndexOf(target,position)==position}function template(string,options,otherOptions){var settings=lodash.templateSettings;if(otherOptions&&isIterateeCall(string,options,otherOptions)){options=otherOptions=null}string=baseToString(string);options=baseAssign(baseAssign({},otherOptions||options),settings,assignOwnDefaults);var imports=baseAssign(baseAssign({},options.imports),settings.imports,assignOwnDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys);var isEscaping,isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");var sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){isEscaping=true;source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable;if(!variable){source="with (obj) {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});result.source=source;if(isError(result)){throw result}return result}function trim(string,chars,guard){var value=string;string=baseToString(string);if(!string){return string}if(guard?isIterateeCall(value,chars,guard):chars==null){return string.slice(trimmedLeftIndex(string),trimmedRightIndex(string)+1)}chars=baseToString(chars);return string.slice(charsLeftIndex(string,chars),charsRightIndex(string,chars)+1)}function trimLeft(string,chars,guard){var value=string;string=baseToString(string);if(!string){return string}if(guard?isIterateeCall(value,chars,guard):chars==null){return string.slice(trimmedLeftIndex(string))}return string.slice(charsLeftIndex(string,baseToString(chars)))}function trimRight(string,chars,guard){var value=string;string=baseToString(string);if(!string){return string}if(guard?isIterateeCall(value,chars,guard):chars==null){return string.slice(0,trimmedRightIndex(string)+1)}return string.slice(0,charsRightIndex(string,baseToString(chars))+1)}function trunc(string,options,guard){if(guard&&isIterateeCall(string,options,guard)){options=null}var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(options!=null){if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?+options.length||0:length;omission="omission"in options?baseToString(options.omission):omission}else{length=+options||0}}string=baseToString(string);if(length>=string.length){return string}var end=length-omission.length;if(end<1){return omission}var result=string.slice(0,end);if(separator==null){return result+omission}if(isRegExp(separator)){if(string.slice(end).search(separator)){var match,newEnd,substring=string.slice(0,end);if(!separator.global){separator=RegExp(separator.source,(reFlags.exec(separator)||"")+"g")}separator.lastIndex=0;while(match=separator.exec(substring)){newEnd=match.index}result=result.slice(0,newEnd==null?end:newEnd)}}else if(string.indexOf(separator,end)!=end){var index=result.lastIndexOf(separator);if(index>-1){result=result.slice(0,index)}}return result+omission}function unescape(string){string=baseToString(string);return string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){if(guard&&isIterateeCall(string,pattern,guard)){pattern=null}string=baseToString(string);return string.match(pattern||reWords)||[]}function attempt(func){try{return func()}catch(e){return isError(e)?e:Error(e)}}function callback(func,thisArg,guard){if(guard&&isIterateeCall(func,thisArg,guard)){thisArg=null}return baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function matches(source){return baseMatches(source,true)}function mixin(object,source,options){if(options==null){var isObj=isObject(source),props=isObj&&keys(source),methodNames=props&&props.length&&baseFunctions(source,props);if(!(methodNames?methodNames.length:isObj)){methodNames=false;options=source;source=object;object=this}}if(!methodNames){methodNames=baseFunctions(source,keys(source))}var chain=true,index=-1,isFunc=isFunction(object),length=methodNames.length;if(options===false){chain=false}else if(isObject(options)&&"chain"in options){chain=options.chain}while(++index<length){var methodName=methodNames[index],func=source[methodName];object[methodName]=func;if(isFunc){object.prototype[methodName]=function(func){return function(){var chainAll=this.__chain__;if(chain||chainAll){var result=object(this.__wrapped__);(result.__actions__=arrayCopy(this.__actions__)).push({func:func,args:arguments,thisArg:object});result.__chain__=chainAll;return result}var args=[this.value()];push.apply(args,arguments);return func.apply(object,args)}}(func)}}return object}function noConflict(){context._=oldDash;return this}function noop(){}function property(key){return baseProperty(key+"")}function propertyOf(object){return function(key){return object==null?undefined:object[key]}}function range(start,end,step){if(step&&isIterateeCall(start,end,step)){end=step=null}start=+start||0;step=step==null?1:+step||0;if(end==null){end=start;start=0}else{end=+end||0}var index=-1,length=nativeMax(ceil((end-start)/(step||1)),0),result=Array(length);while(++index<length){result[index]=start;start+=step}return result}function times(n,iteratee,thisArg){n=+n;if(n<1||!nativeIsFinite(n)){return[]}var index=-1,result=Array(nativeMin(n,MAX_ARRAY_LENGTH));iteratee=bindCallback(iteratee,thisArg,1);while(++index<n){if(index<MAX_ARRAY_LENGTH){result[index]=iteratee(index)}else{iteratee(index)}}return result}function uniqueId(prefix){var id=++idCounter;return baseToString(prefix)+id}LodashWrapper.prototype=lodash.prototype;MapCache.prototype["delete"]=mapDelete;MapCache.prototype.get=mapGet;MapCache.prototype.has=mapHas;MapCache.prototype.set=mapSet;SetCache.prototype.push=cachePush;memoize.Cache=MapCache;lodash.after=after;lodash.ary=ary;lodash.assign=assign;lodash.at=at;lodash.before=before;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.callback=callback;lodash.chain=chain;lodash.chunk=chunk;lodash.compact=compact;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.curry=curry;lodash.curryRight=curryRight;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.drop=drop;lodash.dropRight=dropRight;lodash.dropRightWhile=dropRightWhile;lodash.dropWhile=dropWhile;lodash.filter=filter;lodash.flatten=flatten;lodash.flattenDeep=flattenDeep;lodash.flow=flow;lodash.flowRight=flowRight;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.functions=functions;lodash.groupBy=groupBy;lodash.indexBy=indexBy;lodash.initial=initial;lodash.intersection=intersection;lodash.invert=invert;lodash.invoke=invoke;lodash.keys=keys;lodash.keysIn=keysIn;lodash.map=map;lodash.mapValues=mapValues;lodash.matches=matches;lodash.memoize=memoize;lodash.merge=merge;lodash.mixin=mixin;lodash.negate=negate;lodash.omit=omit;lodash.once=once;lodash.pairs=pairs;lodash.partial=partial;lodash.partialRight=partialRight;lodash.partition=partition;lodash.pick=pick;lodash.pluck=pluck;lodash.property=property;lodash.propertyOf=propertyOf;lodash.pull=pull;lodash.pullAt=pullAt;lodash.range=range;lodash.rearg=rearg;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.shuffle=shuffle;lodash.slice=slice;lodash.sortBy=sortBy;lodash.sortByAll=sortByAll;lodash.take=take;lodash.takeRight=takeRight;lodash.takeRightWhile=takeRightWhile;lodash.takeWhile=takeWhile;lodash.tap=tap;lodash.throttle=throttle;lodash.thru=thru;lodash.times=times;lodash.toArray=toArray;lodash.toPlainObject=toPlainObject;lodash.transform=transform;lodash.union=union;lodash.uniq=uniq;lodash.unzip=unzip;lodash.values=values;lodash.valuesIn=valuesIn;lodash.where=where;lodash.without=without;lodash.wrap=wrap;lodash.xor=xor;lodash.zip=zip;lodash.zipObject=zipObject;lodash.backflow=flowRight;lodash.collect=map;lodash.compose=flowRight;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assign;lodash.iteratee=callback;lodash.methods=functions;lodash.object=zipObject;lodash.select=filter;lodash.tail=rest;lodash.unique=uniq;mixin(lodash,lodash);lodash.attempt=attempt;lodash.camelCase=camelCase;lodash.capitalize=capitalize;lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.deburr=deburr;lodash.endsWith=endsWith;lodash.escape=escape;lodash.escapeRegExp=escapeRegExp;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.findWhere=findWhere;lodash.first=first;lodash.has=has;lodash.identity=identity;lodash.includes=includes;lodash.indexOf=indexOf;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isError=isError;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isMatch=isMatch;lodash.isNaN=isNaN;lodash.isNative=isNative;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isString=isString;lodash.isTypedArray=isTypedArray;lodash.isUndefined=isUndefined;lodash.kebabCase=kebabCase;lodash.last=last;lodash.lastIndexOf=lastIndexOf;lodash.max=max;lodash.min=min;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.pad=pad;lodash.padLeft=padLeft;lodash.padRight=padRight;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.repeat=repeat;lodash.result=result;lodash.runInContext=runInContext;lodash.size=size;lodash.snakeCase=snakeCase;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.sortedLastIndex=sortedLastIndex;lodash.startsWith=startsWith;lodash.template=template;lodash.trim=trim;lodash.trimLeft=trimLeft;lodash.trimRight=trimRight;lodash.trunc=trunc;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.words=words;lodash.all=every;lodash.any=some;lodash.contains=includes;lodash.detect=find;lodash.foldl=reduce;lodash.foldr=reduceRight;lodash.head=first;lodash.include=includes;lodash.inject=reduce;mixin(lodash,function(){var source={};baseForOwn(lodash,function(func,methodName){if(!lodash.prototype[methodName]){source[methodName]=func}});return source}(),false);lodash.sample=sample;lodash.prototype.sample=function(n){if(!this.__chain__&&n==null){return sample(this.value())}return this.thru(function(value){return sample(value,n)})};lodash.VERSION=VERSION;arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash});arrayEach(["filter","map","takeWhile"],function(methodName,index){var isFilter=index==LAZY_FILTER_FLAG;LazyWrapper.prototype[methodName]=function(iteratee,thisArg){var result=this.clone(),filtered=result.filtered,iteratees=result.iteratees||(result.iteratees=[]);result.filtered=filtered||isFilter||index==LAZY_WHILE_FLAG&&result.dir<0;iteratees.push({iteratee:getCallback(iteratee,thisArg,3),type:index});return result}});arrayEach(["drop","take"],function(methodName,index){var countName=methodName+"Count",whileName=methodName+"While";LazyWrapper.prototype[methodName]=function(n){n=n==null?1:nativeMax(+n||0,0);var result=this.clone();if(result.filtered){var value=result[countName];result[countName]=index?nativeMin(value,n):value+n}else{var views=result.views||(result.views=[]);views.push({size:n,type:methodName+(result.dir<0?"Right":"")})}return result};LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()};LazyWrapper.prototype[methodName+"RightWhile"]=function(predicate,thisArg){return this.reverse()[whileName](predicate,thisArg).reverse()}});arrayEach(["first","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}});arrayEach(["initial","rest"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this[dropName](1)}});arrayEach(["pluck","where"],function(methodName,index){var operationName=index?"filter":"map",createCallback=index?matches:property; LazyWrapper.prototype[methodName]=function(value){return this[operationName](createCallback(value))}});LazyWrapper.prototype.dropWhile=function(iteratee,thisArg){var done,lastIndex,isRight=this.dir<0;iteratee=getCallback(iteratee,thisArg,3);return this.filter(function(value,index,array){done=done&&(isRight?index<lastIndex:index>lastIndex);lastIndex=index;return done||(done=!iteratee(value,index,array))})};LazyWrapper.prototype.reject=function(iteratee,thisArg){iteratee=getCallback(iteratee,thisArg,3);return this.filter(function(value,index,array){return!iteratee(value,index,array)})};LazyWrapper.prototype.slice=function(start,end){start=start==null?0:+start||0;var result=start<0?this.takeRight(-start):this.drop(start);if(typeof end!="undefined"){end=+end||0;result=end<0?result.dropRight(-end):result.take(end-start)}return result};baseForOwn(LazyWrapper.prototype,function(func,methodName){var retUnwrapped=/^(?:first|last)$/.test(methodName);lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=arguments,chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isLazy=value instanceof LazyWrapper,onlyLazy=isLazy&&!isHybrid;if(retUnwrapped&&!chainAll){return onlyLazy?func.call(value):lodash[methodName](this.value())}var interceptor=function(value){var otherArgs=[value];push.apply(otherArgs,args);return lodash[methodName].apply(lodash,otherArgs)};if(isLazy||isArray(value)){var wrapper=onlyLazy?value:new LazyWrapper(this),result=func.apply(wrapper,args);if(!retUnwrapped&&(isHybrid||result.actions)){var actions=result.actions||(result.actions=[]);actions.push({func:thru,args:[interceptor],thisArg:lodash})}return new LodashWrapper(result,chainAll)}return this.thru(interceptor)}});arrayEach(["concat","join","pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:join|pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){return func.apply(this.value(),args)}return this[chainName](function(value){return func.apply(value,args)})}});LazyWrapper.prototype.clone=lazyClone;LazyWrapper.prototype.reverse=lazyReverse;LazyWrapper.prototype.value=lazyValue;lodash.prototype.chain=wrapperChain;lodash.prototype.reverse=wrapperReverse;lodash.prototype.toString=wrapperToString;lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue;lodash.prototype.collect=lodash.prototype.map;lodash.prototype.head=lodash.prototype.first;lodash.prototype.select=lodash.prototype.filter;lodash.prototype.tail=lodash.prototype.rest;return lodash}var _=runInContext();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root._=_;define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}else{freeExports._=_}}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],169:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],170:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var isArray=types.builtInTypes.array;var b=types.builders;var n=types.namedTypes;var leap=require("./leap");var meta=require("./meta");var util=require("./util");var runtimeKeysMethod=util.runtimeProperty("keys");var hasOwn=Object.prototype.hasOwnProperty;function Emitter(contextId){assert.ok(this instanceof Emitter);n.Identifier.assert(contextId);Object.defineProperties(this,{contextId:{value:contextId},listing:{value:[]},marked:{value:[true]},finalLoc:{value:loc()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new leap.LeapManager(this)}})}var Ep=Emitter.prototype;exports.Emitter=Emitter;function loc(){return b.literal(-1)}Ep.mark=function(loc){n.Literal.assert(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Ep.emit=function(node){if(n.Expression.check(node))node=b.expressionStatement(node);n.Statement.assert(node);this.listing.push(node)};Ep.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Ep.assign=function(lhs,rhs){return b.expressionStatement(b.assignmentExpression("=",lhs,rhs))};Ep.contextProperty=function(name,computed){return b.memberExpression(this.contextId,computed?b.literal(name):b.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Ep.isVolatileContextProperty=function(expr){if(n.MemberExpression.check(expr)){if(expr.computed){return true}if(n.Identifier.check(expr.object)&&n.Identifier.check(expr.property)&&expr.object.name===this.contextId.name&&hasOwn.call(volatileContextPropertyNames,expr.property.name)){return true}}return false};Ep.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Ep.setReturnValue=function(valuePath){n.Expression.assert(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Ep.clearPendingException=function(tryLoc,assignee){n.Literal.assert(tryLoc);var catchCall=b.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Ep.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(b.breakStatement())};Ep.jumpIf=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);this.emit(b.ifStatement(test,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};Ep.jumpIfNot=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);var negatedTest;if(n.UnaryExpression.check(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=b.unaryExpression("!",test)}this.emit(b.ifStatement(negatedTest,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};var nextTempId=0;Ep.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Ep.getContextFunction=function(id){var func=b.functionExpression(id||null,[this.contextId],b.blockStatement([this.getDispatchLoop()]),false,false);func._aliasFunction=true;return func};Ep.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(b.switchCase(b.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(b.switchCase(this.finalLoc,[]),b.switchCase(b.literal("end"),[b.returnStatement(b.callExpression(this.contextProperty("stop"),[]))]));return b.whileStatement(b.literal(1),b.switchStatement(b.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return n.BreakStatement.check(stmt)||n.ContinueStatement.check(stmt)||n.ReturnStatement.check(stmt)||n.ThrowStatement.check(stmt)}Ep.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return b.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc}return b.arrayExpression(triple)}))};Ep.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.assert(node);if(n.Statement.check(node))return self.explodeStatement(path);if(n.Expression.check(node))return self.explodeExpression(path,ignoreResult);if(n.Declaration.check(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Ep.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;n.Statement.assert(stmt);if(labelId){n.Identifier.assert(labelId)}else{labelId=null}if(n.BlockStatement.check(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}switch(stmt.type){case"ExpressionStatement":self.explodeExpression(path.get("expression"),true);break;case"LabeledStatement":var after=loc();self.leapManager.withEntry(new leap.LabeledEntry(after,stmt.label),function(){self.explodeStatement(path.get("body"),stmt.label)});self.mark(after);break;case"WhileStatement":var before=loc();var after=loc();self.mark(before);self.jumpIfNot(self.explodeExpression(path.get("test")),after);self.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(before);self.mark(after);break;case"DoWhileStatement":var first=loc();var test=loc();var after=loc();self.mark(first);self.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){self.explode(path.get("body"))});self.mark(test);self.jumpIf(self.explodeExpression(path.get("test")),first);self.mark(after);break;case"ForStatement":var head=loc();var update=loc();var after=loc();if(stmt.init){self.explode(path.get("init"),true)}self.mark(head);if(stmt.test){self.jumpIfNot(self.explodeExpression(path.get("test")),after)}else{}self.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){self.explodeStatement(path.get("body"))});self.mark(update);if(stmt.update){self.explode(path.get("update"),true)}self.jump(head);self.mark(after);break;case"ForInStatement":n.Identifier.assert(stmt.left);var head=loc();var after=loc();var keyIterNextFn=self.makeTempVar();self.emitAssign(keyIterNextFn,b.callExpression(runtimeKeysMethod,[self.explodeExpression(path.get("right"))]));self.mark(head);var keyInfoTmpVar=self.makeTempVar();self.jumpIf(b.memberExpression(b.assignmentExpression("=",keyInfoTmpVar,b.callExpression(keyIterNextFn,[])),b.identifier("done"),false),after);self.emitAssign(stmt.left,b.memberExpression(keyInfoTmpVar,b.identifier("value"),false));self.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(head);self.mark(after);break;case"BreakStatement":self.emitAbruptCompletion({type:"break",target:self.leapManager.getBreakLoc(stmt.label)});break;case"ContinueStatement":self.emitAbruptCompletion({type:"continue",target:self.leapManager.getContinueLoc(stmt.label)});break;case"SwitchStatement":var disc=self.emitAssign(self.makeTempVar(),self.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];n.SwitchCase.assert(c);if(c.test){condition=b.conditionalExpression(b.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}self.jump(self.explodeExpression(new types.NodePath(condition,path,"discriminant")));self.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var c=casePath.value;var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});self.mark(after);if(defaultLoc.value===-1){self.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}break;case"IfStatement":var elseLoc=stmt.alternate&&loc();var after=loc();self.jumpIfNot(self.explodeExpression(path.get("test")),elseLoc||after);self.explodeStatement(path.get("consequent"));if(elseLoc){self.jump(after);self.mark(elseLoc);self.explodeStatement(path.get("alternate"))}self.mark(after);break;case"ReturnStatement":self.emitAbruptCompletion({type:"return",value:self.explodeExpression(path.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var after=loc();var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(self.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);self.tryEntries.push(tryEntry);self.updateContextPrevLoc(tryEntry.firstLoc);self.leapManager.withEntry(tryEntry,function(){self.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){self.jump(finallyLoc)}else{self.jump(after)}self.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=self.makeTempVar();self.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;n.CatchClause.assert(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(util.isReference(path,catchParamName)&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)},visitFunction:function(path){if(path.scope.declares(catchParamName)){return false}this.traverse(path)}});self.leapManager.withEntry(catchEntry,function(){self.explodeStatement(bodyPath)})}if(finallyLoc){self.updateContextPrevLoc(self.mark(finallyLoc));self.leapManager.withEntry(finallyEntry,function(){self.explodeStatement(path.get("finalizer"))});self.emit(b.callExpression(self.contextProperty("finish"),[finallyEntry.firstLoc]))}});self.mark(after);break;case"ThrowStatement":self.emit(b.throwStatement(self.explodeExpression(path.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Ep.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[b.literal(record.type)];if(record.type==="break"||record.type==="continue"){n.Literal.assert(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){n.Expression.assert(record.value);abruptArgs[1]=record.value}}this.emit(b.returnStatement(b.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!hasOwn.call(record,"target")}if(type==="break"||type==="continue"){return!hasOwn.call(record,"value")&&n.Literal.check(record.target)}if(type==="return"||type==="throw"){return hasOwn.call(record,"value")&&!hasOwn.call(record,"target")}return false}Ep.getUnmarkedCurrentLoc=function(){return b.literal(this.listing.length)};Ep.updateContextPrevLoc=function(loc){if(loc){n.Literal.assert(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Ep.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){n.Expression.assert(expr)}else{return expr}var self=this;var result;function finish(expr){n.Expression.assert(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}switch(expr.type){case"MemberExpression":return finish(b.memberExpression(self.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed));case"CallExpression":var oldCalleePath=path.get("callee");var newCallee=self.explodeExpression(oldCalleePath);if(!n.MemberExpression.check(oldCalleePath.node)&&n.MemberExpression.check(newCallee)){newCallee=b.sequenceExpression([b.literal(0),newCallee])}return finish(b.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"NewExpression":return finish(b.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"ObjectExpression":return finish(b.objectExpression(path.get("properties").map(function(propPath){return b.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})));case"ArrayExpression":return finish(b.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})));case"SequenceExpression":var lastIndex=expr.expressions.length-1;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result;case"LogicalExpression":var after=loc();if(!ignoreResult){result=self.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){self.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");self.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);self.mark(after);return result;case"ConditionalExpression":var elseLoc=loc();var after=loc();var test=self.explodeExpression(path.get("test"));self.jumpIfNot(test,elseLoc);if(!ignoreResult){result=self.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);self.jump(after);self.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);self.mark(after);return result;case"UnaryExpression":return finish(b.unaryExpression(expr.operator,self.explodeExpression(path.get("argument")),!!expr.prefix));case"BinaryExpression":return finish(b.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))));case"AssignmentExpression":return finish(b.assignmentExpression(expr.operator,self.explodeExpression(path.get("left")),self.explodeExpression(path.get("right"))));case"UpdateExpression":return finish(b.updateExpression(expr.operator,self.explodeExpression(path.get("argument")),expr.prefix));case"YieldExpression":var after=loc();var arg=expr.argument&&self.explodeExpression(path.get("argument"));if(arg&&expr.delegate){var result=self.makeTempVar();self.emit(b.returnStatement(b.callExpression(self.contextProperty("delegateYield"),[arg,b.literal(result.property.name),after])));self.mark(after);return result}self.emitAssign(self.contextProperty("next"),after);self.emit(b.returnStatement(arg||null));self.mark(after);return self.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"./leap":172,"./meta":173,"./util":174,assert:121,"ast-types":119}],171:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);n.Function.assert(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){n.VariableDeclaration.assert(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(b.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return b.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return b.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(n.VariableDeclaration.check(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(n.VariableDeclaration.check(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var parentNode=path.parent.node;var assignment=b.expressionStatement(b.assignmentExpression("=",node.id,b.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(n.BlockStatement.check(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(path){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(n.Identifier.check(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!hasOwn.call(paramNames,name)){declarations.push(b.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return b.variableDeclaration("var",declarations)}},{assert:121,"ast-types":119}],172:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var inherits=require("util").inherits;var hasOwn=Object.prototype.hasOwnProperty;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);n.Literal.assert(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);exports.FunctionEntry=FunctionEntry;function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Literal.assert(continueLoc);if(label){n.Identifier.assert(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);exports.LoopEntry=LoopEntry;function SwitchEntry(breakLoc){Entry.call(this);n.Literal.assert(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);exports.SwitchEntry=SwitchEntry;function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);n.Literal.assert(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);exports.TryEntry=TryEntry;function CatchEntry(firstLoc,paramId){Entry.call(this);n.Literal.assert(firstLoc);n.Identifier.assert(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);exports.CatchEntry=CatchEntry;function FinallyEntry(firstLoc){Entry.call(this);n.Literal.assert(firstLoc);this.firstLoc=firstLoc}inherits(FinallyEntry,Entry);exports.FinallyEntry=FinallyEntry;function LabeledEntry(breakLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Identifier.assert(label);this.breakLoc=breakLoc;this.label=label}inherits(LabeledEntry,Entry);exports.LabeledEntry=LabeledEntry;function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}var LMp=LeapManager.prototype;exports.LeapManager=LeapManager;LMp.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LMp._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else if(entry instanceof LabeledEntry){}else{return loc}}}return null};LMp.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LMp.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"./emit":170,assert:121,"ast-types":119,util:146}],173:[function(require,module,exports){var assert=require("assert");var m=require("private").makeAccessor();var types=require("ast-types");var isArray=types.builtInTypes.array;var n=types.namedTypes;var hasOwn=Object.prototype.hasOwnProperty;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.assert(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.assert(node);var meta=m(node);if(hasOwn.call(meta,propertyName))return meta[propertyName];if(hasOwn.call(opaqueTypes,node.type))return meta[propertyName]=false;if(hasOwn.call(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(hasOwn.call(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:121,"ast-types":119,"private":169}],174:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.defaults=function(obj){var len=arguments.length;var extension;for(var i=1;i<len;++i){if(extension=arguments[i]){for(var key in extension){if(hasOwn.call(extension,key)&&!hasOwn.call(obj,key)){obj[key]=extension[key]}}}}return obj};exports.runtimeProperty=function(name){return b.memberExpression(b.identifier("regeneratorRuntime"),b.identifier(name),false)};exports.isReference=function(path,name){var node=path.value;if(!n.Identifier.check(node)){return false}if(name&&node.name!==name){return false}var parent=path.parent.value;switch(parent.type){case"VariableDeclarator":return path.name==="init";case"MemberExpression":return path.name==="object"||parent.computed&&path.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(path.name==="id"){return false}if(parent.params===path.parentPath&&parent.params[path.name]===node){return false}return true;case"ClassDeclaration":case"ClassExpression":return path.name!=="id";case"CatchClause":return path.name!=="param";case"Property":case"MethodDefinition":return path.name!=="key";case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return false;default:return true}}},{assert:121,"ast-types":119}],175:[function(require,module,exports){var assert=require("assert");var fs=require("fs");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var hoist=require("./hoist").hoist;var Emitter=require("./emit").Emitter;var runtimeProperty=require("./util").runtimeProperty;var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");var runtimeValuesMethod=runtimeProperty("values");var runtimeAsyncMethod=runtimeProperty("async");exports.transform=function transform(node,options){options=options||{};var path=node instanceof NodePath?node:new NodePath(node);visitor.visit(path,options);node=path.value;options.madeChanges=visitor.wasChangeReported();return node};var visitor=types.PathVisitor.fromMethodsObject({reset:function(node,options){this.options=options},visitFunction:function(path){this.traverse(path);var node=path.value;var shouldTransformAsync=node.async&&!this.options.disableAsync;if(!node.generator&&!shouldTransformAsync){return}this.reportChanged();node.generator=false;if(node.expression){node.expression=false;node.body=b.blockStatement([b.returnStatement(node.body)])}if(shouldTransformAsync){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=path.scope.parent.declareTemporary("callee$"));var innerFnId=b.identifier(node.id.name+"$");var contextId=path.scope.declareTemporary("context$");var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));var outerBody=[];if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),shouldTransformAsync?b.literal(null):outerFnId,b.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=b.callExpression(shouldTransformAsync?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(b.returnStatement(wrapCall));node.body=b.blockStatement(outerBody);if(shouldTransformAsync){node.async=false;return}if(n.FunctionDeclaration.check(node)){var pp=path.parent;while(pp&&!(n.BlockStatement.check(pp.value)||n.Program.check(pp.value))){pp=pp.parent }if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=b.variableDeclaration("var",[b.variableDeclarator(node.id,b.callExpression(runtimeMarkMethod,[node]))]);if(node.comments){varDecl.leadingComments=node.leadingComments;varDecl.trailingComments=node.trailingComments;node.leadingComments=null;node.trailingComments=null}varDecl._blockHoist=3;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;bodyPath.push(varDecl)}else{n.FunctionExpression.assert(node);return b.callExpression(runtimeMarkMethod,[node])}}});function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;n.Statement.assert(value);if(n.ExpressionStatement.check(value)&&n.Literal.check(value.expression)&&value.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(n.CallExpression.check(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){return false},visitAwaitExpression:function(path){return b.yieldExpression(path.value.argument,false)}})},{"./emit":170,"./hoist":171,"./util":174,assert:121,"ast-types":119,fs:120}],176:[function(require,module,exports){(function(__dirname){var assert=require("assert");var path=require("path");var fs=require("fs");var through=require("through");var transform=require("./lib/visit").transform;var utils=require("./lib/util");var types=require("ast-types");var genOrAsyncFunExp=/\bfunction\s*\*|\basync\b/;var blockBindingExp=/\b(let|const)\s+/;function exports(file,options){var data=[];return through(write,end);function write(buf){data.push(buf)}function end(){this.queue(compile(data.join(""),options).code);this.queue(null)}}module.exports=exports;function runtime(){require("./runtime")}exports.runtime=runtime;runtime.path=path.join(__dirname,"runtime.js");exports.transform=transform}).call(this,"/node_modules/regenerator-6to5")},{"./lib/util":174,"./lib/visit":175,"./runtime":178,assert:121,"ast-types":119,fs:120,path:129,through:177}],177:[function(require,module,exports){(function(process){var Stream=require("stream");exports=module.exports=through;through.through=through;function through(write,end,opts){write=write||function(data){this.queue(data)};end=end||function(){this.queue(null)};var ended=false,destroyed=false,buffer=[],_ended=false;var stream=new Stream;stream.readable=stream.writable=true;stream.paused=false;stream.autoDestroy=!(opts&&opts.autoDestroy===false);stream.write=function(data){write.call(this,data);return!stream.paused};function drain(){while(buffer.length&&!stream.paused){var data=buffer.shift();if(null===data)return stream.emit("end");else stream.emit("data",data)}}stream.queue=stream.push=function(data){if(_ended)return stream;if(data==null)_ended=true;buffer.push(data);drain();return stream};stream.on("end",function(){stream.readable=false;if(!stream.writable&&stream.autoDestroy)process.nextTick(function(){stream.destroy()})});function _end(){stream.writable=false;end.call(stream);if(!stream.readable&&stream.autoDestroy)stream.destroy()}stream.end=function(data){if(ended)return;ended=true;if(arguments.length)stream.write(data);_end();return stream};stream.destroy=function(){if(destroyed)return;destroyed=true;ended=true;buffer.length=0;stream.writable=stream.readable=false;stream.emit("close");return stream};stream.pause=function(){if(stream.paused)return;stream.paused=true;return stream};stream.resume=function(){if(stream.paused){stream.paused=false;stream.emit("resume")}drain();if(!stream.paused)stream.emit("drain");return stream};return stream}}).call(this,require("_process"))},{_process:130,stream:142}],178:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;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";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}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"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}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{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},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"){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")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){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"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"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,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],179:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:181}],180:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],181:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var length=data.length;var start=data[index];var end=data[length-1];if(length>=2){if(codePoint<start||codePoint>end){return false}}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var loneLowSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<HIGH_SURROGATE_MIN){if(end<HIGH_SURROGATE_MIN){bmp.push(start,end+1)}if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=LOW_SURROGATE_MIN&&start<=LOW_SURROGATE_MAX){if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneLowSurrogates.push(start,end+1)}if(end>LOW_SURROGATE_MAX){loneLowSurrogates.push(start,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>LOW_SURROGATE_MAX&&start<=65535){if(end<=65535){bmp.push(start,end+1)}else{bmp.push(start,65535+1);astral.push(65535+1,end+1)}}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,loneLowSurrogates:loneLowSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data,bmpOnly){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var loneLowSurrogates=parts.loneLowSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneHighSurrogates=!dataIsEmpty(loneHighSurrogates);var hasLoneLowSurrogates=!dataIsEmpty(loneLowSurrogates);var surrogateMappings=surrogateSet(astral);if(bmpOnly){bmp=dataAddData(bmp,loneHighSurrogates);hasLoneHighSurrogates=false;bmp=dataAddData(bmp,loneLowSurrogates);hasLoneLowSurrogates=false}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasLoneHighSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates)+"(?![\\uDC00-\\uDFFF])")}if(hasLoneLowSurrogates){result.push("(?:[^\\uD800-\\uDBFF]|^)"+createBMPCharacterClasses(loneLowSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.2.0";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint)) },clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(options){var result=createCharacterClassesFromData(this.data,options?options.bmpOnly:false);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],182:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],183:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&&current("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="‌";var ZWNJ="‍";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],184:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":179,"./data/iu-mappings.json":180,regenerate:181,regjsgen:182,regjsparser:183}],185:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":191,"./source-map/source-map-generator":192,"./source-map/source-node":193}],186:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":194,amdefine:195}],187:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":188,amdefine:195}],188:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:195}],189:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return mid}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return mid}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?-1:aLow}}exports.search=function search(aNeedle,aHaystack,aCompare){if(aHaystack.length===0){return-1}return recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare)}})},{amdefine:195}],190:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function generatedPositionAfter(mappingA,mappingB){var lineA=mappingA.generatedLine;var lineB=mappingB.generatedLine;var columnA=mappingA.generatedColumn;var columnB=mappingB.generatedColumn;return lineB>lineA||lineB==lineA&&columnB>=columnA||util.compareByGeneratedPositions(mappingA,mappingB)<=0}function MappingList(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}MappingList.prototype.unsortedForEach=function MappingList_forEach(aCallback,aThisArg){this._array.forEach(aCallback,aThisArg)};MappingList.prototype.add=function MappingList_add(aMapping){var mapping;if(generatedPositionAfter(this._last,aMapping)){this._last=aMapping;this._array.push(aMapping)}else{this._sorted=false;this._array.push(aMapping)}};MappingList.prototype.toArray=function MappingList_toArray(){if(!this._sorted){this._array.sort(util.compareByGeneratedPositions);this._sorted=true}return this._array};exports.MappingList=MappingList})},{"./util":194,amdefine:195}],191:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}sources=sources.map(util.normalize);this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.toArray().slice();smc.__originalMappings=aSourceMap._mappings.toArray().slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName]) }if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.computeColumnSpans=function SourceMapConsumer_computeColumnSpans(){for(var index=0;index<this._generatedMappings.length;++index){var mapping=this._generatedMappings[index];if(index+1<this._generatedMappings.length){var nextMapping=this._generatedMappings[index+1];if(mapping.generatedLine===nextMapping.generatedLine){mapping.lastGeneratedColumn=nextMapping.generatedColumn-1;continue}}mapping.lastGeneratedColumn=Infinity}};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(index>=0){var mapping=this._generatedMappings[index];if(mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};SourceMapConsumer.prototype.allGeneratedPositionsFor=function SourceMapConsumer_allGeneratedPositionsFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:Infinity};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mappings=[];var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];while(mapping&&mapping.originalLine===needle.originalLine){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[--index]}}return mappings.reverse()};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":186,"./base64-vlq":187,"./binary-search":189,"./util":194,amdefine:195}],192:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;var MappingList=require("./mapping-list").MappingList;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._skipValidation=util.getArg(aArgs,"skipValidation",false);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=new MappingList;this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);if(!this._skipValidation){this._validateMapping(generated,original,source,name)}if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.add({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.unsortedForEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;var mappings=this._mappings.toArray();for(var i=0,len=mappings.length;i<len;i++){mapping=mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":186,"./base64-vlq":187,"./mapping-list":190,"./util":194,amdefine:195}],193:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var NEWLINE_CODE=10;var isSourceNode="$$$isSourceNode$$$";function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;this[isSourceNode]=true;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk[isSourceNode]||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk[isSourceNode]||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk[isSourceNode]){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild[isSourceNode]){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i][isSourceNode]){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}for(var idx=0,length=chunk.length;idx<length;idx++){if(chunk.charCodeAt(idx)===NEWLINE_CODE){generated.line++;generated.column=0;if(idx+1===length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column++}}});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":192,"./util":194,amdefine:195}],194:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:195}],195:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps)})}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:130,path:129}],196:[function(require,module,exports){(function(process){"use strict";var argv=process.argv;module.exports=function(){if(argv.indexOf("--no-color")!==-1||argv.indexOf("--no-colors")!==-1||argv.indexOf("--color=false")!==-1){return false}if(argv.indexOf("--color")!==-1||argv.indexOf("--colors")!==-1||argv.indexOf("--color=true")!==-1||argv.indexOf("--color=always")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:130}],197:[function(require,module,exports){module.exports={name:"6to5",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"3.0.15",author:"Sebastian McKenzie <sebmck@gmail.com>",homepage:"https://6to5.org/",repository:"6to5/6to5",preferGlobal:true,main:"lib/6to5/index.js",bin:{"6to5":"./bin/6to5/index.js","6to5-node":"./bin/6to5-node"},browser:{"./lib/6to5/index.js":"./lib/6to5/browser.js","./lib/6to5/register.js":"./lib/6to5/register-browser.js"},keywords:["harmony","classes","modules","let","const","var","es6","transpile","transpiler","6to5"],scripts:{bench:"make bench",test:"make test"},dependencies:{"acorn-6to5":"0.11.1-25","ast-types":"~0.6.1",chalk:"^0.5.1",chokidar:"0.12.6",commander:"2.6.0","core-js":"^0.4.9",debug:"^2.1.1","detect-indent":"3.0.0",estraverse:"1.9.1",esutils:"1.1.6",esvalid:"1.1.0","fs-readdir-recursive":"0.1.0","js-tokenizer":"1.3.3",lodash:"3.0.0","output-file-sync":"1.1.0","private":"0.1.6","regenerator-6to5":"0.8.9-6",regexpu:"1.1.0",roadrunner:"1.0.4","source-map":"0.1.43","source-map-support":"0.2.9","supports-color":"1.2.0"},devDependencies:{browserify:"8.1.1",chai:"1.10.0",istanbul:"0.3.5",jscs:"1.10.0",jshint:"2.6.0","jshint-stylish":"1.0.0",matcha:"0.6.0",mocha:"2.1.0",rimraf:"2.2.8","uglify-js":"2.4.16"},optionalDependencies:{kexec:"1.0.0"}}},{}],198:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-delete":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceDelete",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-get":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-set":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceSet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"apply-constructor":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-comprehension-container":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-from":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-push":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STATEMENT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"async-to-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"next",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"throw",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"TryStatement",start:null,end:null,loc:null,range:null,block:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},handler:{type:"CatchClause",start:null,end:null,loc:null,range:null,param:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guard:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guardedHandlers:[],finalizer:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"then",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},bind:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Function",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},call:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CONTEXT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getIterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"default-parameter":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"DEFAULT_VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},defaults:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"define-property":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-default-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-module-declaration":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"extends":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:1,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:null,update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},get:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"has-own":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},inherits:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"Super expression must either be null or a function, not ",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"+",right:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:false,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__proto__",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require-wildcard":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"let-scoping-return":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-without-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"indexOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-identifier":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"require-assign-key":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},require:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},rest:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"START",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-global":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"self",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},slice:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"slice",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"sliced-to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},system:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"System",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"register",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_DEPENDENCIES",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXPORT_IDENTIFIER",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setters",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SETTERS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"execute",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXECUTE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-exports":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-module":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"typeof":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Literal",start:null,end:null,loc:null,range:null,value:"symbol",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},alternate:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"umd-runner-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"amd",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AMD_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_TEST",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}} },{}]},{},[1])(1)});
/*! jQuery v1.11.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-css,-css/addGetHookIf,-css/curCSS,-css/defaultDisplay,-css/hiddenVisibleSelectors,-css/support,-css/swap,-css/var/cssExpand,-css/var/isHidden,-css/var/rmargin,-css/var/rnumnonpx,-effects,-effects/Tween,-effects/animatedSelector,-effects/support,-dimensions,-offset,-wrap | (c) 2005, 2014 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="".trim,l={},m="1.11.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-css,-css/addGetHookIf,-css/curCSS,-css/defaultDisplay,-css/hiddenVisibleSelectors,-css/support,-css/swap,-css/var/cssExpand,-css/var/isHidden,-css/var/rmargin,-css/var/rnumnonpx,-effects,-effects/Tween,-effects/animatedSelector,-effects/support,-dimensions,-offset,-wrap",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,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=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.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},n.extend=n.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||n.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&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.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(l.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&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},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=s(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:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.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=s(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),n.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||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=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)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(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 mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(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 typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.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},z=b?function(a,b){if(a===b)return j=!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===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.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=db.selectors={cacheLength:50,createPseudo:fb,match:V,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(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===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]||db.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]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(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(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.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+" ").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(),t=!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&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&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]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)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&&(t&&((l[s]||(l[s]={}))[a]=[u,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()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(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),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?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===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.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 X.test(a.nodeName)},input:function(a){return W.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:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(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]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[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?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;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=[u,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[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(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 sb(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 tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(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?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.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]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(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}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(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&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.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){n.each(b,function(b,c){var d=n.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&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.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},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.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?n.extend(a,d):d}},e={};return d.pipe=d.then,n.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&&n.isFunction(a.promise)?e:0,g=1===f?a:n.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]&&n.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 I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c }catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.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()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.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=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.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 n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.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=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(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},V=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var W=/^(?:input|select|textarea)$/i,X=/^key/,Y=/^(?:mouse|contextmenu)|click/,Z=/^(?:focusinfocus|focusoutblur)$/,$=/^([^.]*)(?:\.(.+)|)$/;function _(){return!0}function ab(){return!1}function bb(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=$.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.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?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=$.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!Z.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.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]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,Z.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.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)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.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=((n.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?n(c,this).index(i)>=0:n.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[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Y.test(e)?this.mouseHooks:X.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),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||z,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!==bb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===bb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.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]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?_:ab):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:ab,isPropagationStopped:ab,isImmediatePropagationStopped:ab,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=_,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=_,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=_,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return W.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;W.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._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 n.event.remove(this,"._change"),!W.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.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=ab;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.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,n(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=ab),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function cb(a){var b=db.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var db="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",eb=/ jQuery\d+="(?:null|\d+)"/g,fb=new RegExp("<(?:"+db+")[\\s/>]","i"),gb=/^\s+/,hb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ib=/<([\w:]+)/,jb=/<tbody/i,kb=/<|&#?\w+;/,lb=/<(?:script|style|link)/i,mb=/checked\s*(?:[^=]|=\s*.checked.)/i,nb=/^$|\/(?:java|ecma)script/i,ob=/^true\/(.*)/,pb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,qb={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:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},rb=cb(z),sb=rb.appendChild(z.createElement("div"));qb.optgroup=qb.option,qb.tbody=qb.tfoot=qb.colgroup=qb.caption=qb.thead,qb.th=qb.td;function tb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,tb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function ub(a){V.test(a.type)&&(a.defaultChecked=a.checked)}function vb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function wb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function xb(a){var b=ob.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function yb(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function zb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._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++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ab(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(wb(b).text=a.text,xb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&V.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)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!fb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(sb.innerHTML=a.outerHTML,sb.removeChild(f=sb.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=tb(f),h=tb(a),g=0;null!=(e=h[g]);++g)d[g]&&Ab(e,d[g]);if(b)if(c)for(h=h||tb(a),d=d||tb(f),g=0;null!=(e=h[g]);g++)zb(e,d[g]);else zb(a,f);return d=tb(f,"script"),d.length>0&&yb(d,!i&&tb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=cb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(kb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ib.exec(f)||["",""])[1].toLowerCase(),k=qb[i]||qb._default,h.innerHTML=k[1]+f.replace(hb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&gb.test(f)&&p.push(b.createTextNode(gb.exec(f)[0])),!l.tbody){f="table"!==i||jb.test(f)?"<table>"!==k[1]||jb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.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),l.appendChecked||n.grep(tb(p,"input"),ub),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=tb(o.appendChild(f),"script"),g&&yb(h),c)){e=0;while(f=h[e++])nb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return U(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).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=vb(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=vb(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?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(tb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&yb(tb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(tb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.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 n.clone(this,a,b)})},html:function(a){return U(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(eb,""):void 0;if(!("string"!=typeof a||lb.test(a)||!l.htmlSerialize&&fb.test(a)||!l.leadingWhitespace&&gb.test(a)||qb[(ib.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(hb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(tb(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,n.cleanData(tb(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,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&mb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(tb(i,"script"),wb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,tb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,xb),j=0;f>j;j++)d=g[j],nb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(pb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}}),n.fn.delay=function(a,b){return a=n.fx?n.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=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var Bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(Bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.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||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.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}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var Cb,Db,Eb=n.expr.attrHandle,Fb=/^(?:checked|selected)$/i,Gb=l.getSetAttribute,Hb=l.input;n.fn.extend({attr:function(a,b){return U(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Db:Cb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.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 n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?Hb&&Gb||!Fb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(Gb?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Db={set:function(a,b,c){return b===!1?n.removeAttr(a,c):Hb&&Gb||!Fb.test(c)?a.setAttribute(!Gb&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=Eb[b]||n.find.attr;Eb[b]=Hb&&Gb||!Fb.test(b)?function(a,b,d){var e,f;return d||(f=Eb[b],Eb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,Eb[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),Hb&&Gb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):Cb&&Cb.set(a,b,c)}}),Gb||(Cb={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}},Eb.id=Eb.name=Eb.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:Cb.set},n.attrHooks.contenteditable={set:function(a,b,c){Cb.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var Ib=/^(?:input|select|textarea|button|object)$/i,Jb=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return U(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.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||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.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=n.find.attr(a,"tabindex");return b?parseInt(b,10):Ib.test(a.nodeName)||Jb.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var Kb=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(Kb," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.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(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(Kb," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.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(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._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(Kb," ").indexOf(b)>=0)return!0;return!1}}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.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 Lb=/%20/g,Mb=/\[\]$/,Nb=/\r?\n/g,Ob=/^(?:submit|button|image|reset|file)$/i,Pb=/^(?:input|select|textarea|keygen)/i;function Qb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Mb.test(a)?d(a,e):Qb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Qb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b) };if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Qb(c,a[c],b,e);return d.join("&").replace(Lb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Pb.test(this.nodeName)&&!Ob.test(a)&&(this.checked||!V.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Nb,"\r\n")}}):{name:b.name,value:c.replace(Nb,"\r\n")}}).get()}}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))},n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Rb=a.jQuery,Sb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Sb),b&&a.jQuery===n&&(a.jQuery=Rb),n},typeof b===L&&(a.jQuery=a.$=n),n}); //# sourceMappingURL=jquery.min.map
/*! jQuery v1.11.1 | (c) 2005, 2014 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.1",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)>=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=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"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=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)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(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||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(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 I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(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 ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(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 typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),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))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),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===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(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?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.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 fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.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},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.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=fb.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=fb.selectors={cacheLength:50,createPseudo:hb,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(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===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]||fb.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]&&fb.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(cb,db).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("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.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+" ").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()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(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),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).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:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(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]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.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?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(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 sb(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 tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(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 vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(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?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(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 vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(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]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.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(cb,db),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(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(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 ab(){return!0}function bb(){return!1}function cb(){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!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&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?ab:bb):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:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,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=bb;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=bb),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 db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={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>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(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,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(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 xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(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 Bb(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?(xb(b).text=a.text,yb(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)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(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=db(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(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.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(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.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=wb(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=wb(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(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(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(ub(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(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(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(ub(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&&nb.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(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.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(qb,"")));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 Cb,Db={};function Eb(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 Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[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 Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.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&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.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 Lb(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.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 Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(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",Fb(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 Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(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 Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(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]=Ub(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=Qb.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]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[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?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(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 Nb.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(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[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}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),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=Ib(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 Vb(this,!0)},hide:function(){return Vb(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 Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,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=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):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):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.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}}},Zb.propHooks.scrollTop=Zb.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=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.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 fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(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 hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(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")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(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],ac.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?Fb(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=hc(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 jc(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 kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),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:$b||fc(),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(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,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(kc,{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],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.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=kc(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&&cc.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(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("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($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=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(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=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 lc=/\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(lc,""):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 mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=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)?nc:mc)),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)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?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}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&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=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={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}},oc.id=oc.name=oc.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:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.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 sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?: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):sc.test(a.nodeName)||tc.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 uc=/[\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(uc," "):" ")){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(uc," "):"")){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(uc," ").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 vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\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(xc,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 yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(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 Mc(a,b,c,d){var e={},f=a===Ic;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 Nc(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 Oc(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 Pc(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:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,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?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),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=Cc.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||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),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]?", "+Jc+"; 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=Mc(Ic,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=Oc(k,v,c)),u=Pc(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.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),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 Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(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)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},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")&&Uc.test(this.nodeName)&&!Tc.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(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;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 Xc[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=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){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 _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.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(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.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,_c.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 bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.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.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(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=dd(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||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),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=dd(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]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.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 ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
/** * Copyright (c) 2015, Facebook, Inc. All rights reserved. * * Facebook, Inc. ("Facebook") owns all right, title and interest, including * all intellectual property and other proprietary rights, in and to the React * Native CustomComponents software (the "Software"). Subject to your * compliance with these terms, you are hereby granted a non-exclusive, * worldwide, royalty-free copyright license to (1) use and copy the Software; * and (2) reproduce and distribute the Software as part of your own software * ("Your Software"). Facebook reserves all rights not expressly granted to * you in this license agreement. * * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @providesModule NavigatorNavigationBar */ 'use strict'; var React = require('React'); var NavigatorNavigationBarStyles = require('NavigatorNavigationBarStyles'); var StaticContainer = require('StaticContainer.react'); var StyleSheet = require('StyleSheet'); var View = require('View'); var { Map } = require('immutable'); var COMPONENT_NAMES = ['Title', 'LeftButton', 'RightButton']; var navStatePresentedIndex = function(navState) { if (navState.presentedIndex !== undefined) { return navState.presentedIndex; } // TODO: rename `observedTopOfStack` to `presentedIndex` in `NavigatorIOS` return navState.observedTopOfStack; }; var NavigatorNavigationBar = React.createClass({ propTypes: { navigator: React.PropTypes.object, routeMapper: React.PropTypes.shape({ Title: React.PropTypes.func.isRequired, LeftButton: React.PropTypes.func.isRequired, RightButton: React.PropTypes.func.isRequired, }).isRequired, navState: React.PropTypes.shape({ routeStack: React.PropTypes.arrayOf(React.PropTypes.object), presentedIndex: React.PropTypes.number, }), style: View.propTypes.style, }, statics: { Styles: NavigatorNavigationBarStyles, }, componentWillMount: function() { this._components = {}; this._descriptors = {}; COMPONENT_NAMES.forEach(componentName => { this._components[componentName] = new Map(); this._descriptors[componentName] = new Map(); }); }, _getReusableProps: function( /*string*/componentName, /*number*/index ) /*object*/ { if (!this._reusableProps) { this._reusableProps = {}; } var propStack = this._reusableProps[componentName]; if (!propStack) { propStack = this._reusableProps[componentName] = []; } var props = propStack[index]; if (!props) { props = propStack[index] = {style:{}}; } return props; }, _updateIndexProgress: function( /*number*/progress, /*number*/index, /*number*/fromIndex, /*number*/toIndex ) { var amount = toIndex > fromIndex ? progress : (1 - progress); var oldDistToCenter = index - fromIndex; var newDistToCenter = index - toIndex; var interpolate; if (oldDistToCenter > 0 && newDistToCenter === 0 || newDistToCenter > 0 && oldDistToCenter === 0) { interpolate = NavigatorNavigationBarStyles.Interpolators.RightToCenter; } else if (oldDistToCenter < 0 && newDistToCenter === 0 || newDistToCenter < 0 && oldDistToCenter === 0) { interpolate = NavigatorNavigationBarStyles.Interpolators.CenterToLeft; } else if (oldDistToCenter === newDistToCenter) { interpolate = NavigatorNavigationBarStyles.Interpolators.RightToCenter; } else { interpolate = NavigatorNavigationBarStyles.Interpolators.RightToLeft; } COMPONENT_NAMES.forEach(function (componentName) { var component = this._components[componentName].get(this.props.navState.routeStack[index]); var props = this._getReusableProps(componentName, index); if (component && interpolate[componentName](props.style, amount)) { component.setNativeProps(props); } }, this); }, updateProgress: function( /*number*/progress, /*number*/fromIndex, /*number*/toIndex ) { var max = Math.max(fromIndex, toIndex); var min = Math.min(fromIndex, toIndex); for (var index = min; index <= max; index++) { this._updateIndexProgress(progress, index, fromIndex, toIndex); } }, render: function() { var navState = this.props.navState; var components = COMPONENT_NAMES.map(function (componentName) { return navState.routeStack.map( this._getComponent.bind(this, componentName) ); }, this); return ( <View style={[styles.navBarContainer, this.props.style]}> {components} </View> ); }, _getComponent: function( /*string*/componentName, /*object*/route, /*number*/index ) /*?Object*/ { if (this._descriptors[componentName].includes(route)) { return this._descriptors[componentName].get(route); } var rendered = null; var content = this.props.routeMapper[componentName]( this.props.navState.routeStack[index], this.props.navigator, index, this.props.navState ); if (!content) { return null; } var initialStage = index === navStatePresentedIndex(this.props.navState) ? NavigatorNavigationBarStyles.Stages.Center : NavigatorNavigationBarStyles.Stages.Left; rendered = ( <View ref={(ref) => { this._components[componentName] = this._components[componentName].set(route, ref); }} style={initialStage[componentName]}> {content} </View> ); this._descriptors[componentName] = this._descriptors[componentName].set(route, rendered); return rendered; }, }); var styles = StyleSheet.create({ navBarContainer: { position: 'absolute', height: NavigatorNavigationBarStyles.General.TotalNavHeight, top: 0, left: 0, right: 0, backgroundColor: 'transparent', }, }); module.exports = NavigatorNavigationBar;
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/Persist");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Persist":28,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":34}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":27,"./Shared":33}],4:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},o.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),o.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" 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: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},o.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},o.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},o.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},o.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},o.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},o.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},o.prototype.sort=function(a,b){var c=this,d=n.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1 },index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},o.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},o.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},o.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=o},{"./Index2d":10,"./IndexBinaryTree":11,"./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Overload":26,"./Path":27,"./ReactorIO":31,"./Shared":33}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":33}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.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"},b.exports=i},{"./Db.js":8,"./Metrics.js":14,"./Overload":26,"./Shared":33}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":14,"./Overload":26,"./Shared":33}],9:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./GeoHash":9,"./Path":27,"./Shared":33}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":27,"./Shared":33}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":27,"./Shared":33}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"), d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":33}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":25,"./Shared":33}],15:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":26,"./Serialiser":32}],18:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],19:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":26}],20:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f.triggerStack={},f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b["export"],e=b["import"],d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g["export"],c=g["import"],b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":26}],24:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":27,"./Shared":33}],26:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],27:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":33}],28:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){b?c(b):o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"); }else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":29,"./PersistCrypto":30,"./Shared":33,async:35,localforage:70}],29:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":33,pako:71}],30:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":33,"crypto-js":44}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":33}],32:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],33:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.745",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Tags":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":26}],34:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],35:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){for(;!j.paused&&g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){s.unshift(a)}function f(a){var b=p(s,a);b>=0&&s.splice(b,1)}function g(){j--,k(s.slice(0),function(a){a()})}"function"==typeof arguments[1]&&(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=!1,s=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(t,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](s,l))}if(!q){for(var j,k=N(a[d])?a[d]:[a[d]],s=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,q=!0,c(a,e)}else l[d]=b,K.setImmediate(g)}),t=k.slice(0,k.length-1),u=t.length;u--;){if(!(j=a[t[u]]))throw new Error("Has nonexistent dependency in "+t.join(", "));if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](s,l)):e(i)}})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c.apply(null,[null].concat(f))});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={},f=Object.prototype.hasOwnProperty;b=b||e;var g=r(function(e){var g=e.pop(),h=b.apply(null,e);f.call(c,h)?K.setImmediate(function(){g.apply(null,c[h])}):f.call(d,h)?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([r(function(a){c[h]=a;var b=d[h];delete d[h];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return g.memo=c,g.unmemoized=a,g},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:87}],36:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],37:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":38}],38:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0); var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],39:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2,l=j|k;g[h>>>2]|=l<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":38}],40:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":38}],41:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":38,"./hmac":43,"./sha1":62}],42:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":37,"./core":38}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":38}],44:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":36,"./cipher-core":37,"./core":38,"./enc-base64":39,"./enc-utf16":40,"./evpkdf":41,"./format-hex":42,"./hmac":43,"./lib-typedarrays":45,"./md5":46,"./mode-cfb":47,"./mode-ctr":49,"./mode-ctr-gladman":48,"./mode-ecb":50,"./mode-ofb":51,"./pad-ansix923":52,"./pad-iso10126":53,"./pad-iso97971":54,"./pad-nopadding":55,"./pad-zeropadding":56,"./pbkdf2":57,"./rabbit":59,"./rabbit-legacy":58,"./rc4":60,"./ripemd160":61,"./sha1":62,"./sha224":63,"./sha256":64,"./sha3":65,"./sha384":66,"./sha512":67,"./tripledes":68,"./x64-core":69}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":38}],46:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":38}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":37,"./core":38}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":37,"./core":38}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":37,"./core":38}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":37,"./core":38}],51:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":37,"./core":38}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":37,"./core":38}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":37,"./core":38}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":37,"./core":38}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":37,"./core":38}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":37,"./core":38}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":38,"./hmac":43,"./sha1":62}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],61:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":38}],62:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":38}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":38,"./sha256":64}],64:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":38}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":38,"./x64-core":69}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)]); },_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":38,"./sha512":67,"./x64-core":69}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":38,"./x64-core":69}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],69:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":38}],70:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0;var e=function(a){function b(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b={};return b[h.INDEXEDDB]=!!function(){try{var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB;return"undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent)?!1:b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),b[h.WEBSQL]=!!function(){try{return a.openDatabase}catch(b){return!1}}(),b[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),b}(a),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function a(b){d(this,a),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return a.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},a.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},a.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},a.prototype.supports=function(a){return!!l[a]},a.prototype._extend=function(a){e(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<j.length;a++)b(this,j[a])},a.prototype.createInstance=function(b){return new a(b)},a}();return new n}("undefined"!=typeof window?window:self);b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c=function(a){function b(b,c){b=b||[],c=c||{};try{return new Blob(b,c)}catch(d){if("TypeError"!==d.name)throw d;for(var e=a.BlobBuilder||a.MSBlobBuilder||a.MozBlobBuilder||a.WebKitBlobBuilder,f=new e,g=0;g<b.length;g+=1)f.append(b[g]);return f.getBlob(c.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(a){return new Promise(function(c,e){var f=b([""],{type:"image/png"}),g=a.transaction([D],"readwrite");g.objectStore(D).put(f,"key"),g.oncomplete=function(){var b=a.transaction([D],"readwrite"),f=b.objectStore(D).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}},g.onerror=g.onabort=e})["catch"](function(){return!1})}function f(a){return"boolean"==typeof B?Promise.resolve(B):e(a).then(function(a){return B=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(a){var d=c(atob(a.data));return b([d],{type:a.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){var b=this,c=b._initReady().then(function(){var a=C[b._dbInfo.name];return a&&a.dbReady?a.dbReady:void 0});return c.then(a,a),c}function k(a){var b=C[a.name],c={};c.promise=new Promise(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function l(a){var b=C[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function m(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];C||(C={});var f=C[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},C[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=j);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady()["catch"](b))}var k=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,n(d)}).then(function(a){return d.db=a,q(d,c._defaultConfig.version)?o(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<k.length;b++){var e=k[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function n(a){return p(a,!1)}function o(a){return p(a,!0)}function p(b,c){return new Promise(function(d,e){if(b.db){if(!c)return d(b.db);k(b),b.db.close()}var f=[b.name];c&&f.push(b.version);var g=A.open.apply(A,f);c&&(g.onupgradeneeded=function(c){var d=g.result;try{d.createObjectStore(b.storeName),c.oldVersion<=1&&d.createObjectStore(D)}catch(e){if("ConstraintError"!==e.name)throw e;a.console.warn('The database "'+b.name+'" has been upgraded from version '+c.oldVersion+" to version "+c.newVersion+', but the storage "'+b.storeName+'" already exists.')}}),g.onerror=function(){e(g.error)},g.onsuccess=function(){d(g.result),l(b)}})}function q(b,c){if(!b.db)return!0;var d=!b.db.objectStoreNames.contains(b.storeName),e=b.version<b.db.version,f=b.version>b.db.version;if(e&&(b.version!==c&&a.console.warn('The database "'+b.name+"\" can't be downgraded from version "+b.db.version+" to version "+b.version+"."),b.version=b.db.version),f||d){if(d){var g=b.db.version+1;g>b.version&&(b.version=g)}return!0}return!1}function r(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(b);g.onsuccess=function(){var b=g.result;void 0===b&&(b=null),i(b)&&(b=h(b)),a(b)},g.onerror=function(){c(g.error)}})["catch"](c)});return z(e,c),e}function s(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return z(d,b),d}function t(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var h=new Promise(function(a,d){var h;e.ready().then(function(){return h=e._dbInfo,c instanceof Blob?f(h.db).then(function(a){return a?c:g(c)}):c}).then(function(c){var e=h.db.transaction(h.storeName,"readwrite"),f=e.objectStore(h.storeName);null===c&&(c=void 0),e.oncomplete=function(){void 0===c&&(c=null),a(c)},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;d(a)};var g=f.put(c,b)})["catch"](d)});return z(h,d),h}function u(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."), b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](b);f.oncomplete=function(){a()},f.onerror=function(){c(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;c(a)}})["catch"](c)});return z(e,c),e}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return z(c,a),c}function w(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return z(c,a),c}function x(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return z(d,b),d}function y(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return z(c,a),c}function z(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var A=A||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB;if(A){var B,C,D="local-forage-detect-blob-support",E={_driver:"asyncStorage",_initStorage:m,iterate:s,getItem:r,setItem:t,removeItem:u,clear:v,length:w,key:x,keys:y};return E}}("undefined"!=typeof window?window:self);b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=function(a){function b(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=m.length-1;c>=0;c--){var d=m.key(c);0===d.indexOf(a)&&m.removeItem(d)}});return l(c,a),c}function e(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=d.ready().then(function(){var a=d._dbInfo,c=m.getItem(a.keyPrefix+b);return c&&(c=a.serializer.deserialize(c)),c});return l(e,c),e}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=m.length,g=1,h=0;f>h;h++){var i=m.key(h);if(0===i.indexOf(d)){var j=m.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=m.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=m.length,d=[],e=0;c>e;e++)0===m.key(e).indexOf(a.keyPrefix)&&d.push(m.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=d.ready().then(function(){var a=d._dbInfo;m.removeItem(a.keyPrefix+b)});return l(e,c),e}function k(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var f=e.ready().then(function(){void 0===c&&(c=null);var a=c;return new Promise(function(d,f){var g=e._dbInfo;g.serializer.serialize(c,function(c,e){if(e)f(e);else try{m.setItem(g.keyPrefix+b,c),d(a)}catch(h){"QuotaExceededError"!==h.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==h.name||f(h),f(h)}})})});return l(f,d),f}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=null;try{if(!(a.localStorage&&"setItem"in a.localStorage))return;m=a.localStorage}catch(n){return}var o={_driver:"localStorageWrapper",_initStorage:b,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};return o}("undefined"!=typeof window?window:self);b["default"]=d,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c=function(a){function b(b,c){b=b||[],c=c||{};try{return new Blob(b,c)}catch(d){if("TypeError"!==d.name)throw d;for(var e=a.BlobBuilder||a.MSBlobBuilder||a.MozBlobBuilder||a.WebKitBlobBuilder,f=new e,g=0;g<b.length;g+=1)f.append(b[g]);return f.getBlob(c.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(a){if(a.substring(0,k)!==j)return JSON.parse(a);var c,d=a.substring(w),f=a.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return b([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};return x}("undefined"!=typeof window?window:self);b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=function(a){function b(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(a,c){try{d.db=m(d.name,String(d.version),d.description,d.size)}catch(e){return c(e)}d.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,a()},function(a,b){c(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo;e.db.transaction(function(d){d.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[b],function(b,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),a(d)},function(a,b){c(b)})})})["catch"](c)});return l(e,c),e}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var f=new Promise(function(a,d){e.ready().then(function(){void 0===c&&(c=null);var f=c,g=e._dbInfo;g.serializer.serialize(c,function(c,e){e?d(e):g.db.transaction(function(e){e.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[b,c],function(){a(f)},function(a,b){d(b)})},function(a){a.code===a.QUOTA_ERR&&d(a)})})})["catch"](d)});return l(f,d),f}function g(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo;e.db.transaction(function(d){d.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[b],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(e,c),e}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=a.openDatabase;if(m){var n={_driver:"webSQLStorage",_initStorage:b,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};return n}}("undefined"!=typeof window?window:self);b["default"]=d,a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:87}],71:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":72,"./lib/inflate":73,"./lib/utils/common":74,"./lib/zlib/constants":77}],72:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);b.header&&h.deflateSetHeader(this.strm,b.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d===r?(this.onEnd(p),e.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":74,"./utils/strings":75,"./zlib/deflate":79,"./zlib/messages":84,"./zlib/zstream":86}],73:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l=this.strm,m=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?l.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new h.Buf8(m),l.next_out=0,l.avail_out=m),c=g.inflate(l,j.Z_NO_FLUSH),c===j.Z_BUF_ERROR&&o===!0&&(c=j.Z_OK,o=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0!==l.avail_out&&c!==j.Z_STREAM_END&&(0!==l.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(l.output,l.next_out),f=l.next_out-e,k=i.buf2string(l.output,e),l.next_out=f,l.avail_out=m-f,f&&h.arraySet(l.output,l.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(l.output,l.next_out)))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d===j.Z_SYNC_FLUSH?(this.onEnd(j.Z_OK),l.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":74,"./utils/strings":75,"./zlib/constants":77,"./zlib/gzheader":80,"./zlib/inflate":82,"./zlib/messages":84,"./zlib/zstream":86}],74:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],75:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":74}],76:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],77:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],78:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],79:[function(a,b,c){"use strict";function d(a,b){return a.msg=H[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(D.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){E._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,D.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=F(a.adler,b,e,c):2===a.state.wrap&&(a.adler=G(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ka?a.strstart-(a.w_size-ka):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ja,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ja-(m-f),f=m-ja,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ka)){D.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ia)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ia-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ia)););}while(a.lookahead<ka&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===I)return ta;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ta;if(a.strstart-a.block_start>=a.w_size-ka&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ta:ta}function o(a,b){for(var c,d;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c)),a.match_length>=ia)if(d=E._tr_tally(a,a.strstart-a.match_start,a.match_length-ia),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ia){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function p(a,b){for(var c,d,e;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ia-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===T||a.match_length===ia&&a.strstart-a.match_start>4096)&&(a.match_length=ia-1)),a.prev_length>=ia&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ia,d=E._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ia),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ia-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ta}else if(a.match_available){if(d=E._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ta}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=E._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ja){if(m(a),a.lookahead<=ja&&b===I)return ta;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ia&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ja;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ja-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ia?(c=E._tr_tally(a,1,a.match_length-ia),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===I)return ta;break}if(a.match_length=0,c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=C[a.level].max_lazy,a.good_match=C[a.level].good_length,a.nice_match=C[a.level].nice_length,a.max_chain_length=C[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ia-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new D.Buf16(2*ga),this.dyn_dtree=new D.Buf16(2*(2*ea+1)),this.bl_tree=new D.Buf16(2*(2*fa+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new D.Buf16(ha+1),this.heap=new D.Buf16(2*da+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new D.Buf16(2*da+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Y,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?ma:ra,a.adler=2===b.wrap?0:1,b.last_flush=I,E._tr_init(b),N):d(a,P)}function w(a){var b=v(a);return b===N&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?P:(a.state.gzhead=b,N):P}function y(a,b,c,e,f,g){if(!a)return P;var h=1;if(b===S&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>$||c!==Z||8>e||e>15||0>b||b>9||0>g||g>W)return d(a,P);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ia-1)/ia),i.window=new D.Buf8(2*i.w_size),i.head=new D.Buf16(i.hash_size),i.prev=new D.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new D.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,Z,_,aa,X)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>M||0>b)return a?d(a,P):P;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===sa&&b!==L)return d(a,0===a.avail_out?R:P);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===ma)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=G(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=na):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,xa),h.status=ra);else{var m=Z+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=U||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=la),m+=31-m%31,h.status=ra,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===na)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=qa)}else h.status=qa;if(h.status===qa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=ra)):h.status=ra),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,N}else if(0===a.avail_in&&e(b)<=e(c)&&b!==L)return d(a,R);if(h.status===sa&&0!==a.avail_in)return d(a,R);if(0!==a.avail_in||0!==h.lookahead||b!==I&&h.status!==sa){var o=h.strategy===U?r(h,b):h.strategy===V?q(h,b):C[h.level].func(h,b);if(o!==va&&o!==wa||(h.status=sa),o===ta||o===va)return 0===a.avail_out&&(h.last_flush=-1), N;if(o===ua&&(b===J?E._tr_align(h):b!==M&&(E._tr_stored_block(h,0,0,!1),b===K&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,N}return b!==L?N:h.wrap<=0?O:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?N:O)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa?d(a,P):(a.state=null,b===ra?d(a,Q):N)):P}var C,D=a("../utils/common"),E=a("./trees"),F=a("./adler32"),G=a("./crc32"),H=a("./messages"),I=0,J=1,K=3,L=4,M=5,N=0,O=1,P=-2,Q=-3,R=-5,S=-1,T=1,U=2,V=3,W=4,X=0,Y=2,Z=8,$=9,_=15,aa=8,ba=29,ca=256,da=ca+1+ba,ea=30,fa=19,ga=2*da+1,ha=15,ia=3,ja=258,ka=ja+ia+1,la=32,ma=42,na=69,oa=73,pa=91,qa=103,ra=113,sa=666,ta=1,ua=2,va=3,wa=4,xa=3;C=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":74,"./adler32":76,"./crc32":78,"./messages":84,"./trees":85}],80:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],81:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],82:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":74,"./adler32":76,"./crc32":78,"./inffast":81,"./inftrees":83}],83:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":74}],84:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],85:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return 256>a?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;W>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;V>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;W>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;Q-1>d;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;16>d;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;T>d;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;W>=b;b++)g[b]=0;for(a=0;143>=a;)ga[2*a+1]=8,a++,g[8]++;for(;255>=a;)ga[2*a+1]=9,a++,g[9]++;for(;279>=a;)ga[2*a+1]=7,a++,g[7]++;for(;287>=a;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;T>a;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;S>b;b++)a.dyn_ltree[2*b]=0;for(b=0;T>b;b++)a.dyn_dtree[2*b]=0;for(b=0;U>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):10>=h?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;c>=d;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(l>h){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):10>=h?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;d>e;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;R>b;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":74}],86:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}],87:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}]},{},[1]);
/** * 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 reactComponentExpect * @nolint */ 'use strict'; var ReactInstanceMap = require('ReactInstanceMap'); var ReactTestUtils = require('ReactTestUtils'); var assign = require('Object.assign'); function reactComponentExpect(instance) { if (instance instanceof reactComponentExpectInternal) { return instance; } if (!(this instanceof reactComponentExpect)) { return new reactComponentExpect(instance); } expect(instance).not.toBeNull(); var internalInstance = ReactInstanceMap.get(instance); expect(typeof internalInstance).toBe('object'); expect(typeof internalInstance.constructor).toBe('function'); expect(ReactTestUtils.isElement(internalInstance)).toBe(false); return new reactComponentExpectInternal(internalInstance); } function reactComponentExpectInternal(internalInstance) { this._instance = internalInstance; } assign(reactComponentExpectInternal.prototype, { // Getters ------------------------------------------------------------------- /** * @instance: Retrieves the backing instance. */ instance: function() { return this._instance.getPublicInstance(); }, /** * There are two types of components in the world. * - A component created via React.createClass() - Has a single child * subComponent - the return value from the .render() function. This * function @subComponent expects that this._instance is component created * with React.createClass(). * - A primitive DOM component - which has many renderedChildren, each of * which may have a name that is unique with respect to its siblings. This * method will fail if this._instance is a primitive component. * * TL;DR: An instance may have a subComponent (this._renderedComponent) or * renderedChildren, but never both. Neither will actually show up until you * render the component (simply instantiating is not enough). */ expectRenderedChild: function() { this.toBeCompositeComponent(); var child = this._instance._renderedComponent; // TODO: Hide ReactEmptyComponent instances here? return new reactComponentExpectInternal(child); }, /** * The nth child of a DOMish component instance that is not falsy. */ expectRenderedChildAt: function(childIndex) { // Currently only dom components have arrays of children, but that will // change soon. this.toBeDOMComponent(); var renderedChildren = this._instance._renderedComponent._renderedChildren || {}; for (var name in renderedChildren) { if (!renderedChildren.hasOwnProperty(name)) { continue; } if (renderedChildren[name]) { if (renderedChildren[name]._mountIndex === childIndex) { return new reactComponentExpectInternal(renderedChildren[name]); } } } throw new Error('Child:' + childIndex + ' is not found'); }, toBeDOMComponentWithChildCount: function(n) { this.toBeDOMComponent(); expect(this._instance._renderedComponent._renderedChildren).toBeTruthy(); var len = Object.keys(this._instance._renderedComponent._renderedChildren) .length; expect(len).toBe(n); return this; }, toBeDOMComponentWithNoChildren: function() { this.toBeDOMComponent(); expect(this._instance._renderedComponent._renderedChildren).toBeFalsy(); return this; }, // Matchers ------------------------------------------------------------------ toBeComponentOfType: function(constructor) { expect( this._instance._currentElement.type === constructor ).toBe(true); return this; }, /** * A component that is created with React.createClass. Just duck typing * here. */ toBeCompositeComponent: function() { expect( typeof this.instance() === 'object' && typeof this.instance().render === 'function' ).toBe(true); return this; }, toBeCompositeComponentWithType: function(constructor) { this.toBeCompositeComponent(); expect( this._instance._currentElement.type === constructor ).toBe(true); return this; }, toBeTextComponentWithValue: function(val) { var elementType = typeof this._instance._currentElement; expect(elementType === 'string' || elementType === 'number').toBe(true); expect(this._instance._stringText).toBe(val); return this; }, toBePresent: function() { expect(this.instance()).toBeTruthy(); return this; }, /** * A terminal type of component representing some virtual dom node. Just duck * typing here. */ toBeDOMComponent: function() { expect(ReactTestUtils.isDOMComponent(this.instance())).toBe(true); return this; }, /** * @deprecated * @see toBeComponentOfType */ toBeDOMComponentWithTag: function(tag) { this.toBeDOMComponent(); expect(this.instance().tagName).toBe(tag.toUpperCase()); return this; }, /** * Check that internal state values are equal to a state of expected values. */ scalarStateEqual: function(stateNameToExpectedValue) { expect(this.instance()).toBeTruthy(); for (var stateName in stateNameToExpectedValue) { if (!stateNameToExpectedValue.hasOwnProperty(stateName)) { continue; } expect(this.instance().state[stateName]) .toEqual(stateNameToExpectedValue[stateName]); } return this; }, /** * Check a set of props are equal to a set of expected values - only works * with scalars. */ scalarPropsEqual: function(propNameToExpectedValue) { expect(this.instance()).toBeTruthy(); for (var propName in propNameToExpectedValue) { if (!propNameToExpectedValue.hasOwnProperty(propName)) { continue; } expect(this.instance().props[propName]) .toEqual(propNameToExpectedValue[propName]); } return this; }, /** * Check a set of props are equal to a set of expected values - only works * with scalars. */ scalarContextEqual: function(contextNameToExpectedValue) { expect(this.instance()).toBeTruthy(); for (var contextName in contextNameToExpectedValue) { if (!contextNameToExpectedValue.hasOwnProperty(contextName)) { continue; } expect(this.instance().context[contextName]) .toEqual(contextNameToExpectedValue[contextName]); } return this; } }); module.exports = reactComponentExpect;
YUI.add("event-focus",function(e,t){function u(t,r,u){var a="_"+t+"Notifiers";e.Event.define(t,{_useActivate:o,_attach:function(i,s,o){return e.DOM.isWindow(i)?n._attach([t,function(e){s.fire(e)},i]):n._attach([r,this._proxy,i,this,s,o],{capture:!0})},_proxy:function(t,r,i){var s=t.target,f=t.currentTarget,l=s.getData(a),c=e.stamp(f._node),h=o||s!==f,p;r.currentTarget=i?s:f,r.container=i?f:null,l?h=!0:(l={},s.setData(a,l),h&&(p=n._attach([u,this._notify,s._node]).sub,p.once=!0)),l[c]||(l[c]=[]),l[c].push(r),h||this._notify(t)},_notify:function(t,n){var r=t.currentTarget,i=r.getData(a),o=r.ancestors(),u=r.get("ownerDocument"),f=[],l=i?e.Object.keys(i).length:0,c,h,p,d,v,m,g,y,b,w;r.clearData(a),o.push(r),u&&o.unshift(u),o._nodes.reverse(),l&&(m=l,o.some(function(t){var n=e.stamp(t),r=i[n],s,o;if(r){l--;for(s=0,o=r.length;s<o;++s)r[s].handle.sub.filter&&f.push(r[s])}return!l}),l=m);while(l&&(c=o.shift())){d=e.stamp(c),h=i[d];if(h){for(g=0,y=h.length;g<y;++g){p=h[g],b=p.handle.sub,v=!0,t.currentTarget=c,b.filter&&(v=b.filter.apply(c,[c,t].concat(b.args||[])),f.splice(s(f,p),1)),v&&(t.container=p.container,w=p.fire(t));if(w===!1||t.stopped===2)break}delete h[d],l--}if(t.stopped!==2)for(g=0,y=f.length;g<y;++g){p=f[g],b=p.handle.sub,b.filter.apply(c,[c,t].concat(b.args||[]))&&(t.container=p.container,t.currentTarget=c,w=p.fire(t));if(w===!1||t.stopped===2)break}if(t.stopped)break}},on:function(e,t,n){t.handle=this._attach(e._node,n)},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,s){i(s)&&(n.filter=function(n){return e.Selector.test(n._node,s,t===n?null:t._node)}),n.handle=this._attach(t._node,r,!0)},detachDelegate:function(e,t){t.handle.detach()}},!0)}var n=e.Event,r=e.Lang,i=r.isString,s=e.Array.indexOf,o=function(){var t=!1,n=e.config.doc,r;return n&&(r=n.createElement("p"),r.setAttribute("onbeforeactivate",";"),t=r.onbeforeactivate!==undefined),t}();o?(u("focus","beforeactivate","focusin"),u("blur","beforedeactivate","focusout")):(u("focus","focus","focus"),u("blur","blur","blur"))},"@VERSION@",{requires:["event-synthetic"]});
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("react");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=e(t);function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function a(t,e){return a=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},a(t,e)}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&a(t,e)}function l(t){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l(t)}function u(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function s(t,e){if(e&&("object"===l(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return u(t)}function c(t){return c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},c(t)}function p(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=f(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,o=function(){};return{s:o,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,i=!0,l=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return i=t.done,t},e:function(t){l=!0,a=t},f:function(){try{i||null==n.return||n.return()}finally{if(l)throw a}}}}function f(t,e){if(t){if("string"==typeof t)return y(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(t,e):void 0}}function y(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function v(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}var d,h,b,m=function(e){i(h,t.Component);var a,l,u,f,y,d=(a=h,l=v(),function(){var t,e=c(a);if(l){var n=c(this).constructor;t=Reflect.construct(e,arguments,n)}else t=e.apply(this,arguments);return s(this,t)});function h(){return r(this,h),d.apply(this,arguments)}return u=h,(f=[{key:"initMap",value:function(){this.map=new google.maps.Map(this.container,this.props.options),this.props.onMapReady&&this.props.onMapReady({map:this.map}),this.initOverlays(this.props.overlays),this.bindMapEvent("click",this.props.onMapClick),this.bindMapEvent("dragend",this.props.onMapDragEnd),this.bindMapEvent("zoom_changed",this.props.onZoomChanged)}},{key:"initOverlays",value:function(t){if(t){var e,n=p(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;r.setMap(this.map),this.bindOverlayEvents(r)}}catch(t){n.e(t)}finally{n.f()}}}},{key:"bindOverlayEvents",value:function(t){var e=this;t.addListener("click",(function(n){e.props.onOverlayClick&&e.props.onOverlayClick({originalEvent:n,overlay:t,map:e.map})})),t.getDraggable()&&this.bindDragEvents(t)}},{key:"bindDragEvents",value:function(t){this.bindDragEvent(t,"dragstart",this.props.onOverlayDragStart),this.bindDragEvent(t,"drag",this.props.onOverlayDrag),this.bindDragEvent(t,"dragend",this.props.onOverlayDragEnd)}},{key:"bindMapEvent",value:function(t,e){this.map.addListener(t,(function(t){e&&e(t)}))}},{key:"bindDragEvent",value:function(t,e,n){var r=this;t.addListener(e,(function(e){n&&n({originalEvent:e,overlay:t,map:r.map})}))}},{key:"getMap",value:function(){return this.map}},{key:"componentDidUpdate",value:function(t,e,n){if(t.overlays!==this.props.overlays){if(t.overlays){var r,o=p(t.overlays);try{for(o.s();!(r=o.n()).done;){var a=r.value;google.maps.event.clearInstanceListeners(a),a.setMap(null)}}catch(t){o.e(t)}finally{o.f()}}this.initOverlays(this.props.overlays)}}},{key:"componentDidMount",value:function(){this.initMap()}},{key:"render",value:function(){var t=this;return n.default.createElement("div",{ref:function(e){return t.container=e},style:this.props.style,className:this.props.className})}}])&&o(u.prototype,f),y&&o(u,y),h}();b={options:null,overlays:null,style:null,className:null,onMapReady:null,onMapClick:null,onMapDragEnd:null,onZoomChanged:null,onOverlayDragStart:null,onOverlayDrag:null,onOverlayDragEnd:null,onOverlayClick:null},(h="defaultProps")in(d=m)?Object.defineProperty(d,h,{value:b,enumerable:!0,configurable:!0,writable:!0}):d[h]=b,exports.GMap=m;
/* NUGET: BEGIN LICENSE TEXT jQuery v1.9.1 Microsoft grants you the right to use these script files for the sole purpose of either: (i) interacting through your browser with the Microsoft website, subject to the website's terms of use; or (ii) using the files as included with a Microsoft product subject to that product's license terms. Microsoft reserves all other rights to the files not expressly granted by Microsoft, whether by implication, estoppel or otherwise. The notices and licenses below are for informational purposes only. *************************************************** * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors ******************************** * Includes Sizzle CSS Selector Engine * http://sizzlejs.com/ * Copyright 2012 jQuery Foundation and other contributors ******************************************************** Provided for Informational Purposes Only MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * NUGET: END LICENSE TEXT */ /*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},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(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&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(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):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,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===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]||st.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]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.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.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.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"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={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:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.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 b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.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){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,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"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.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),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
"use strict";import Dimensions from"../Dimensions";import{useEffect,useState}from"react";export default function useWindowDimensions(){var n=useState(function(){return Dimensions.get("window")}),e=n[0],i=n[1];return useEffect(function(){function n(n){var e=n.window;i(e)}return Dimensions.addEventListener("change",n),i(Dimensions.get("window")),function(){Dimensions.removeEventListener("change",n)}},[]),e};
/** * @fileoverview Utility functions for React version configuration * @author Yannick Croissant */ 'use strict'; function getFromContext(context) { var confVer = '999.999.999'; // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings) if (context.settings.react && context.settings.react.version) { confVer = context.settings.react.version; } confVer = /^[0-9]+\.[0-9]+$/.test(confVer) ? `${confVer}.0` : confVer; return confVer.split('.').map(function(part) { return Number(part); }); } function test(context, methodVer) { var confVer = getFromContext(context); methodVer = methodVer.split('.').map(function(part) { return Number(part); }); var higherMajor = methodVer[0] < confVer[0]; var higherMinor = methodVer[0] === confVer[0] && methodVer[1] < confVer[1]; var higherOrEqualPatch = methodVer[0] === confVer[0] && methodVer[1] === confVer[1] && methodVer[2] <= confVer[2]; return higherMajor || higherMinor || higherOrEqualPatch; } module.exports = { test: test };
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highstock JS v2.0.1 (2014-04-24) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () {}, charts = [], chartCount = 0, PRODUCT = 'Highstock', VERSION = '2.0.1', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', MILLISECOND = 'millisecond', SECOND = 'second', MINUTE = 'minute', HOUR = 'hour', DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used makeTime, timezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}; // The Highcharts namespace var Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {}; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Take an array and turn into a hash with even number arguments as keys and odd numbers as * values. Allows creating constants for commonly used style properties, attributes etc. * Avoid it in performance critical situations like looping */ function hash() { var i = 0, args = arguments, length = args.length, obj = {}; for (; i < length; i++) { obj[args[i++]] = args[i]; } return obj; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof arg !== 'undefined' && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () {}; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? (n.toString().split('.')[1] || '').length : // preserve decimals (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - timezoneOffset), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, options) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (options && options.allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Helper class that contains variuos counters that are local to the chart. */ function ChartCounters() { this.color = 0; this.symbol = 0; } ChartCounters.prototype = { /** * Wraps the color counter if it reaches the specified length. */ wrapColor: function (length) { if (this.color >= length) { this.color = 0; } }, /** * Wraps the symbol counter if it reaches the specified length. */ wrapSymbol: function (length) { if (this.symbol >= length) { this.symbol = 0; } } }; /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } else if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ /*jslint white: true*/ timeUnits = hash( MILLISECOND, 1, SECOND, 1000, MINUTE, 60000, HOUR, 3600000, DAY, 24 * 3600000, WEEK, 7 * 24 * 3600000, MONTH, 31 * 24 * 3600000, YEAR, 31556952000 ); /*jslint white: false*/ /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx, Step = Fx.step, dSetter, Tween = $.Tween, propHooks = Tween && Tween.propHooks, opacityHook = $.cssHooks.opacity; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Step, base; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && Tween) { // jQuery 1.8 model obj = propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { var elem; // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap(opacityHook, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) dSetter = function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }; // jQuery 1.8 style if (Tween) { propHooks.d = { set: dSetter }; // pre 1.8 } else { // animate paths Step.d = dSetter; } /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (this[0]) { if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } } return ret; }; }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; delete eventArguments.returnValue; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { $(el).stop(); } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, // align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#606060', cursor: 'default', fontSize: '11px' } }; defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'], // docs symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/stock/2.0.1/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/stock/2.0.1/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', // docs fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' // docs } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { align: 'center', //defer: true, enabled: false, formatter: function () { return this.y === null ? '' : numberFormat(this.y, -1); }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, // docs navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', // docs fontSize: '12px', fontWeight: 'bold' // docs }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '1em' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', // docs shadow: true, //shape: 'calout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; timezoneOffset = ((useUTC && defaultOptions.global.timezoneOffset) || 0) * 60000; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Default base for animation */ opacity: 1, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width); // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad, textStr = wrapper.textStr, cacheKey; // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num.' + textStr.toString().length + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); } //else { // This code block made demo/waterfall fail, related to buildText // Caching all strings reduces rendering time by 4-5%. // TODO: Check how this affects places where bBox is found on the element //cacheKey = textStr + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); //} if (cacheKey) { bBox = renderer.cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it wrapper.bBox = bBox; if (cacheKey) { renderer.cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881) if (inherit && this.element.namespaceURI === SVG_NS) { this.element.removeAttribute('visibility'); return this; } else { return this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); } }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.hide(); } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, element = this.element, zIndex = this.zIndex, otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393). while (parentToClean && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this.element.getAttribute('stroke-width'); } value = value.join(','); this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, // In Chrome/Win < 6 as well as Batik and PhantomJS as of 1.9.7, the stroke attribute can't be set when the stroke- // width is 0. #1369 'stroke-widthSetter': function (value, key, element) { if (value === 0) { value = 0.00001; } this.strokeWidth = value; // read in symbol paths like 'callout' element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.textContent = value; }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, zIndexSetter: function (value, key, element) { element.setAttribute(key, value); this[key] = value; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; SVGElement.prototype.strokeSetter = SVGElement.prototype.fillSetter; // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke- // width is 0. #1369 /*SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.element.setAttribute('stroke', this.stroke); this.element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { this.element.removeAttribute('stroke'); this.hasStroke = false; } };*/ /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, i = childNodes.length, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12) ).h; }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node if (!hasMarkup && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(textStr)); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan), // Safari 6.0.2 - too optimized for its own good (#1539) // TODO: revisit this with future versions of Safari isWebKit && tspan.offsetHeight ); } // Append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = words.length > 1 && textStyles.whiteSpace !== 'nowrap', tooLong, actualWidth, clipHeight = wrapper._clipHeight, rest = [], dy = getLineHeight(), softLineNo = 1, bBox; while (hasWhiteSpace && (words.length || rest.length)) { delete wrapper.bBox; // delete cache bBox = wrapper.getBBox(); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { softLineNo++; if (clipHeight && softLineNo * dy > clipHeight) { words = ['...']; wrapper.attr('title', wrapper.textStr); } else { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } } } }); }); } }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function () { if (curState !== 3) { callback.call(label); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc]; // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. // obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors; x += normalizer; y += normalizer; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var childNodes = element.childNodes, child, i; for (i = 1; i < childNodes.length; i++) { child = childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (child.getAttribute('x') === element.getAttribute('x')) { child.setAttribute('x', value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize) { fontSize = fontSize || this.style.fontSize; fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.textStr && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.attr('fill', NONE).add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: str || '', // alignment is available now x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, visibilitySetter: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ Highcharts.VMLElement = VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; css = extend(css, labelOptions.style); // first call if (!defined(label)) { attr = { align: axis.labelAlign }; if (isNumber(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } if (width && labelOptions.ellipsis) { attr._clipHeight = axis.len / tickPositions.length; } tick.label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(css) .add(axis.labelGroup) : null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? label.getBBox()[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.label.getBBox(), axis = this.axis, horiz = axis.horiz, options = axis.options, labelOptions = options.labels, size = horiz ? bBox.width : bBox.height, leftSide = horiz ? labelOptions.x - size * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] : 0, rightSide = horiz ? size + leftSide : size; return [leftSide, rightSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, isFirst = this.isFirst, isLast = this.isLast, horiz = axis.horiz, pxPos = horiz ? xy.x : xy.y, reversed = axis.reversed, tickPositions = axis.tickPositions, sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], axisLeft, axisRight, neighbour, neighbourEdge, line = this.label.line || 0, labelEdge = axis.labelEdge, justifyLabel = axis.justifyLabels && (isFirst || isLast), justifyToPlot; // Hide it if it now overlaps the neighbour label if (labelEdge[line] === UNDEFINED || pxPos + leftSide > labelEdge[line]) { labelEdge[line] = pxPos + rightSide; } else if (!justifyLabel) { show = false; } if (justifyLabel) { justifyToPlot = axis.justifyToPlot; axisLeft = justifyToPlot ? axis.pos : 0; axisRight = justifyToPlot ? axisLeft + axis.len : axis.chart.chartWidth; // Find the firsth neighbour on the same line do { index += (isFirst ? 1 : -1); neighbour = axis.ticks[tickPositions[index]]; } while (tickPositions[index] && (!neighbour || neighbour.label.line !== line)); neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (pxPos + leftSide < axisLeft) { // Align it to plot left pxPos = axisLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (pxPos + rightSide > axisRight) { // Align it to plot right pxPos = axisRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = pxPos; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b, rotation = labelOptions.rotation; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for rotation (#1764) if (rotation && axis.side === 2) { y -= baseline - baseline * mathCos(rotation * deg2rad); } // Vertically centered if (!defined(labelOptions.y) && !rotation) { // #1951 y += baseline - label.getBBox().height / 2; } // Correct for staggered labels if (staggerLines) { label.line = (index / (step || 1) % staggerLines); y += label.line * (axis.labelOffset / staggerLines); } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { show = tick.handleOverflow(index, xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, halfPointRange = (axis.pointRange || 0) / 2, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs = {}, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); if (color) { attribs.fill = color; } if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; if (label) { plotLine.label = label = label.destroy(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; if (defined(zIndex)) { attribs.zIndex = zIndex; } plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], pick(path[6], path[1])]; ys = [path[2], path[5], pick(path[7], path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function (options) { this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new Highcharts.PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return numberFormat(this.total, -1); }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { x: 0, y: 20 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = []; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // reset dataMin and dataMax in case we're redrawing axis.dataMin = axis.dataMax = null; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (axis.isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, keepTwoTicksOnly, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); // For squished axes, set only two ticks if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial && !this.isLog && !categories && options.startOnTick && options.endOnTick) { keepTwoTicksOnly = true; axis.tickInterval /= 4; // tick extremes closer to the real values } } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { // Too many ticks if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) { error(19, true); } if (isDatetimeAxis) { tickPositions = axis.getTimeTicks( axis.normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } if (keepTwoTicksOnly) { tickPositions.splice(1, tickPositions.length - 2); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (options.startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = mathAbs(axis.max) > 10e12 ? 1 : 0.001; // The lowest possible number to avoid extra padding on columns (#2619, #2846) axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.coll, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false && this.min !== UNDEFINED) { var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (!axis.isXAxis) { if (axis.oldStacks) { stacks = axis.stacks = axis.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options; // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) { newMin = UNDEFINED; } if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // docs // Check for percentage based input values if (percentRegex.test(height)) { height = parseInt(height, 10) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseInt(top, 10) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n, i, autoStaggerLines = 1, maxStaggerLines = pick(labelOptions.maxStaggerLines, 5), sortedPositions, lastRight, overlap, pos, bBox, x, w, lineNo, lineHeightCorrection = side === 2 ? renderer.fontMetrics(labelOptions.style.fontSize).b : 0; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(); } if (hasData || axis.isLinked) { // Set the explicit or automatic label alignment axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation)); // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); // Handle automatic stagger lines if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) { sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions; while (autoStaggerLines < maxStaggerLines) { lastRight = []; overlap = false; for (i = 0; i < sortedPositions.length; i++) { pos = sortedPositions[i]; bBox = ticks[pos].label && ticks[pos].label.getBBox(); w = bBox ? bBox.width : 0; lineNo = i % autoStaggerLines; if (w) { x = axis.translate(pos); // don't handle log if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) { overlap = true; } lastRight[lineNo] = x + w; } } if (overlap) { autoStaggerLines++; } else { break; } } if (autoStaggerLines > 1) { axis.staggerLines = autoStaggerLines; } } each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); titleOffsetOption = axisTitleOptions.offset; } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.axisTitleMargin = pick(titleOffsetOption, labelOffset + titleMargin + (labelOffset && (directionFactor * options.labels[horiz ? 'y' : 'x'] - lineHeightCorrection)) ); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, horiz = axis.horiz, reversed = axis.reversed, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, sortedPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, overflow = options.labels.overflow, justifyLabels = axis.justifyLabels = horiz && overflow !== false, to; // Reset axis.labelEdge.length = 0; axis.justifyToPlot = overflow === 'justify'; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 sortedPositions = tickPositions.slice(); if ((horiz && reversed) || (!horiz && !reversed)) { sortedPositions.reverse(); } if (justifyLabels) { sortedPositions = sortedPositions.slice(1).concat([sortedPositions[0]]); } each(sortedPositions, function (pos, i) { // Reorganize the indices if (justifyLabels) { i = (i === sortedPositions.length - 1) ? 0 : i + 1; } // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i, false, 1); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && axis.min === 0) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { var axis = this, chart = axis.chart, pointer = chart.pointer; // hide tooltip and hover states if (pointer) { pointer.reset(true); } // render the axis axis.render(); // move plot lines and bands each(axis.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(axis.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too. if ((defined(point) || !pick(this.crosshair.snap, true)) === false) { this.hideCrosshair(); return; } var path, options = this.crosshair, animation = options.animation, pos; // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY; /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)); } else { path = this.getPlotLinePath(null, null, null, null, pos); } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { var attribs = { 'stroke-width': options.width || 1, stroke: options.color || '#C0C0C0', zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min - timezoneOffset), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits[SECOND]) { // second minDate.setMilliseconds(0); minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits[MINUTE]) { // minute minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits[HOUR]) { // hour minDate[setHours](interval >= timeUnits[DAY] ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits[DAY]) { // day minDate[setDate](interval >= timeUnits[MONTH] ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits[MONTH]) { // month minDate[setMonth](interval >= timeUnits[YEAR] ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits[YEAR]) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits[WEEK]) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; if (timezoneOffset) { minDate = new Date(minDate.getTime() + timezoneOffset); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), localTimezoneOffset = useUTC ? timezoneOffset : (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits[YEAR]) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits[MONTH]) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits[DAY] ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === localTimezoneOffset; }), function (time) { higherRanks[time] = DAY; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; }; /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) { var units = unitsOption || [[ MILLISECOND, // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ SECOND, [1, 2, 5, 10, 15, 30] ], [ MINUTE, [1, 2, 5, 10, 15, 30] ], [ HOUR, [1, 2, 3, 4, 6, 8, 12] ], [ DAY, [1, 2] ], [ WEEK, [1, 2] ], [ MONTH, [1, 2, 3, 4, 6] ], [ YEAR, null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === YEAR ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; };/** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max)) { // #1670 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden, skipAnchor = tooltip.followPointer || tooltip.len > 1; // get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // move to the intermediate value tooltip.label.attr(now); // run on next tick of the mouse tracker if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) { // never allow two timeouts clearTimeout(this.tooltipTimeout); // set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function () { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft], // The far side is right or bottom preferFarSide = point.ttBelow || (chart.inverted && !point.negative) || (!chart.inverted && point.negative), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = alignedLeft; } else if (roomRight) { ret[dim] = alignedRight; } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), series = items[0].series, s; // build the header s = [tooltip.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = point.series, tooltipOptions = series.tooltipOptions, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), headerFormat = tooltipOptions.headerFormat, closestPointRange = xAxis && xAxis.closestPointRange, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { if (closestPointRange) { for (n in timeUnits) { if (timeUnits[n] >= closestPointRange || // If the point is placed every day at 23:59, we need to show // the minutes as well. This logic only works for time units less than // a day, since all higher time units are dividable by those. #2637. (timeUnits[n] <= timeUnits[DAY] && point.key % timeUnits[n] > 0)) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } xDateFormat = xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 } // Insert the header date format if any if (isDateTime && xDateFormat) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = options.tooltip.followTouchMove; } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, followPointer, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].singularTooltips !== true && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point && point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // Separate tooltip and general mouse events followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (hoverSeries && hoverSeries.tracker && !followPointer) { // #2584, #2830 // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Draw independent crosshairs each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(point, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight)); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; hoverChartIndex = chart.index; // normalize e = this.normalize(e); if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement, relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499 if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && relatedSeries !== series) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = self.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || chart.runChartClick), clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if ((hasZoom || followTouchMove) && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(axis.dataMin), max = axis.toPixels(axis.dataMax), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } } }, onContainerTouchStart: function (e) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } else { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom || this.followTouchMove) { css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.lastLineHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, // docs ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, lastY, allItems = this.allItems; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight - this.padding; this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || 12; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 5 - (symbolHeight / 2), legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = 0; chart.counters = new ChartCounters(); chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (chart.hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); chart.getMargins(); // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Generate stacks for each series and calculate stacks total values */ getStacks: function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: 15 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) : new Renderer(container, chartWidth, chartHeight, optionsChart.style); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, spacing = chart.spacing, axisOffset, legend = chart.legend, margin = chart.margin, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 20), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset = chart.titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(margin[1])) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacing[1] ); } } else if (align === 'left') { if (!defined(margin[3])) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacing[3] ); } } else if (verticalAlign === 'top') { if (!defined(margin[0])) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacing[0] ); } } else if (verticalAlign === 'bottom') { if (!defined(margin[2])) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacing[2] ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(margin[3])) { chart.plotLeft += axisOffset[3]; } if (!defined(margin[0])) { chart.plotTop += axisOffset[0]; } if (!defined(margin[2])) { chart.marginBottom += axisOffset[2]; } if (!defined(margin[1])) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } // Resize the container with the global animation applied if enabled (#2503) (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, spacing = chart.spacing, margin = chart.margin; chart.plotTop = pick(margin[0], spacing[0]); chart.marginRight = pick(margin[1], spacing[1]); chart.marginBottom = pick(margin[2], spacing[2]); chart.plotLeft = pick(margin[3], spacing[3]); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }) ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); if (serie.setTooltipPoints) { serie.setTooltipPoints(); } serie.render(); }); }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; var labels = options.labels, credits = options.credits, creditsHref; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); chart.getStacks(); // render stacks // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; chart.credits = renderer.text( credits.text, 0, 0 ) .on('click', function () { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } // Set flag chart.hasRendered = true; }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), isPercent; return map(positions, function (length, i) { isPercent = /%$/.test(length); handleSlicingRoom = i < 2 || (i === 2 && isPercent); return (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length) + (handleSlicingRoom ? slicingRoom : 0); }); } }; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); } };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, /** * Get the series' color */ getColor: function () { var options = this.options, userOptions = this.userOptions, defaultColors = this.chart.options.colors, counters = this.chart.counters, color, colorIndex; color = options.color || defaultPlotOptions[this.type].color; if (!color && !options.colorByPoint) { if (defined(userOptions._colorIndex)) { // after Series.update() colorIndex = userOptions._colorIndex; } else { userOptions._colorIndex = counters.color; colorIndex = counters.color++; } color = defaultColors[colorIndex]; } this.color = color; counters.wrapColor(defaultColors.length); }, /** * Get the series' symbol */ getSymbol: function () { var series = this, userOptions = series.userOptions, seriesMarkerOption = series.options.marker, chart = series.chart, defaultSymbols = chart.options.symbols, counters = chart.counters, symbolIndex; series.symbol = seriesMarkerOption.symbol; if (!series.symbol) { if (defined(userOptions._symbolIndex)) { // after Series.update() symbolIndex = userOptions._symbolIndex; } else { userOptions._symbolIndex = counters.symbol; symbolIndex = counters.symbol++; } series.symbol = defaultSymbols[symbolIndex]; } // don't substract radius in image symbols (#604) if (/^url/.test(series.symbol)) { seriesMarkerOption.radius = 0; } counters.wrapSymbol(defaultSymbols.length); }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, tooltipPoints = series.tooltipPoints, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData) { each(data, function (point, i) { oldData[i].update(point, false); }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && pt.name) { xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; //series.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } if (tooltipPoints) { // #2594 tooltipPoints.length = 0; } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, activePointCount = 0, isCartesian = series.isCartesian, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { min = xAxis.min; max = xAxis.max; // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; activePointCount = processedXData.length; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (!cropped && processedXData[i] > min && processedXData[i] < max) { activePointCount++; } if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; series.activePointCount = activePointCount; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, dataMin, dataMax, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = pick(dataMin, arrayMin(activeYData)); this.dataMax = pick(dataMax, arrayMax(activeYData)); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; stackValues = pointStack.points[series.index + ',' + i]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === 0) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ? //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 yAxis.translate(yValue, 0, 1, 0, 1) : UNDEFINED; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = series.clipBox || chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = ['_sharedClip', animation.duration, animation.easing, clipBox.height].join(','); // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group, clipBox = this.clipBox; if (group && this.options.clip !== false) { if (!sharedClipKey || !clipBox) { group.clip(clipBox ? chart.renderer.clipRect(clipBox) : chart.clipRect); } this.markerGroup.clip(); // no clip } fireEvent(this, 'afterAnimate'); // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { if (!clipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, enabled, isInside, markerGroup = series.markerGroup, globallyEnabled = pick( seriesMarkerOptions.enabled, series.activePointCount < (0.5 * series.xAxis.len / seriesMarkerOptions.radius) ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858 // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover.color) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: NONE, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor || options.negativeFillColor, translatedThreshold, posAttr, negAttr, graph = this.graph, area = this.area, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), yAxis = this.yAxis, above, below; if (negativeColor && (graph || area)) { translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true)); if (translatedThreshold < 0) { chartSizeMax -= translatedThreshold; // #2534 } above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax }; if (chart.inverted) { above.height = below.y = chart.plotWidth - translatedThreshold; if (renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } } if (yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.negClip = negClip = renderer.clipRect(negAttr); if (graph && this.graphNeg) { graph.clip(posClip); this.graphNeg.clip(negClip); } if (area) { area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.clipNeg(); } // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { series.afterAnimate(); } } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); if (series.setTooltipPoints) { series.setTooltipPoints(true); } series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var series = this.series, reversedStacks = pick(this.options.reversedStacks, true), i = series.length; if (!this.isXAxis) { this.usePercentage = false; while (i--) { series[reversedStacks ? i : series.length - i - 1].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.setStackedPoints = function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, isNegative, stack, other, key, pointKey, i, x, y; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; pointKey = series.index + ',' + i; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < threshold; key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; stack.points[pointKey] = [stack.cum || 0]; // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = (stack.cum || 0) + (y || 0); stack.points[pointKey].push(stack.cum); stackedYData[i] = stack.cum; } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }; /** * Iterate over all stacks and compute the absolute values to percent */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[series.index + ',' + i]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv; var loadingOptions = options.loading; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '', left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation) { var point = this, series = point.series, graphic = point.graphic, i, data = series.data, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function () { point.applyOptions(options); // update visuals if (isObject(options)) { series.getAttribs(); if (graphic) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || '']); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } } // record changes in the parallel arrays i = inArray(point, data); series.updateParallelArrays(point, i); seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.legend.destroyItem(point); } if (redraw) { chart.redraw(animation); } }); }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, points = series.points, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point, 'splice', i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, x, i; setAnimation(animation, chart); // Make graph animate sideways if (shift) { each([graph, area, series.graphNeg, series.areaNeg], function (shape) { if (shape) { shape.shift = currentShift + 1; } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, n; // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); for (n in proto) { // Overwrite series-type specific methods (#2270) if (proto.hasOwnProperty(n)) { this[n] = UNDEFINED; } } extend(this, seriesTypes[newOptions.type || oldType].prototype); this.init(chart, newOptions); if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = UNDEFINED; // #1611, #2887 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, val, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(+x); } } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836 return; // The point exists, push it to the segment } else if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { plotX = xAxis.translate(x); val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991 plotY = yAxis.toPixels(val, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length, translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181 yBottom; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { yBottom = pick(segment[i].yBottom, translatedThreshold); // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, yBottom); } areaSegmentPath.push(segment[i].plotX, yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment, translatedThreshold); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment, translatedThreshold) { path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, negativeColor = options.negativeColor, negativeFillColor = options.negativeFillColor, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color if (negativeColor || negativeFillColor) { props.push(['areaNeg', negativeColor, negativeFillColor]); } each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.area = AreaSeries; /** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.activePointCount > 0.5 * series.xAxis.len ? 0 : 1 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1; if (chart.renderer.isVML && chart.inverted) { yCrisp += 1; } Series.prototype.translate.apply(series); // record the new values each(series.points, function (point) { var yBottom = pick(point.yBottom, translatedThreshold), plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), right, bottom, fromTop, fromLeft, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485) } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216) point.tooltipPos = chart.inverted ? [yAxis.len - plotY, series.xAxis.len - barX - barW / 2] : [barX + barW / 2, plotY]; // Round off to obtain crisp edges fromLeft = mathAbs(barX) < 0.5; right = mathRound(barX + barW) + xCrisp; barX = mathRound(barX) + xCrisp; barW = right - barX; fromTop = mathAbs(barY) < 0.5; bottom = mathRound(barY + barH) + yCrisp; barY = mathRound(barY) + yCrisp; barH = bottom - barY; // Top and left edges are exceptions if (fromLeft) { barX += 1; barW -= 1; } if (fromTop) { barY -= 1; barH += 1; } // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: barW, height: barH }; }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr, borderAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(pointAttr) .attr(borderAttr) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, tooltip: { headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', // docs pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup'], takeOrdinalPosition: false, // #2342 singularTooltips: true, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { return this.point.name; } // softConnector: true, //y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; // Disallow negative values (#1530) if (point.y < 0) { point.y = null; } //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart; // if called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, singularTooltips: true, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw, animation, updatePoints) { Series.prototype.setData.call(this, data, false, animation, updatePoints); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(animation); } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { var i, total = 0, points, len, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; Series.prototype.generatePoints.call(this); // Populate local vars points = this.points; len = points.length; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; point.percentage = total > 0 ? (point.y / total) * 100 : 0; point.total = total; } }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90), circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' //zIndex: 1 // #2722 (reversed) }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility (#2430) if (point.visible !== undefined) { point.setVisible(point.visible); } }); }, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', HIDDEN, options.zIndex || 6 ); if (!series.hasRendered && pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: 0 }); addEvent(series, 'afterAnimate', function () { series.dataLabelsGroup.show()[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(extend(options.style, cursor && { cursor: cursor })) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text alignAttr = { align: options.align, x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } } } // Show or hide based on the final aligned position if (!visible) { dataLabel.attr({ y: -999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified; // Off left off = alignAttr.x; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 halves[point.half].push(point); } }); // assume equal label heights i = 0; while (!labelHeight && data[i]) { // #1569 labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968 i++; } /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, length = points.length, slotIndex; // Sort by angle series.sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // build the slots for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) { slots.push(pos); // visualize the slot /* var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver' }) .add(); chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4) .attr({ fill: 'silver' }).add(); } */ } slotsLength = slots.length; // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = naturalY; } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; if (chart.hoverSeries !== series) { series.onMouseOver(); } while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange; if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887 this.firePointEvent('mouseOut'); this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(series.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + 1; } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Memorize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, xExtremes = xAxis && xAxis.getExtremes(), axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, pointX, nextPoint, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false || series.singularTooltips) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Polar needs additional shaping if (series.orderTooltipPoints) { series.orderTooltipPoints(points); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; pointX = point.x; if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149 nextPoint = points[i + 1]; // Set this range's low to the last range's high plus one low = high === UNDEFINED ? 0 : high + 1; // Now find the new high high = points[i + 1] ? mathMin(mathMax(0, mathFloor( // #2070 (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2 )), axisLength) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } } series.tooltipPoints = tooltipPoints; }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph });/* **************************************************************************** * Start ordinal axis logic * *****************************************************************************/ wrap(Series.prototype, 'init', function (proceed) { var series = this, xAxis; // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); xAxis = series.xAxis; // Destroy the extended ordinal index on updated data if (xAxis && xAxis.options.ordinal) { addEvent(series, 'updatedData', function () { delete xAxis.ordinalIndex; }); } }); /** * In an ordinal axis, there might be areas with dense consentrations of points, then large * gaps between some. Creating equally distributed ticks over this entire range * may lead to a huge number of ticks that will later be removed. So instead, break the * positions up in segments, find the tick positions for each segment then concatenize them. * This method is used from both data grouping logic and X axis tick position logic. */ wrap(Axis.prototype, 'getTimeTicks', function (proceed, normalizedInterval, min, max, startOfWeek, positions, closestDistance, findHigherRanks) { var start = 0, end = 0, segmentPositions, higherRanks = {}, hasCrossedHigherRank, info, posLength, outsideMax, groupPositions = [], lastGroupPosition = -Number.MAX_VALUE, tickPixelIntervalOption = this.options.tickPixelInterval; // The positions are not always defined, for example for ordinal positions when data // has regular interval (#1557, #2090) if (!this.options.ordinal || !positions || positions.length < 3 || min === UNDEFINED) { return proceed.call(this, normalizedInterval, min, max, startOfWeek); } // Analyze the positions array to split it into segments on gaps larger than 5 times // the closest distance. The closest distance is already found at this point, so // we reuse that instead of computing it again. posLength = positions.length; for (; end < posLength; end++) { outsideMax = end && positions[end - 1] > max; if (positions[end] < min) { // Set the last position before min start = end; } if (end === posLength - 1 || positions[end + 1] - positions[end] > closestDistance * 5 || outsideMax) { // For each segment, calculate the tick positions from the getTimeTicks utility // function. The interval will be the same regardless of how long the segment is. if (positions[end] > lastGroupPosition) { // #1475 segmentPositions = proceed.call(this, normalizedInterval, positions[start], positions[end], startOfWeek); // Prevent duplicate groups, for example for multiple segments within one larger time frame (#1475) while (segmentPositions.length && segmentPositions[0] <= lastGroupPosition) { segmentPositions.shift(); } if (segmentPositions.length) { lastGroupPosition = segmentPositions[segmentPositions.length - 1]; } groupPositions = groupPositions.concat(segmentPositions); } // Set start of next segment start = end + 1; } if (outsideMax) { break; } } // Get the grouping info from the last of the segments. The info is the same for // all segments. info = segmentPositions.info; // Optionally identify ticks with higher rank, for example when the ticks // have crossed midnight. if (findHigherRanks && info.unitRange <= timeUnits[HOUR]) { end = groupPositions.length - 1; // Compare points two by two for (start = 1; start < end; start++) { if (new Date(groupPositions[start] - timezoneOffset)[getDate]() !== new Date(groupPositions[start - 1] - timezoneOffset)[getDate]()) { higherRanks[groupPositions[start]] = DAY; hasCrossedHigherRank = true; } } // If the complete array has crossed midnight, we want to mark the first // positions also as higher rank if (hasCrossedHigherRank) { higherRanks[groupPositions[0]] = DAY; } info.higherRanks = higherRanks; } // Save the info groupPositions.info = info; // Don't show ticks within a gap in the ordinal axis, where the space between // two points is greater than a portion of the tick pixel interval if (findHigherRanks && defined(tickPixelIntervalOption)) { // check for squashed ticks var length = groupPositions.length, i = length, itemToRemove, translated, translatedArr = [], lastTranslated, medianDistance, distance, distances = []; // Find median pixel distance in order to keep a reasonably even distance between // ticks (#748) while (i--) { translated = this.translate(groupPositions[i]); if (lastTranslated) { distances[i] = lastTranslated - translated; } translatedArr[i] = lastTranslated = translated; } distances.sort(); medianDistance = distances[mathFloor(distances.length / 2)]; if (medianDistance < tickPixelIntervalOption * 0.6) { medianDistance = null; } // Now loop over again and remove ticks where needed i = groupPositions[length - 1] > max ? length - 1 : length; // #817 lastTranslated = undefined; while (i--) { translated = translatedArr[i]; distance = lastTranslated - translated; // Remove ticks that are closer than 0.6 times the pixel interval from the one to the right, // but not if it is close to the median distance (#748). if (lastTranslated && distance < tickPixelIntervalOption * 0.8 && (medianDistance === null || distance < medianDistance * 0.8)) { // Is this a higher ranked position with a normal position to the right? if (higherRanks[groupPositions[i]] && !higherRanks[groupPositions[i + 1]]) { // Yes: remove the lower ranked neighbour to the right itemToRemove = i + 1; lastTranslated = translated; // #709 } else { // No: remove this one itemToRemove = i; } groupPositions.splice(itemToRemove, 1); } else { lastTranslated = translated; } } } return groupPositions; }); // Extend the Axis prototype extend(Axis.prototype, { /** * Calculate the ordinal positions before tick positions are calculated. */ beforeSetTickPositions: function () { var axis = this, len, ordinalPositions = [], useOrdinal = false, dist, extremes = axis.getExtremes(), min = extremes.min, max = extremes.max, minIndex, maxIndex, slope, i; // apply the ordinal logic if (axis.options.ordinal) { each(axis.series, function (series, i) { if (series.visible !== false && series.takeOrdinalPosition !== false) { // concatenate the processed X data into the existing positions, or the empty array ordinalPositions = ordinalPositions.concat(series.processedXData); len = ordinalPositions.length; // remove duplicates (#1588) ordinalPositions.sort(function (a, b) { return a - b; // without a custom function it is sorted as strings }); if (len) { i = len - 1; while (i--) { if (ordinalPositions[i] === ordinalPositions[i + 1]) { ordinalPositions.splice(i, 1); } } } } }); // cache the length len = ordinalPositions.length; // Check if we really need the overhead of mapping axis data against the ordinal positions. // If the series consist of evenly spaced data any way, we don't need any ordinal logic. if (len > 2) { // two points have equal distance by default dist = ordinalPositions[1] - ordinalPositions[0]; i = len - 1; while (i-- && !useOrdinal) { if (ordinalPositions[i + 1] - ordinalPositions[i] !== dist) { useOrdinal = true; } } // When zooming in on a week, prevent axis padding for weekends even though the data within // the week is evenly spaced. if (!axis.options.keepOrdinalPadding && (ordinalPositions[0] - min > dist || max - ordinalPositions[ordinalPositions.length - 1] > dist)) { useOrdinal = true; } } // Record the slope and offset to compute the linear values from the array index. // Since the ordinal positions may exceed the current range, get the start and // end positions within it (#719, #665b) if (useOrdinal) { // Register axis.ordinalPositions = ordinalPositions; // This relies on the ordinalPositions being set. Use mathMax and mathMin to prevent // padding on either sides of the data. minIndex = axis.val2lin(mathMax(min, ordinalPositions[0]), true); maxIndex = axis.val2lin(mathMin(max, ordinalPositions[ordinalPositions.length - 1]), true); // Set the slope and offset of the values compared to the indices in the ordinal positions axis.ordinalSlope = slope = (max - min) / (maxIndex - minIndex); axis.ordinalOffset = min - (minIndex * slope); } else { axis.ordinalPositions = axis.ordinalSlope = axis.ordinalOffset = UNDEFINED; } } axis.groupIntervalFactor = null; // reset for next run }, /** * Translate from a linear axis value to the corresponding ordinal axis position. If there * are no gaps in the ordinal axis this will be the same. The translated value is the value * that the point would have if the axis were linear, using the same min and max. * * @param Number val The axis value * @param Boolean toIndex Whether to return the index in the ordinalPositions or the new value */ val2lin: function (val, toIndex) { var axis = this, ordinalPositions = axis.ordinalPositions; if (!ordinalPositions) { return val; } else { var ordinalLength = ordinalPositions.length, i, distance, ordinalIndex; // first look for an exact match in the ordinalpositions array i = ordinalLength; while (i--) { if (ordinalPositions[i] === val) { ordinalIndex = i; break; } } // if that failed, find the intermediate position between the two nearest values i = ordinalLength - 1; while (i--) { if (val > ordinalPositions[i] || i === 0) { // interpolate distance = (val - ordinalPositions[i]) / (ordinalPositions[i + 1] - ordinalPositions[i]); // something between 0 and 1 ordinalIndex = i + distance; break; } } return toIndex ? ordinalIndex : axis.ordinalSlope * (ordinalIndex || 0) + axis.ordinalOffset; } }, /** * Translate from linear (internal) to axis value * * @param Number val The linear abstracted value * @param Boolean fromIndex Translate from an index in the ordinal positions rather than a value */ lin2val: function (val, fromIndex) { var axis = this, ordinalPositions = axis.ordinalPositions; if (!ordinalPositions) { // the visible range contains only equally spaced values return val; } else { var ordinalSlope = axis.ordinalSlope, ordinalOffset = axis.ordinalOffset, i = ordinalPositions.length - 1, linearEquivalentLeft, linearEquivalentRight, distance; // Handle the case where we translate from the index directly, used only // when panning an ordinal axis if (fromIndex) { if (val < 0) { // out of range, in effect panning to the left val = ordinalPositions[0]; } else if (val > i) { // out of range, panning to the right val = ordinalPositions[i]; } else { // split it up i = mathFloor(val); distance = val - i; // the decimal } // Loop down along the ordinal positions. When the linear equivalent of i matches // an ordinal position, interpolate between the left and right values. } else { while (i--) { linearEquivalentLeft = (ordinalSlope * i) + ordinalOffset; if (val >= linearEquivalentLeft) { linearEquivalentRight = (ordinalSlope * (i + 1)) + ordinalOffset; distance = (val - linearEquivalentLeft) / (linearEquivalentRight - linearEquivalentLeft); // something between 0 and 1 break; } } } // If the index is within the range of the ordinal positions, return the associated // or interpolated value. If not, just return the value return distance !== UNDEFINED && ordinalPositions[i] !== UNDEFINED ? ordinalPositions[i] + (distance ? distance * (ordinalPositions[i + 1] - ordinalPositions[i]) : 0) : val; } }, /** * Get the ordinal positions for the entire data set. This is necessary in chart panning * because we need to find out what points or data groups are available outside the * visible range. When a panning operation starts, if an index for the given grouping * does not exists, it is created and cached. This index is deleted on updated data, so * it will be regenerated the next time a panning operation starts. */ getExtendedPositions: function () { var axis = this, chart = axis.chart, grouping = axis.series[0].currentDataGrouping, ordinalIndex = axis.ordinalIndex, key = grouping ? grouping.count + grouping.unitName : 'raw', extremes = axis.getExtremes(), fakeAxis, fakeSeries; // If this is the first time, or the ordinal index is deleted by updatedData, // create it. if (!ordinalIndex) { ordinalIndex = axis.ordinalIndex = {}; } if (!ordinalIndex[key]) { // Create a fake axis object where the extended ordinal positions are emulated fakeAxis = { series: [], getExtremes: function () { return { min: extremes.dataMin, max: extremes.dataMax }; }, options: { ordinal: true }, val2lin: Axis.prototype.val2lin // #2590 }; // Add the fake series to hold the full data, then apply processData to it each(axis.series, function (series) { fakeSeries = { xAxis: fakeAxis, xData: series.xData, chart: chart, destroyGroupedData: noop }; fakeSeries.options = { dataGrouping : grouping ? { enabled: true, forced: true, approximation: 'open', // doesn't matter which, use the fastest units: [[grouping.unitName, [grouping.count]]] } : { enabled: false } }; series.processData.apply(fakeSeries); fakeAxis.series.push(fakeSeries); }); // Run beforeSetTickPositions to compute the ordinalPositions axis.beforeSetTickPositions.apply(fakeAxis); // Cache it ordinalIndex[key] = fakeAxis.ordinalPositions; } return ordinalIndex[key]; }, /** * Find the factor to estimate how wide the plot area would have been if ordinal * gaps were included. This value is used to compute an imagined plot width in order * to establish the data grouping interval. * * A real world case is the intraday-candlestick * example. Without this logic, it would show the correct data grouping when viewing * a range within each day, but once moving the range to include the gap between two * days, the interval would include the cut-away night hours and the data grouping * would be wrong. So the below method tries to compensate by identifying the most * common point interval, in this case days. * * An opposite case is presented in issue #718. We have a long array of daily data, * then one point is appended one hour after the last point. We expect the data grouping * not to change. * * In the future, if we find cases where this estimation doesn't work optimally, we * might need to add a second pass to the data grouping logic, where we do another run * with a greater interval if the number of data groups is more than a certain fraction * of the desired group count. */ getGroupIntervalFactor: function (xMin, xMax, series) { var i = 0, processedXData = series.processedXData, len = processedXData.length, distances = [], median, groupIntervalFactor = this.groupIntervalFactor; // Only do this computation for the first series, let the other inherit it (#2416) if (!groupIntervalFactor) { // Register all the distances in an array for (; i < len - 1; i++) { distances[i] = processedXData[i + 1] - processedXData[i]; } // Sort them and find the median distances.sort(function (a, b) { return a - b; }); median = distances[mathFloor(len / 2)]; // Compensate for series that don't extend through the entire axis extent. #1675. xMin = mathMax(xMin, processedXData[0]); xMax = mathMin(xMax, processedXData[len - 1]); this.groupIntervalFactor = groupIntervalFactor = (len * median) / (xMax - xMin); } // Return the factor needed for data grouping return groupIntervalFactor; }, /** * Make the tick intervals closer because the ordinal gaps make the ticks spread out or cluster */ postProcessTickInterval: function (tickInterval) { // TODO: http://jsfiddle.net/highcharts/FQm4E/1/ // This is a case where this algorithm doesn't work optimally. In this case, the // tick labels are spread out per week, but all the gaps reside within weeks. So // we have a situation where the labels are courser than the ordinal gaps, and // thus the tick interval should not be altered var ordinalSlope = this.ordinalSlope; return ordinalSlope ? tickInterval / (ordinalSlope / this.closestPointRange) : tickInterval; } }); // Extending the Chart.pan method for ordinal axes wrap(Chart.prototype, 'pan', function (proceed, e) { var chart = this, xAxis = chart.xAxis[0], chartX = e.chartX, runBase = false; if (xAxis.options.ordinal && xAxis.series.length) { var mouseDownX = chart.mouseDownX, extremes = xAxis.getExtremes(), dataMax = extremes.dataMax, min = extremes.min, max = extremes.max, trimmedRange, hoverPoints = chart.hoverPoints, closestPointRange = xAxis.closestPointRange, pointPixelWidth = xAxis.translationSlope * (xAxis.ordinalSlope || closestPointRange), movedUnits = (mouseDownX - chartX) / pointPixelWidth, // how many ordinal units did we move? extendedAxis = { ordinalPositions: xAxis.getExtendedPositions() }, // get index of all the chart's points ordinalPositions, searchAxisLeft, lin2val = xAxis.lin2val, val2lin = xAxis.val2lin, searchAxisRight; if (!extendedAxis.ordinalPositions) { // we have an ordinal axis, but the data is equally spaced runBase = true; } else if (mathAbs(movedUnits) > 1) { // Remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (movedUnits < 0) { searchAxisLeft = extendedAxis; searchAxisRight = xAxis.ordinalPositions ? xAxis : extendedAxis; } else { searchAxisLeft = xAxis.ordinalPositions ? xAxis : extendedAxis; searchAxisRight = extendedAxis; } // In grouped data series, the last ordinal position represents the grouped data, which is // to the left of the real data max. If we don't compensate for this, we will be allowed // to pan grouped data series passed the right of the plot area. ordinalPositions = searchAxisRight.ordinalPositions; if (dataMax > ordinalPositions[ordinalPositions.length - 1]) { ordinalPositions.push(dataMax); } // Get the new min and max values by getting the ordinal index for the current extreme, // then add the moved units and translate back to values. This happens on the // extended ordinal positions if the new position is out of range, else it happens // on the current x axis which is smaller and faster. chart.fixedRange = max - min; trimmedRange = xAxis.toFixedRange(null, null, lin2val.apply(searchAxisLeft, [ val2lin.apply(searchAxisLeft, [min, true]) + movedUnits, // the new index true // translate from index ]), lin2val.apply(searchAxisRight, [ val2lin.apply(searchAxisRight, [max, true]) + movedUnits, // the new index true // translate from index ]) ); // Apply it if it is within the available data range if (trimmedRange.min >= mathMin(extremes.dataMin, min) && trimmedRange.max <= mathMax(dataMax, max)) { xAxis.setExtremes(trimmedRange.min, trimmedRange.max, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); } } else { runBase = true; } // revert to the linear chart.pan version if (runBase) { // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } }); /** * Extend getSegments by identifying gaps in the ordinal data so that we can draw a gap in the * line or area */ wrap(Series.prototype, 'getSegments', function (proceed) { var series = this, segments, gapSize = series.options.gapSize, xAxis = series.xAxis; // call base method proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (gapSize) { // properties segments = series.segments; // extension for ordinal breaks each(segments, function (segment, no) { var i = segment.length - 1; while (i--) { if (segment[i + 1].x - segment[i].x > xAxis.closestPointRange * gapSize) { segments.splice( // insert after this one no + 1, 0, segment.splice(i + 1, segment.length - i) ); } } }); } }); /* **************************************************************************** * End ordinal axis logic * *****************************************************************************/ /* **************************************************************************** * Start data grouping module * ******************************************************************************/ /*jslint white:true */ var DATA_GROUPING = 'dataGrouping', seriesProto = Series.prototype, tooltipProto = Tooltip.prototype, baseProcessData = seriesProto.processData, baseGeneratePoints = seriesProto.generatePoints, baseDestroy = seriesProto.destroy, baseTooltipHeaderFormatter = tooltipProto.tooltipHeaderFormatter, NUMBER = 'number', commonOptions = { approximation: 'average', // average, open, high, low, close, sum //enabled: null, // (true for stock charts, false for basic), //forced: undefined, groupPixelWidth: 2, // the first one is the point or start value, the second is the start value if we're dealing with range, // the third one is the end value if dealing with a range dateTimeLabelFormats: hash( MILLISECOND, ['%A, %b %e, %H:%M:%S.%L', '%A, %b %e, %H:%M:%S.%L', '-%H:%M:%S.%L'], SECOND, ['%A, %b %e, %H:%M:%S', '%A, %b %e, %H:%M:%S', '-%H:%M:%S'], MINUTE, ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], HOUR, ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], DAY, ['%A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], WEEK, ['Week from %A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], MONTH, ['%B %Y', '%B', '-%B %Y'], YEAR, ['%Y', '%Y', '-%Y'] ) // smoothed = false, // enable this for navigator series only }, specificOptions = { // extends common options line: {}, spline: {}, area: {}, areaspline: {}, column: { approximation: 'sum', groupPixelWidth: 10 }, arearange: { approximation: 'range' }, areasplinerange: { approximation: 'range' }, columnrange: { approximation: 'range', groupPixelWidth: 10 }, candlestick: { approximation: 'ohlc', groupPixelWidth: 10 }, ohlc: { approximation: 'ohlc', groupPixelWidth: 5 } }, // units are defined in a separate array to allow complete overriding in case of a user option defaultDataGroupingUnits = [[ MILLISECOND, // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ SECOND, [1, 2, 5, 10, 15, 30] ], [ MINUTE, [1, 2, 5, 10, 15, 30] ], [ HOUR, [1, 2, 3, 4, 6, 8, 12] ], [ DAY, [1] ], [ WEEK, [1] ], [ MONTH, [1, 3, 6] ], [ YEAR, null ] ], /** * Define the available approximation types. The data grouping approximations takes an array * or numbers as the first parameter. In case of ohlc, four arrays are sent in as four parameters. * Each array consists only of numbers. In case null values belong to the group, the property * .hasNulls will be set to true on the array. */ approximations = { sum: function (arr) { var len = arr.length, ret; // 1. it consists of nulls exclusively if (!len && arr.hasNulls) { ret = null; // 2. it has a length and real values } else if (len) { ret = 0; while (len--) { ret += arr[len]; } } // 3. it has zero length, so just return undefined // => doNothing() return ret; }, average: function (arr) { var len = arr.length, ret = approximations.sum(arr); // If we have a number, return it divided by the length. If not, return // null or undefined based on what the sum method finds. if (typeof ret === NUMBER && len) { ret = ret / len; } return ret; }, open: function (arr) { return arr.length ? arr[0] : (arr.hasNulls ? null : UNDEFINED); }, high: function (arr) { return arr.length ? arrayMax(arr) : (arr.hasNulls ? null : UNDEFINED); }, low: function (arr) { return arr.length ? arrayMin(arr) : (arr.hasNulls ? null : UNDEFINED); }, close: function (arr) { return arr.length ? arr[arr.length - 1] : (arr.hasNulls ? null : UNDEFINED); }, // ohlc and range are special cases where a multidimensional array is input and an array is output ohlc: function (open, high, low, close) { open = approximations.open(open); high = approximations.high(high); low = approximations.low(low); close = approximations.close(close); if (typeof open === NUMBER || typeof high === NUMBER || typeof low === NUMBER || typeof close === NUMBER) { return [open, high, low, close]; } // else, return is undefined }, range: function (low, high) { low = approximations.low(low); high = approximations.high(high); if (typeof low === NUMBER || typeof high === NUMBER) { return [low, high]; } // else, return is undefined } }; /*jslint white:false */ /** * Takes parallel arrays of x and y data and groups the data into intervals defined by groupPositions, a collection * of starting x values for each group. */ seriesProto.groupData = function (xData, yData, groupPositions, approximation) { var series = this, data = series.data, dataOptions = series.options.data, groupedXData = [], groupedYData = [], dataLength = xData.length, pointX, pointY, groupedY, handleYData = !!yData, // when grouping the fake extended axis for panning, we don't need to consider y values = [[], [], [], []], approximationFn = typeof approximation === 'function' ? approximation : approximations[approximation], pointArrayMap = series.pointArrayMap, pointArrayMapLength = pointArrayMap && pointArrayMap.length, i; // Start with the first point within the X axis range (#2696) for (i = 0; i <= dataLength; i++) { if (xData[i] >= groupPositions[0]) { break; } } for (; i <= dataLength; i++) { // when a new group is entered, summarize and initiate the previous group while ((groupPositions[1] !== UNDEFINED && xData[i] >= groupPositions[1]) || i === dataLength) { // get the last group // get group x and y pointX = groupPositions.shift(); groupedY = approximationFn.apply(0, values); // push the grouped data if (groupedY !== UNDEFINED) { groupedXData.push(pointX); groupedYData.push(groupedY); } // reset the aggregate arrays values[0] = []; values[1] = []; values[2] = []; values[3] = []; // don't loop beyond the last group if (i === dataLength) { break; } } // break out if (i === dataLength) { break; } // for each raw data point, push it to an array that contains all values for this specific group if (pointArrayMap) { var index = series.cropStart + i, point = (data && data[index]) || series.pointClass.prototype.applyOptions.apply({ series: series }, [dataOptions[index]]), j, val; for (j = 0; j < pointArrayMapLength; j++) { val = point[pointArrayMap[j]]; if (typeof val === NUMBER) { values[j].push(val); } else if (val === null) { values[j].hasNulls = true; } } } else { pointY = handleYData ? yData[i] : null; if (typeof pointY === NUMBER) { values[0].push(pointY); } else if (pointY === null) { values[0].hasNulls = true; } } } return [groupedXData, groupedYData]; }; /** * Extend the basic processData method, that crops the data to the current zoom * range, with data grouping logic. */ seriesProto.processData = function () { var series = this, chart = series.chart, options = series.options, dataGroupingOptions = options[DATA_GROUPING], groupingEnabled = dataGroupingOptions && pick(dataGroupingOptions.enabled, chart.options._stock), hasGroupedData; // run base method series.forceCrop = groupingEnabled; // #334 series.groupPixelWidth = null; // #2110 series.hasProcessed = true; // #2692 // skip if processData returns false or if grouping is disabled (in that order) if (baseProcessData.apply(series, arguments) === false || !groupingEnabled) { return; } else { series.destroyGroupedData(); } var i, processedXData = series.processedXData, processedYData = series.processedYData, plotSizeX = chart.plotSizeX, xAxis = series.xAxis, ordinal = xAxis.options.ordinal, groupPixelWidth = series.groupPixelWidth = xAxis.getGroupPixelWidth && xAxis.getGroupPixelWidth(), nonGroupedPointRange = series.pointRange; // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (groupPixelWidth) { hasGroupedData = true; series.points = null; // force recreation of point instances in series.translate var extremes = xAxis.getExtremes(), xMin = extremes.min, xMax = extremes.max, groupIntervalFactor = (ordinal && xAxis.getGroupIntervalFactor(xMin, xMax, series)) || 1, interval = (groupPixelWidth * (xMax - xMin) / plotSizeX) * groupIntervalFactor, groupPositions = xAxis.getTimeTicks( xAxis.normalizeTimeTickInterval(interval, dataGroupingOptions.units || defaultDataGroupingUnits), xMin, xMax, null, processedXData, series.closestPointRange ), groupedXandY = seriesProto.groupData.apply(series, [processedXData, processedYData, groupPositions, dataGroupingOptions.approximation]), groupedXData = groupedXandY[0], groupedYData = groupedXandY[1]; // prevent the smoothed data to spill out left and right, and make // sure data is not shifted to the left if (dataGroupingOptions.smoothed) { i = groupedXData.length - 1; groupedXData[i] = xMax; while (i-- && i > 0) { groupedXData[i] += interval / 2; } groupedXData[0] = xMin; } // record what data grouping values were used series.currentDataGrouping = groupPositions.info; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = groupPositions.info.totalRange; } series.closestPointRange = groupPositions.info.totalRange; // Make sure the X axis extends to show the first group (#2533) if (defined(groupedXData[0]) && groupedXData[0] < xAxis.dataMin) { xAxis.dataMin = groupedXData[0]; } // set series props series.processedXData = groupedXData; series.processedYData = groupedYData; } else { series.currentDataGrouping = null; series.pointRange = nonGroupedPointRange; } series.hasGroupedData = hasGroupedData; }; /** * Destroy the grouped data points. #622, #740 */ seriesProto.destroyGroupedData = function () { var groupedData = this.groupedData; // clear previous groups each(groupedData || [], function (point, i) { if (point) { groupedData[i] = point.destroy ? point.destroy() : null; } }); this.groupedData = null; }; /** * Override the generatePoints method by adding a reference to grouped data */ seriesProto.generatePoints = function () { baseGeneratePoints.apply(this); // record grouped data in order to let it be destroyed the next time processData runs this.destroyGroupedData(); // #622 this.groupedData = this.hasGroupedData ? this.points : null; }; /** * Extend the original method, make the tooltip's header reflect the grouped range */ tooltipProto.tooltipHeaderFormatter = function (point) { var tooltip = this, series = point.series, options = series.options, tooltipOptions = series.tooltipOptions, dataGroupingOptions = options.dataGrouping, xDateFormat = tooltipOptions.xDateFormat, xDateFormatEnd, xAxis = series.xAxis, currentDataGrouping, dateTimeLabelFormats, labelFormats, formattedKey, n, ret; // apply only to grouped series if (xAxis && xAxis.options.type === 'datetime' && dataGroupingOptions && isNumber(point.key)) { // set variables currentDataGrouping = series.currentDataGrouping; dateTimeLabelFormats = dataGroupingOptions.dateTimeLabelFormats; // if we have grouped data, use the grouping information to get the right format if (currentDataGrouping) { labelFormats = dateTimeLabelFormats[currentDataGrouping.unitName]; if (currentDataGrouping.count === 1) { xDateFormat = labelFormats[0]; } else { xDateFormat = labelFormats[1]; xDateFormatEnd = labelFormats[2]; } // if not grouped, and we don't have set the xDateFormat option, get the best fit, // so if the least distance between points is one minute, show it, but if the // least distance is one day, skip hours and minutes etc. } else if (!xDateFormat && dateTimeLabelFormats) { for (n in timeUnits) { if (timeUnits[n] >= xAxis.closestPointRange || // If the point is placed every day at 23:59, we need to show // the minutes as well. This logic only works for time units less than // a day, since all higher time units are dividable by those. #2637. (timeUnits[n] <= timeUnits[DAY] && point.key % timeUnits[n] > 0)) { xDateFormat = dateTimeLabelFormats[n][0]; break; } } } // now format the key formattedKey = dateFormat(xDateFormat, point.key); if (xDateFormatEnd) { formattedKey += dateFormat(xDateFormatEnd, point.key + currentDataGrouping.totalRange - 1); } // return the replaced format ret = tooltipOptions.headerFormat.replace('{point.key}', formattedKey); // else, fall back to the regular formatter } else { ret = baseTooltipHeaderFormatter.call(tooltip, point); } return ret; }; /** * Extend the series destroyer */ seriesProto.destroy = function () { var series = this, groupedData = series.groupedData || [], i = groupedData.length; while (i--) { if (groupedData[i]) { groupedData[i].destroy(); } } baseDestroy.apply(series); }; // Handle default options for data grouping. This must be set at runtime because some series types are // defined after this. wrap(seriesProto, 'setOptions', function (proceed, itemOptions) { var options = proceed.call(this, itemOptions), type = this.type, plotOptions = this.chart.options.plotOptions, defaultOptions = defaultPlotOptions[type].dataGrouping; if (specificOptions[type]) { // #1284 if (!defaultOptions) { defaultOptions = merge(commonOptions, specificOptions[type]); } options.dataGrouping = merge( defaultOptions, plotOptions.series && plotOptions.series.dataGrouping, // #1228 plotOptions[type].dataGrouping, // Set by the StockChart constructor itemOptions.dataGrouping ); } if (this.chart.options._stock) { this.requireSorting = true; } return options; }); /** * When resetting the scale reset the hasProccessed flag to avoid taking previous data grouping * of neighbour series into accound when determining group pixel width (#2692). */ wrap(Axis.prototype, 'setScale', function (proceed) { proceed.call(this); each(this.series, function (series) { series.hasProcessed = false; }); }); /** * Get the data grouping pixel width based on the greatest defined individual width * of the axis' series, and if whether one of the axes need grouping. */ Axis.prototype.getGroupPixelWidth = function () { var series = this.series, len = series.length, i, groupPixelWidth = 0, doGrouping = false, dataLength, dgOptions; // If multiple series are compared on the same x axis, give them the same // group pixel width (#334) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions) { groupPixelWidth = mathMax(groupPixelWidth, dgOptions.groupPixelWidth); } } // If one of the series needs grouping, apply it to all (#1634) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions && series[i].hasProcessed) { // #2692 dataLength = (series[i].processedXData || series[i].data).length; // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (series[i].groupPixelWidth || dataLength > (this.chart.plotSizeX / groupPixelWidth) || (dataLength && dgOptions.forced)) { doGrouping = true; } } } return doGrouping ? groupPixelWidth : 0; }; /* **************************************************************************** * End data grouping module * ******************************************************************************//* **************************************************************************** * Start OHLC series code * *****************************************************************************/ // 1 - Set default options defaultPlotOptions.ohlc = merge(defaultPlotOptions.column, { lineWidth: 1, tooltip: { pointFormat: '<span style="color:{series.color}">\u25CF</span> <b> {series.name}</b><br/>' + 'Open: {point.open}<br/>' + 'High: {point.high}<br/>' + 'Low: {point.low}<br/>' + 'Close: {point.close}<br/>' }, states: { hover: { lineWidth: 3 } }, threshold: null //upColor: undefined }); // 2 - Create the OHLCSeries object var OHLCSeries = extendClass(seriesTypes.column, { type: 'ohlc', pointArrayMap: ['open', 'high', 'low', 'close'], // array point configs are mapped to this toYData: function (point) { // return a plain array for speedy calculation return [point.open, point.high, point.low, point.close]; }, pointValKey: 'high', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'color', 'stroke-width': 'lineWidth' }, upColorProp: 'stroke', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.column.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upColor = options.upColor || series.color, seriesDownPointAttr = merge(series.pointAttr), upColorProp = series.upColorProp; seriesDownPointAttr[''][upColorProp] = upColor; seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || upColor; seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor; each(series.points, function (point) { if (point.open < point.close) { point.pointAttr = seriesDownPointAttr; } }); }, /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis; seriesTypes.column.prototype.translate.apply(series); // do the translation each(series.points, function (point) { // the graphics if (point.open !== null) { point.plotOpen = yAxis.translate(point.open, 0, 1, 0, 1); } if (point.close !== null) { point.plotClose = yAxis.translate(point.close, 0, 1, 0, 1); } }); }, /** * Draw the data points */ drawPoints: function () { var series = this, points = series.points, chart = series.chart, pointAttr, plotOpen, plotClose, crispCorr, halfWidth, path, graphic, crispX; each(points, function (point) { if (point.plotY !== UNDEFINED) { graphic = point.graphic; pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || series.pointAttr[NORMAL_STATE]; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 halfWidth = mathRound(point.shapeArgs.width / 2); // the vertical stem path = [ 'M', crispX, mathRound(point.yBottom), 'L', crispX, mathRound(point.plotY) ]; // open if (point.open !== null) { plotOpen = mathRound(point.plotOpen) + crispCorr; path.push( 'M', crispX, plotOpen, 'L', crispX - halfWidth, plotOpen ); } // close if (point.close !== null) { plotClose = mathRound(point.plotClose) + crispCorr; path.push( 'M', crispX, plotClose, 'L', crispX + halfWidth, plotClose ); } // create and/or update the graphic if (graphic) { graphic.animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group); } } }); }, /** * Disable animation */ animate: null }); seriesTypes.ohlc = OHLCSeries; /* **************************************************************************** * End OHLC series code * *****************************************************************************/ /* **************************************************************************** * Start Candlestick series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.candlestick = merge(defaultPlotOptions.column, { lineColor: 'black', lineWidth: 1, states: { hover: { lineWidth: 2 } }, tooltip: defaultPlotOptions.ohlc.tooltip, threshold: null, upColor: 'white' // upLineColor: null }); // 2 - Create the CandlestickSeries object var CandlestickSeries = extendClass(OHLCSeries, { type: 'candlestick', /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'color', stroke: 'lineColor', 'stroke-width': 'lineWidth' }, upColorProp: 'fill', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.ohlc.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upLineColor = options.upLineColor || options.lineColor, hoverStroke = stateOptions.hover.upLineColor || upLineColor, selectStroke = stateOptions.select.upLineColor || upLineColor; // Add custom line color for points going up (close > open). // Fill is handled by OHLCSeries' getAttribs. each(series.points, function (point) { if (point.open < point.close) { point.pointAttr[''].stroke = upLineColor; point.pointAttr.hover.stroke = hoverStroke; point.pointAttr.select.stroke = selectStroke; } }); }, /** * Draw the data points */ drawPoints: function () { var series = this, //state = series.state, points = series.points, chart = series.chart, pointAttr, seriesPointAttr = series.pointAttr[''], plotOpen, plotClose, topBox, bottomBox, hasTopWhisker, hasBottomWhisker, crispCorr, crispX, graphic, path, halfWidth; each(points, function (point) { graphic = point.graphic; if (point.plotY !== UNDEFINED) { pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || seriesPointAttr; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 plotOpen = point.plotOpen; plotClose = point.plotClose; topBox = math.min(plotOpen, plotClose); bottomBox = math.max(plotOpen, plotClose); halfWidth = mathRound(point.shapeArgs.width / 2); hasTopWhisker = mathRound(topBox) !== mathRound(point.plotY); hasBottomWhisker = bottomBox !== point.yBottom; topBox = mathRound(topBox) + crispCorr; bottomBox = mathRound(bottomBox) + crispCorr; // create the path path = [ 'M', crispX - halfWidth, bottomBox, 'L', crispX - halfWidth, topBox, 'L', crispX + halfWidth, topBox, 'L', crispX + halfWidth, bottomBox, 'Z', // Use a close statement to ensure a nice rectangle #2602 'M', crispX, topBox, 'L', crispX, hasTopWhisker ? mathRound(point.plotY) : topBox, // #460, #2094 'M', crispX, bottomBox, 'L', crispX, hasBottomWhisker ? mathRound(point.yBottom) : bottomBox, // #460, #2094 'Z' ]; if (graphic) { graphic.animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group) .shadow(series.options.shadow); } } }); } }); seriesTypes.candlestick = CandlestickSeries; /* **************************************************************************** * End Candlestick series code * *****************************************************************************/ /* **************************************************************************** * Start Flags series code * *****************************************************************************/ var symbols = SVGRenderer.prototype.symbols; // 1 - set default options defaultPlotOptions.flags = merge(defaultPlotOptions.column, { dataGrouping: null, fillColor: 'white', lineWidth: 1, pointRange: 0, // #673 //radius: 2, shape: 'flag', stackDistance: 12, states: { hover: { lineColor: 'black', fillColor: '#FCFFC5' } }, style: { fontSize: '11px', fontWeight: 'bold', textAlign: 'center' }, tooltip: { pointFormat: '{point.text}<br/>' }, threshold: null, y: -30 }); // 2 - Create the CandlestickSeries object seriesTypes.flags = extendClass(seriesTypes.column, { type: 'flags', sorted: false, noSharedTooltip: true, takeOrdinalPosition: false, // #1074 trackerGroups: ['markerGroup'], forceCrop: true, /** * Inherit the initialization from base Series */ init: Series.prototype.init, /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'fillColor', stroke: 'color', 'stroke-width': 'lineWidth', r: 'radius' }, /** * Extend the translate method by placing the point on the related series */ translate: function () { seriesTypes.column.prototype.translate.apply(this); var series = this, options = series.options, chart = series.chart, points = series.points, cursor = points.length - 1, point, lastPoint, optionsOnSeries = options.onSeries, onSeries = optionsOnSeries && chart.get(optionsOnSeries), step = onSeries && onSeries.options.step, onData = onSeries && onSeries.points, i = onData && onData.length, xAxis = series.xAxis, xAxisExt = xAxis.getExtremes(), leftPoint, lastX, rightPoint, currentDataGrouping; // relate to a master series if (onSeries && onSeries.visible && i) { currentDataGrouping = onSeries.currentDataGrouping; lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374 // sort the data points points.sort(function (a, b) { return (a.x - b.x); }); while (i-- && points[cursor]) { point = points[cursor]; leftPoint = onData[i]; if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) { if (point.x <= lastX) { // #803 point.plotY = leftPoint.plotY; // interpolate between points, #666 if (leftPoint.x < point.x && !step) { rightPoint = onData[i + 1]; if (rightPoint && rightPoint.plotY !== UNDEFINED) { point.plotY += ((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1 (rightPoint.plotY - leftPoint.plotY); // the y distance } } } cursor--; i++; // check again for points in the same x position if (cursor < 0) { break; } } } } // Add plotY position and handle stacking each(points, function (point, i) { // Undefined plotY means the point is either on axis, outside series range or hidden series. // If the series is outside the range of the x axis it should fall through with // an undefined plotY, but then we must remove the shapeArgs (#847). if (point.plotY === UNDEFINED) { if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop; } else { point.shapeArgs = {}; // 847 } } // if multiple flags appear at the same x, order them into a stack lastPoint = points[i - 1]; if (lastPoint && lastPoint.plotX === point.plotX) { if (lastPoint.stackIndex === UNDEFINED) { lastPoint.stackIndex = 0; } point.stackIndex = lastPoint.stackIndex + 1; } }); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, seriesPointAttr = series.pointAttr[''], points = series.points, chart = series.chart, renderer = chart.renderer, plotX, plotY, options = series.options, optionsY = options.y, shape, i, point, graphic, stackIndex, crisp = (options.lineWidth % 2 / 2), anchorX, anchorY, outsideRight; i = points.length; while (i--) { point = points[i]; outsideRight = point.plotX > series.xAxis.len; plotX = point.plotX + (outsideRight ? crisp : -crisp); stackIndex = point.stackIndex; shape = point.options.shape || options.shape; plotY = point.plotY; if (plotY !== UNDEFINED) { plotY = point.plotY + optionsY + crisp - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance); } anchorX = stackIndex ? UNDEFINED : point.plotX + crisp; // skip connectors for higher level stacked points anchorY = stackIndex ? UNDEFINED : point.plotY; graphic = point.graphic; // only draw the point if y is defined and the flag is within the visible area if (plotY !== UNDEFINED && plotX >= 0 && !outsideRight) { // shortcuts pointAttr = point.pointAttr[point.selected ? 'select' : ''] || seriesPointAttr; if (graphic) { // update graphic.attr({ x: plotX, y: plotY, r: pointAttr.r, anchorX: anchorX, anchorY: anchorY }); } else { graphic = point.graphic = renderer.label( point.options.title || options.title || 'A', plotX, plotY, shape, anchorX, anchorY, options.useHTML ) .css(merge(options.style, point.style)) .attr(pointAttr) .attr({ align: shape === 'flag' ? 'left' : 'center', width: options.width, height: options.height }) .add(series.markerGroup) .shadow(options.shadow); } // Set the tooltip anchor position point.tooltipPos = [plotX, plotY]; } else if (graphic) { point.graphic = graphic.destroy(); } } }, /** * Extend the column trackers with listeners to expand and contract stacks */ drawTracker: function () { var series = this, points = series.points; TrackerMixin.drawTrackerPoint.apply(this); // Bring each stacked flag up on mouse over, this allows readability of vertically // stacked elements as well as tight points on the x axis. #1924. each(points, function (point) { var graphic = point.graphic; if (graphic) { addEvent(graphic.element, 'mouseover', function () { // Raise this point if (point.stackIndex > 0 && !point.raised) { point._y = graphic.y; graphic.attr({ y: point._y - 8 }); point.raised = true; } // Revert other raised points each(points, function (otherPoint) { if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) { otherPoint.graphic.attr({ y: otherPoint._y }); otherPoint.raised = false; } }); }); } }); }, /** * Disable animation */ animate: noop }); // create the flag icon with anchor symbols.flag = function (x, y, w, h, options) { var anchorX = (options && options.anchorX) || x, anchorY = (options && options.anchorY) || y; return [ 'M', anchorX, anchorY, 'L', x, y + h, x, y, x + w, y, x + w, y + h, x, y + h, 'M', anchorX, anchorY, 'Z' ]; }; // create the circlepin and squarepin icons with anchor each(['circle', 'square'], function (shape) { symbols[shape + 'pin'] = function (x, y, w, h, options) { var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path = symbols[shape](x, y, w, h), labelTopOrBottomY; if (anchorX && anchorY) { // if the label is below the anchor, draw the connecting line from the top edge of the label // otherwise start drawing from the bottom edge labelTopOrBottomY = (y > anchorY) ? y : y + h; path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY); } return path; }; }); // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === Highcharts.VMLRenderer) { each(['flag', 'circlepin', 'squarepin'], function (shape) { VMLRenderer.prototype.symbols[shape] = symbols[shape]; }); } /* **************************************************************************** * End Flags series code * *****************************************************************************/ /* **************************************************************************** * Start Scroller code * *****************************************************************************/ var units = [].concat(defaultDataGroupingUnits), // copy defaultSeriesType; // add more resolution to units units[4] = [DAY, [1, 2, 3, 4]]; // allow more days units[5] = [WEEK, [1, 2, 3]]; // allow more weeks defaultSeriesType = seriesTypes.areaspline === UNDEFINED ? 'line' : 'areaspline'; extend(defaultOptions, { navigator: { //enabled: true, handles: { backgroundColor: '#ebe7e8', // docs borderColor: '#b2b1b6' // docs }, height: 40, margin: 25, // docs maskFill: 'rgba(128,179,236,0.3)', // docs maskInside: true, // docs outlineColor: '#b2b1b6', // docs outlineWidth: 1, series: { type: defaultSeriesType, color: '#4572A7', compare: null, fillOpacity: 0.05, // docs dataGrouping: { approximation: 'average', enabled: true, groupPixelWidth: 2, smoothed: true, units: units }, dataLabels: { enabled: false, zIndex: 2 // #1839 }, id: PREFIX + 'navigator-series', lineColor: '#4572A7', lineWidth: 1, marker: { enabled: false }, pointRange: 0, shadow: false, threshold: null }, //top: undefined, xAxis: { tickWidth: 0, lineWidth: 0, gridLineColor: '#EEE', gridLineWidth: 1, tickPixelInterval: 200, labels: { align: 'left', style: { color: '#888' // docs }, x: 3, y: -4 }, crosshair: false }, yAxis: { gridLineWidth: 0, startOnTick: false, endOnTick: false, minPadding: 0.1, maxPadding: 0.1, labels: { enabled: false }, crosshair: false, title: { text: null }, tickWidth: 0 } }, scrollbar: { //enabled: true height: isTouchDevice ? 20 : 14, barBackgroundColor: '#bfc8d1', // docs barBorderRadius: 0, // docs: new default barBorderWidth: 1, barBorderColor: '#bfc8d1', // docs buttonArrowColor: '#666', buttonBackgroundColor: '#ebe7e8', // docs buttonBorderColor: '#bbb', // docs: new default buttonBorderRadius: 0, // docs: new default buttonBorderWidth: 1, minWidth: 6, rifleColor: '#666', trackBackgroundColor: '#eeeeee', // docs: new default trackBorderColor: '#eeeeee', // docs: new default trackBorderWidth: 1, // trackBorderRadius: 0 liveRedraw: hasSVG && !isTouchDevice } }); /** * The Scroller class * @param {Object} chart */ function Scroller(chart) { var chartOptions = chart.options, navigatorOptions = chartOptions.navigator, navigatorEnabled = navigatorOptions.enabled, scrollbarOptions = chartOptions.scrollbar, scrollbarEnabled = scrollbarOptions.enabled, height = navigatorEnabled ? navigatorOptions.height : 0, scrollbarHeight = scrollbarEnabled ? scrollbarOptions.height : 0; this.handles = []; this.scrollbarButtons = []; this.elementsToDestroy = []; // Array containing the elements to destroy when Scroller is destroyed this.chart = chart; this.setBaseSeries(); this.height = height; this.scrollbarHeight = scrollbarHeight; this.scrollbarEnabled = scrollbarEnabled; this.navigatorEnabled = navigatorEnabled; this.navigatorOptions = navigatorOptions; this.scrollbarOptions = scrollbarOptions; this.outlineHeight = height + scrollbarHeight; // Run scroller this.init(); } Scroller.prototype = { /** * Draw one of the handles on the side of the zoomed range in the navigator * @param {Number} x The x center for the handle * @param {Number} index 0 for left and 1 for right */ drawHandle: function (x, index) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, elementsToDestroy = scroller.elementsToDestroy, handles = scroller.handles, handlesOptions = scroller.navigatorOptions.handles, attr = { fill: handlesOptions.backgroundColor, stroke: handlesOptions.borderColor, 'stroke-width': 1 }, tempElem; // create the elements if (!scroller.rendered) { // the group handles[index] = renderer.g('navigator-handle-' + ['left', 'right'][index]) .css({ cursor: 'e-resize' }) .attr({ zIndex: 4 - index }) // zIndex = 3 for right handle, 4 for left .add(); // the rectangle tempElem = renderer.rect(-4.5, 0, 9, 16, 0, 1) .attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); // the rifles tempElem = renderer.path([ 'M', -1.5, 4, 'L', -1.5, 12, 'M', 0.5, 4, 'L', 0.5, 12 ]).attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); } // Place it handles[index][chart.isResizing ? 'animate' : 'attr']({ translateX: scroller.scrollerLeft + scroller.scrollbarHeight + parseInt(x, 10), translateY: scroller.top + scroller.height / 2 - 8 }); }, /** * Draw the scrollbar buttons with arrows * @param {Number} index 0 is left, 1 is right */ drawScrollbarButton: function (index) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, elementsToDestroy = scroller.elementsToDestroy, scrollbarButtons = scroller.scrollbarButtons, scrollbarHeight = scroller.scrollbarHeight, scrollbarOptions = scroller.scrollbarOptions, tempElem; if (!scroller.rendered) { scrollbarButtons[index] = renderer.g().add(scroller.scrollbarGroup); tempElem = renderer.rect( -0.5, -0.5, scrollbarHeight + 1, // +1 to compensate for crispifying in rect method scrollbarHeight + 1, scrollbarOptions.buttonBorderRadius, scrollbarOptions.buttonBorderWidth ).attr({ stroke: scrollbarOptions.buttonBorderColor, 'stroke-width': scrollbarOptions.buttonBorderWidth, fill: scrollbarOptions.buttonBackgroundColor }).add(scrollbarButtons[index]); elementsToDestroy.push(tempElem); tempElem = renderer.path([ 'M', scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 - 3, 'L', scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 + 3, scrollbarHeight / 2 + (index ? 2 : -2), scrollbarHeight / 2 ]).attr({ fill: scrollbarOptions.buttonArrowColor }).add(scrollbarButtons[index]); elementsToDestroy.push(tempElem); } // adjust the right side button to the varying length of the scroll track if (index) { scrollbarButtons[index].attr({ translateX: scroller.scrollerWidth - scrollbarHeight }); } }, /** * Render the navigator and scroll bar * @param {Number} min X axis value minimum * @param {Number} max X axis value maximum * @param {Number} pxMin Pixel value minimum * @param {Number} pxMax Pixel value maximum */ render: function (min, max, pxMin, pxMax) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, navigatorLeft, navigatorWidth, scrollerLeft, scrollerWidth, scrollbarGroup = scroller.scrollbarGroup, navigatorGroup = scroller.navigatorGroup, scrollbar = scroller.scrollbar, xAxis = scroller.xAxis, scrollbarTrack = scroller.scrollbarTrack, scrollbarHeight = scroller.scrollbarHeight, scrollbarEnabled = scroller.scrollbarEnabled, navigatorOptions = scroller.navigatorOptions, scrollbarOptions = scroller.scrollbarOptions, scrollbarMinWidth = scrollbarOptions.minWidth, height = scroller.height, top = scroller.top, navigatorEnabled = scroller.navigatorEnabled, outlineWidth = navigatorOptions.outlineWidth, halfOutline = outlineWidth / 2, zoomedMin, zoomedMax, range, scrX, scrWidth, scrollbarPad = 0, outlineHeight = scroller.outlineHeight, barBorderRadius = scrollbarOptions.barBorderRadius, strokeWidth, scrollbarStrokeWidth = scrollbarOptions.barBorderWidth, centerBarX, outlineTop = top + halfOutline, verb, unionExtremes; // don't render the navigator until we have data (#486) if (isNaN(min)) { return; } scroller.navigatorLeft = navigatorLeft = pick( xAxis.left, chart.plotLeft + scrollbarHeight // in case of scrollbar only, without navigator ); scroller.navigatorWidth = navigatorWidth = pick(xAxis.len, chart.plotWidth - 2 * scrollbarHeight); scroller.scrollerLeft = scrollerLeft = navigatorLeft - scrollbarHeight; scroller.scrollerWidth = scrollerWidth = scrollerWidth = navigatorWidth + 2 * scrollbarHeight; // Set the scroller x axis extremes to reflect the total. The navigator extremes // should always be the extremes of the union of all series in the chart as // well as the navigator series. if (xAxis.getExtremes) { unionExtremes = scroller.getUnionExtremes(true); if (unionExtremes && (unionExtremes.dataMin !== xAxis.min || unionExtremes.dataMax !== xAxis.max)) { xAxis.setExtremes(unionExtremes.dataMin, unionExtremes.dataMax, true, false); } } // Get the pixel position of the handles pxMin = pick(pxMin, xAxis.translate(min)); pxMax = pick(pxMax, xAxis.translate(max)); if (isNaN(pxMin) || mathAbs(pxMin) === Infinity) { // Verify (#1851, #2238) pxMin = 0; pxMax = scrollerWidth; } // Are we below the minRange? (#2618) if (xAxis.translate(pxMax, true) - xAxis.translate(pxMin, true) < chart.xAxis[0].minRange) { return; } // handles are allowed to cross, but never exceed the plot area scroller.zoomedMax = mathMin(mathMax(pxMin, pxMax), navigatorWidth); scroller.zoomedMin = mathMax(scroller.fixedWidth ? scroller.zoomedMax - scroller.fixedWidth : mathMin(pxMin, pxMax), 0); scroller.range = scroller.zoomedMax - scroller.zoomedMin; zoomedMax = mathRound(scroller.zoomedMax); zoomedMin = mathRound(scroller.zoomedMin); range = zoomedMax - zoomedMin; // on first render, create all elements if (!scroller.rendered) { if (navigatorEnabled) { // draw the navigator group scroller.navigatorGroup = navigatorGroup = renderer.g('navigator') .attr({ zIndex: 3 }) .add(); scroller.leftShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); if (!navigatorOptions.maskInside) { scroller.rightShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); } scroller.outline = renderer.path() .attr({ 'stroke-width': outlineWidth, stroke: navigatorOptions.outlineColor }) .add(navigatorGroup); } if (scrollbarEnabled) { // draw the scrollbar group scroller.scrollbarGroup = scrollbarGroup = renderer.g('scrollbar').add(); // the scrollbar track strokeWidth = scrollbarOptions.trackBorderWidth; scroller.scrollbarTrack = scrollbarTrack = renderer.rect().attr({ x: 0, y: -strokeWidth % 2 / 2, fill: scrollbarOptions.trackBackgroundColor, stroke: scrollbarOptions.trackBorderColor, 'stroke-width': strokeWidth, r: scrollbarOptions.trackBorderRadius || 0, height: scrollbarHeight }).add(scrollbarGroup); // the scrollbar itself scroller.scrollbar = scrollbar = renderer.rect() .attr({ y: -scrollbarStrokeWidth % 2 / 2, height: scrollbarHeight, fill: scrollbarOptions.barBackgroundColor, stroke: scrollbarOptions.barBorderColor, 'stroke-width': scrollbarStrokeWidth, r: barBorderRadius }) .add(scrollbarGroup); scroller.scrollbarRifles = renderer.path() .attr({ stroke: scrollbarOptions.rifleColor, 'stroke-width': 1 }) .add(scrollbarGroup); } } // place elements verb = chart.isResizing ? 'animate' : 'attr'; if (navigatorEnabled) { scroller.leftShade[verb](navigatorOptions.maskInside ? { x: navigatorLeft + zoomedMin, y: top, width: zoomedMax - zoomedMin, height: height } : { x: navigatorLeft, y: top, width: zoomedMin, height: height }); if (scroller.rightShade) { scroller.rightShade[verb]({ x: navigatorLeft + zoomedMax, y: top, width: navigatorWidth - zoomedMax, height: height }); } scroller.outline[verb]({ d: [ M, scrollerLeft, outlineTop, // left L, navigatorLeft + zoomedMin + halfOutline, outlineTop, // upper left of zoomed range navigatorLeft + zoomedMin + halfOutline, outlineTop + outlineHeight, // lower left of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop + outlineHeight, // lower right of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop, // upper right of z.r. scrollerLeft + scrollerWidth, outlineTop // right ].concat(navigatorOptions.maskInside ? [ M, navigatorLeft + zoomedMin + halfOutline, outlineTop, // upper left of zoomed range L, navigatorLeft + zoomedMax - halfOutline, outlineTop // upper right of z.r. ] : [])}); // draw handles scroller.drawHandle(zoomedMin + halfOutline, 0); scroller.drawHandle(zoomedMax + halfOutline, 1); } // draw the scrollbar if (scrollbarEnabled && scrollbarGroup) { // draw the buttons scroller.drawScrollbarButton(0); scroller.drawScrollbarButton(1); scrollbarGroup[verb]({ translateX: scrollerLeft, translateY: mathRound(outlineTop + height) }); scrollbarTrack[verb]({ width: scrollerWidth }); // prevent the scrollbar from drawing to small (#1246) scrX = scrollbarHeight + zoomedMin; scrWidth = range - scrollbarStrokeWidth; if (scrWidth < scrollbarMinWidth) { scrollbarPad = (scrollbarMinWidth - scrWidth) / 2; scrWidth = scrollbarMinWidth; scrX -= scrollbarPad; } scroller.scrollbarPad = scrollbarPad; scrollbar[verb]({ x: mathFloor(scrX) + (scrollbarStrokeWidth % 2 / 2), width: scrWidth }); centerBarX = scrollbarHeight + zoomedMin + range / 2 - 0.5; scroller.scrollbarRifles .attr({ visibility: range > 12 ? VISIBLE : HIDDEN })[verb]({ d: [ M, centerBarX - 3, scrollbarHeight / 4, L, centerBarX - 3, 2 * scrollbarHeight / 3, M, centerBarX, scrollbarHeight / 4, L, centerBarX, 2 * scrollbarHeight / 3, M, centerBarX + 3, scrollbarHeight / 4, L, centerBarX + 3, 2 * scrollbarHeight / 3 ] }); } scroller.scrollbarPad = scrollbarPad; scroller.rendered = true; }, /** * Set up the mouse and touch events for the navigator and scrollbar */ addEvents: function () { var container = this.chart.container, mouseDownHandler = this.mouseDownHandler, mouseMoveHandler = this.mouseMoveHandler, mouseUpHandler = this.mouseUpHandler, _events; // Mouse events _events = [ [container, 'mousedown', mouseDownHandler], [container, 'mousemove', mouseMoveHandler], [document, 'mouseup', mouseUpHandler] ]; // Touch events if (hasTouch) { _events.push( [container, 'touchstart', mouseDownHandler], [container, 'touchmove', mouseMoveHandler], [document, 'touchend', mouseUpHandler] ); } // Add them all each(_events, function (args) { addEvent.apply(null, args); }); this._events = _events; }, /** * Removes the event handlers attached previously with addEvents. */ removeEvents: function () { each(this._events, function (args) { removeEvent.apply(null, args); }); this._events = UNDEFINED; if (this.navigatorEnabled && this.baseSeries) { removeEvent(this.baseSeries, 'updatedData', this.updatedDataHandler); } }, /** * Initiate the Scroller object */ init: function () { var scroller = this, chart = scroller.chart, xAxis, yAxis, scrollbarHeight = scroller.scrollbarHeight, navigatorOptions = scroller.navigatorOptions, height = scroller.height, top = scroller.top, dragOffset, hasDragged, bodyStyle = document.body.style, defaultBodyCursor, baseSeries = scroller.baseSeries; /** * Event handler for the mouse down event. */ scroller.mouseDownHandler = function (e) { e = chart.pointer.normalize(e); var zoomedMin = scroller.zoomedMin, zoomedMax = scroller.zoomedMax, top = scroller.top, scrollbarHeight = scroller.scrollbarHeight, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollbarPad = scroller.scrollbarPad, range = scroller.range, chartX = e.chartX, chartY = e.chartY, baseXAxis = chart.xAxis[0], fixedMax, ext, handleSensitivity = isTouchDevice ? 10 : 7, left, isOnNavigator; if (chartY > top && chartY < top + height + scrollbarHeight) { // we're vertically inside the navigator isOnNavigator = !scroller.scrollbarEnabled || chartY < top + height; // grab the left handle if (isOnNavigator && math.abs(chartX - zoomedMin - navigatorLeft) < handleSensitivity) { scroller.grabbedLeft = true; scroller.otherHandlePos = zoomedMax; scroller.fixedExtreme = baseXAxis.max; chart.fixedRange = null; // grab the right handle } else if (isOnNavigator && math.abs(chartX - zoomedMax - navigatorLeft) < handleSensitivity) { scroller.grabbedRight = true; scroller.otherHandlePos = zoomedMin; scroller.fixedExtreme = baseXAxis.min; chart.fixedRange = null; // grab the zoomed range } else if (chartX > navigatorLeft + zoomedMin - scrollbarPad && chartX < navigatorLeft + zoomedMax + scrollbarPad) { scroller.grabbedCenter = chartX; scroller.fixedWidth = range; // In SVG browsers, change the cursor. IE6 & 7 produce an error on changing the cursor, // and IE8 isn't able to show it while dragging anyway. if (chart.renderer.isSVG) { defaultBodyCursor = bodyStyle.cursor; bodyStyle.cursor = 'ew-resize'; } dragOffset = chartX - zoomedMin; // shift the range by clicking on shaded areas, scrollbar track or scrollbar buttons } else if (chartX > scrollerLeft && chartX < scrollerLeft + scrollerWidth) { // Center around the clicked point if (isOnNavigator) { left = chartX - navigatorLeft - range / 2; // Click on scrollbar } else { // Click left scrollbar button if (chartX < navigatorLeft) { left = zoomedMin - range * 0.2; // Click right scrollbar button } else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) { left = zoomedMin + range * 0.2; // Click on scrollbar track, shift the scrollbar by one range } else { left = chartX < navigatorLeft + zoomedMin ? // on the left zoomedMin - range : zoomedMax; } } if (left < 0) { left = 0; } else if (left + range >= navigatorWidth) { left = navigatorWidth - range; fixedMax = xAxis.dataMax; // #2293 } if (left !== zoomedMin) { // it has actually moved scroller.fixedWidth = range; // #1370 ext = xAxis.toFixedRange(left, left + range, null, fixedMax); baseXAxis.setExtremes( ext.min, ext.max, true, false, { trigger: 'navigator' } ); } } } }; /** * Event handler for the mouse move event. */ scroller.mouseMoveHandler = function (e) { var scrollbarHeight = scroller.scrollbarHeight, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, range = scroller.range, chartX; // In iOS, a mousemove event with e.pageX === 0 is fired when holding the finger // down in the center of the scrollbar. This should be ignored. if (e.pageX !== 0) { e = chart.pointer.normalize(e); chartX = e.chartX; // validation for handle dragging if (chartX < navigatorLeft) { chartX = navigatorLeft; } else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) { chartX = scrollerLeft + scrollerWidth - scrollbarHeight; } // drag left handle if (scroller.grabbedLeft) { hasDragged = true; scroller.render(0, 0, chartX - navigatorLeft, scroller.otherHandlePos); // drag right handle } else if (scroller.grabbedRight) { hasDragged = true; scroller.render(0, 0, scroller.otherHandlePos, chartX - navigatorLeft); // drag scrollbar or open area in navigator } else if (scroller.grabbedCenter) { hasDragged = true; if (chartX < dragOffset) { // outside left chartX = dragOffset; } else if (chartX > navigatorWidth + dragOffset - range) { // outside right chartX = navigatorWidth + dragOffset - range; } scroller.render(0, 0, chartX - dragOffset, chartX - dragOffset + range); } if (hasDragged && scroller.scrollbarOptions.liveRedraw) { setTimeout(function () { scroller.mouseUpHandler(e); }, 0); } } }; /** * Event handler for the mouse up event. */ scroller.mouseUpHandler = function (e) { var ext, fixedMin, fixedMax; if (hasDragged) { // When dragging one handle, make sure the other one doesn't change if (scroller.zoomedMin === scroller.otherHandlePos) { fixedMin = scroller.fixedExtreme; } else if (scroller.zoomedMax === scroller.otherHandlePos) { fixedMax = scroller.fixedExtreme; } ext = xAxis.toFixedRange(scroller.zoomedMin, scroller.zoomedMax, fixedMin, fixedMax); chart.xAxis[0].setExtremes( ext.min, ext.max, true, false, { trigger: 'navigator', triggerOp: 'navigator-drag', DOMEvent: e // #1838 } ); } if (e.type !== 'mousemove') { scroller.grabbedLeft = scroller.grabbedRight = scroller.grabbedCenter = scroller.fixedWidth = scroller.fixedExtreme = scroller.otherHandlePos = hasDragged = dragOffset = null; bodyStyle.cursor = defaultBodyCursor || ''; } }; var xAxisIndex = chart.xAxis.length, yAxisIndex = chart.yAxis.length; // make room below the chart chart.extraBottomMargin = scroller.outlineHeight + navigatorOptions.margin; if (scroller.navigatorEnabled) { // an x axis is required for scrollbar also scroller.xAxis = xAxis = new Axis(chart, merge({ ordinal: baseSeries && baseSeries.xAxis.options.ordinal // inherit base xAxis' ordinal option }, navigatorOptions.xAxis, { id: 'navigator-x-axis', isX: true, type: 'datetime', index: xAxisIndex, height: height, offset: 0, offsetLeft: scrollbarHeight, offsetRight: -scrollbarHeight, keepOrdinalPadding: true, // #2436 startOnTick: false, endOnTick: false, minPadding: 0, maxPadding: 0, zoomEnabled: false })); scroller.yAxis = yAxis = new Axis(chart, merge(navigatorOptions.yAxis, { id: 'navigator-y-axis', alignTicks: false, height: height, offset: 0, index: yAxisIndex, zoomEnabled: false })); // If we have a base series, initialize the navigator series if (baseSeries || navigatorOptions.series.data) { scroller.addBaseSeries(); // If not, set up an event to listen for added series } else if (chart.series.length === 0) { wrap(chart, 'redraw', function (proceed, animation) { // We've got one, now add it as base and reset chart.redraw if (chart.series.length > 0 && !scroller.series) { scroller.setBaseSeries(); chart.redraw = proceed; // reset } proceed.call(chart, animation); }); } // in case of scrollbar only, fake an x axis to get translation } else { scroller.xAxis = xAxis = { translate: function (value, reverse) { var ext = chart.xAxis[0].getExtremes(), scrollTrackWidth = chart.plotWidth - 2 * scrollbarHeight, dataMin = ext.dataMin, valueRange = ext.dataMax - dataMin; return reverse ? // from pixel to value (value * valueRange / scrollTrackWidth) + dataMin : // from value to pixel scrollTrackWidth * (value - dataMin) / valueRange; }, toFixedRange: Axis.prototype.toFixedRange }; } /** * For stock charts, extend the Chart.getMargins method so that we can set the final top position * of the navigator once the height of the chart, including the legend, is determined. #367. */ wrap(chart, 'getMargins', function (proceed) { var legend = this.legend, legendOptions = legend.options; proceed.call(this); // Compute the top position scroller.top = top = scroller.navigatorOptions.top || this.chartHeight - scroller.height - scroller.scrollbarHeight - this.spacing[2] - (legendOptions.verticalAlign === 'bottom' && legendOptions.enabled && !legendOptions.floating ? legend.legendHeight + pick(legendOptions.margin, 10) : 0); if (xAxis && yAxis) { // false if navigator is disabled (#904) xAxis.options.top = yAxis.options.top = top; xAxis.setAxisSize(); yAxis.setAxisSize(); } }); scroller.addEvents(); }, /** * Get the union data extremes of the chart - the outer data extremes of the base * X axis and the navigator axis. */ getUnionExtremes: function (returnFalseOnNoBaseSeries) { var baseAxis = this.chart.xAxis[0], navAxis = this.xAxis, navAxisOptions = navAxis.options; if (!returnFalseOnNoBaseSeries || baseAxis.dataMin !== null) { return { dataMin: pick( navAxisOptions && navAxisOptions.min, ((defined(baseAxis.dataMin) && defined(navAxis.dataMin)) ? mathMin : pick)(baseAxis.dataMin, navAxis.dataMin) ), dataMax: pick( navAxisOptions && navAxisOptions.max, ((defined(baseAxis.dataMax) && defined(navAxis.dataMax)) ? mathMax : pick)(baseAxis.dataMax, navAxis.dataMax) ) }; } }, /** * Set the base series. With a bit of modification we should be able to make * this an API method to be called from the outside */ setBaseSeries: function (baseSeriesOption) { var chart = this.chart; baseSeriesOption = baseSeriesOption || chart.options.navigator.baseSeries; // If we're resetting, remove the existing series if (this.series) { this.series.remove(); } // Set the new base series this.baseSeries = chart.series[baseSeriesOption] || (typeof baseSeriesOption === 'string' && chart.get(baseSeriesOption)) || chart.series[0]; // When run after render, this.xAxis already exists if (this.xAxis) { this.addBaseSeries(); } }, addBaseSeries: function () { var baseSeries = this.baseSeries, baseOptions = baseSeries ? baseSeries.options : {}, baseData = baseOptions.data, mergedNavSeriesOptions, navigatorSeriesOptions = this.navigatorOptions.series, navigatorData; // remove it to prevent merging one by one navigatorData = navigatorSeriesOptions.data; this.hasNavigatorData = !!navigatorData; // Merge the series options mergedNavSeriesOptions = merge(baseOptions, navigatorSeriesOptions, { enableMouseTracking: false, group: 'nav', // for columns padXAxis: false, xAxis: 'navigator-x-axis', yAxis: 'navigator-y-axis', name: 'Navigator', showInLegend: false, isInternal: true, visible: true }); // set the data back mergedNavSeriesOptions.data = navigatorData || baseData; // add the series this.series = this.chart.initSeries(mergedNavSeriesOptions); // Respond to updated data in the base series. // Abort if lazy-loading data from the server. if (baseSeries && this.navigatorOptions.adaptToUpdatedData !== false) { addEvent(baseSeries, 'updatedData', this.updatedDataHandler); // Survive Series.update() baseSeries.userOptions.events = extend(baseSeries.userOptions.event, { updatedData: this.updatedDataHandler }); } }, updatedDataHandler: function () { var scroller = this.chart.scroller, baseSeries = scroller.baseSeries, baseXAxis = baseSeries.xAxis, baseExtremes = baseXAxis.getExtremes(), baseMin = baseExtremes.min, baseMax = baseExtremes.max, baseDataMin = baseExtremes.dataMin, baseDataMax = baseExtremes.dataMax, range = baseMax - baseMin, stickToMin, stickToMax, newMax, newMin, doRedraw, navigatorSeries = scroller.series, navXData = navigatorSeries.xData, hasSetExtremes = !!baseXAxis.setExtremes; // detect whether to move the range stickToMax = baseMax >= navXData[navXData.length - 1] - (this.closestPointRange || 0); // #570 stickToMin = baseMin <= baseDataMin; // set the navigator series data to the new data of the base series if (!scroller.hasNavigatorData) { navigatorSeries.options.pointStart = baseSeries.xData[0]; navigatorSeries.setData(baseSeries.options.data, false); doRedraw = true; } // if the zoomed range is already at the min, move it to the right as new data // comes in if (stickToMin) { newMin = baseDataMin; newMax = newMin + range; } // if the zoomed range is already at the max, move it to the right as new data // comes in if (stickToMax) { newMax = baseDataMax; if (!stickToMin) { // if stickToMin is true, the new min value is set above newMin = mathMax(newMax - range, navigatorSeries.xData[0]); } } // update the extremes if (hasSetExtremes && (stickToMin || stickToMax)) { if (!isNaN(newMin)) { baseXAxis.setExtremes(newMin, newMax, true, false, { trigger: 'updatedData' }); } // if it is not at any edge, just move the scroller window to reflect the new series data } else { if (doRedraw) { this.chart.redraw(false); } scroller.render( mathMax(baseMin, baseDataMin), mathMin(baseMax, baseDataMax) ); } }, /** * Destroys allocated elements. */ destroy: function () { var scroller = this; // Disconnect events added in addEvents scroller.removeEvents(); // Destroy properties each([scroller.xAxis, scroller.yAxis, scroller.leftShade, scroller.rightShade, scroller.outline, scroller.scrollbarTrack, scroller.scrollbarRifles, scroller.scrollbarGroup, scroller.scrollbar], function (prop) { if (prop && prop.destroy) { prop.destroy(); } }); scroller.xAxis = scroller.yAxis = scroller.leftShade = scroller.rightShade = scroller.outline = scroller.scrollbarTrack = scroller.scrollbarRifles = scroller.scrollbarGroup = scroller.scrollbar = null; // Destroy elements in collection each([scroller.scrollbarButtons, scroller.handles, scroller.elementsToDestroy], function (coll) { destroyObjectProperties(coll); }); } }; Highcharts.Scroller = Scroller; /** * For Stock charts, override selection zooming with some special features because * X axis zooming is already allowed by the Navigator and Range selector. */ wrap(Axis.prototype, 'zoom', function (proceed, newMin, newMax) { var chart = this.chart, chartOptions = chart.options, zoomType = chartOptions.chart.zoomType, previousZoom, navigator = chartOptions.navigator, rangeSelector = chartOptions.rangeSelector, ret; if (this.isXAxis && ((navigator && navigator.enabled) || (rangeSelector && rangeSelector.enabled))) { // For x only zooming, fool the chart.zoom method not to create the zoom button // because the property already exists if (zoomType === 'x') { chart.resetZoomButton = 'blocked'; // For y only zooming, ignore the X axis completely } else if (zoomType === 'y') { ret = false; // For xy zooming, record the state of the zoom before zoom selection, then when // the reset button is pressed, revert to this state } else if (zoomType === 'xy') { previousZoom = this.previousZoom; if (defined(newMin)) { this.previousZoom = [this.min, this.max]; } else if (previousZoom) { newMin = previousZoom[0]; newMax = previousZoom[1]; delete this.previousZoom; } } } return ret !== UNDEFINED ? ret : proceed.call(this, newMin, newMax); }); // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'beforeRender', function () { var options = this.options; if (options.navigator.enabled || options.scrollbar.enabled) { this.scroller = new Scroller(this); } }); proceed.call(this, options, callback); }); // Pick up badly formatted point options to addPoint wrap(Series.prototype, 'addPoint', function (proceed, options, redraw, shift, animation) { var turboThreshold = this.options.turboThreshold; if (turboThreshold && this.xData.length > turboThreshold && isObject(options) && !isArray(options) && this.chart.scroller) { error(20, true); } proceed.call(this, options, redraw, shift, animation); }); /* **************************************************************************** * End Scroller code * *****************************************************************************/ /* **************************************************************************** * Start Range Selector code * *****************************************************************************/ extend(defaultOptions, { rangeSelector: { // enabled: true, // buttons: {Object} // buttonSpacing: 0, buttonTheme: { width: 28, height: 18, fill: '#f7f7f7', padding: 2, r: 0, 'stroke-width': 0, style: { color: '#444', cursor: 'pointer', fontWeight: 'normal' }, zIndex: 7, // #484, #852 states: { hover: { fill: '#e7e7e7' }, select: { fill: '#e7f0f9', style: { color: 'black', fontWeight: 'bold' } } } }, inputPosition: { align: 'right' }, // inputDateFormat: '%b %e, %Y', // inputEditDateFormat: '%Y-%m-%d', // inputEnabled: true, // inputStyle: {}, labelStyle: { color: '#666' } // selected: undefined } }); defaultOptions.lang = merge(defaultOptions.lang, { rangeSelectorZoom: 'Zoom', rangeSelectorFrom: 'From', rangeSelectorTo: 'To' }); /** * The object constructor for the range selector * @param {Object} chart */ function RangeSelector(chart) { // Run RangeSelector this.init(chart); } RangeSelector.prototype = { /** * The method to run when one of the buttons in the range selectors is clicked * @param {Number} i The index of the button * @param {Object} rangeOptions * @param {Boolean} redraw */ clickButton: function (i, redraw) { var rangeSelector = this, selected = rangeSelector.selected, chart = rangeSelector.chart, buttons = rangeSelector.buttons, rangeOptions = rangeSelector.buttonOptions[i], baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis || {}, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, newMin, newMax = baseAxis && mathRound(mathMin(baseAxis.max, pick(dataMax, baseAxis.max))), // #1568 now, date = new Date(newMax), type = rangeOptions.type, count = rangeOptions.count, baseXAxisOptions, range = rangeOptions._range, rangeMin, year, timeName; if (dataMin === null || dataMax === null || // chart has no data, base series is removed i === rangeSelector.selected) { // same button is clicked twice return; } if (type === 'month' || type === 'year') { timeName = { month: 'Month', year: 'FullYear'}[type]; date['set' + timeName](date['get' + timeName]() - count); newMin = date.getTime(); dataMin = pick(dataMin, Number.MIN_VALUE); if (isNaN(newMin) || newMin < dataMin) { newMin = dataMin; newMax = mathMin(newMin + range, dataMax); } else { range = newMax - newMin; } // Fixed times like minutes, hours, days } else if (range) { newMin = mathMax(newMax - range, dataMin); newMax = mathMin(newMin + range, dataMax); } else if (type === 'ytd') { // On user clicks on the buttons, or a delayed action running from the beforeRender // event (below), the baseAxis is defined. if (baseAxis) { // When "ytd" is the pre-selected button for the initial view, its calculation // is delayed and rerun in the beforeRender event (below). When the series // are initialized, but before the chart is rendered, we have access to the xData // array (#942). if (dataMax === UNDEFINED) { dataMin = Number.MAX_VALUE; dataMax = Number.MIN_VALUE; each(chart.series, function (series) { var xData = series.xData; // reassign it to the last item dataMin = mathMin(xData[0], dataMin); dataMax = mathMax(xData[xData.length - 1], dataMax); }); redraw = false; } now = new Date(dataMax); year = now.getFullYear(); newMin = rangeMin = mathMax(dataMin || 0, Date.UTC(year, 0, 1)); now = now.getTime(); newMax = mathMin(dataMax || now, now); // "ytd" is pre-selected. We don't yet have access to processed point and extremes data // (things like pointStart and pointInterval are missing), so we delay the process (#942) } else { addEvent(chart, 'beforeRender', function () { rangeSelector.clickButton(i); }); return; } } else if (type === 'all' && baseAxis) { newMin = dataMin; newMax = dataMax; } // Deselect previous button if (buttons[selected]) { buttons[selected].setState(0); } // Select this button if (buttons[i]) { buttons[i].setState(2); } chart.fixedRange = range; // update the chart if (!baseAxis) { // axis not yet instanciated baseXAxisOptions = chart.options.xAxis; baseXAxisOptions[0] = merge( baseXAxisOptions[0], { range: range, min: rangeMin } ); rangeSelector.setSelected(i); } else { // existing axis object; after render time baseAxis.setExtremes( newMin, newMax, pick(redraw, 1), 0, { trigger: 'rangeSelectorButton', rangeSelectorButton: rangeOptions } ); rangeSelector.setSelected(i); } }, /** * Set the selected option. This method only sets the internal flag, it doesn't * update the buttons or the actual zoomed range. */ setSelected: function (selected) { this.selected = this.options.selected = selected; }, /** * The default buttons for pre-selecting time frames */ defaultButtons: [{ type: 'month', count: 1, text: '1m' }, { type: 'month', count: 3, text: '3m' }, { type: 'month', count: 6, text: '6m' }, { type: 'ytd', text: 'YTD' }, { type: 'year', count: 1, text: '1y' }, { type: 'all', text: 'All' }], /** * Initialize the range selector */ init: function (chart) { var rangeSelector = this, options = chart.options.rangeSelector, buttonOptions = options.buttons || [].concat(rangeSelector.defaultButtons), selectedOption = options.selected, blurInputs = rangeSelector.blurInputs = function () { var minInput = rangeSelector.minInput, maxInput = rangeSelector.maxInput; if (minInput) { minInput.blur(); } if (maxInput) { maxInput.blur(); } }; rangeSelector.chart = chart; rangeSelector.options = options; rangeSelector.buttons = []; chart.extraTopMargin = 35; rangeSelector.buttonOptions = buttonOptions; addEvent(chart.container, 'mousedown', blurInputs); addEvent(chart, 'resize', blurInputs); // Extend the buttonOptions with actual range each(buttonOptions, rangeSelector.computeButtonRange); // zoomed range based on a pre-selected button index if (selectedOption !== UNDEFINED && buttonOptions[selectedOption]) { this.clickButton(selectedOption, false); } // normalize the pressed button whenever a new range is selected addEvent(chart, 'load', function () { addEvent(chart.xAxis[0], 'afterSetExtremes', function () { rangeSelector.updateButtonStates(true); }); }); }, /** * Dynamically update the range selector buttons after a new range has been set */ updateButtonStates: function (updating) { var rangeSelector = this, chart = this.chart, baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, selected = rangeSelector.selected, buttons = rangeSelector.buttons; if (updating && chart.fixedRange !== mathRound(baseAxis.max - baseAxis.min)) { if (buttons[selected]) { buttons[selected].setState(0); } rangeSelector.setSelected(null); } each(rangeSelector.buttonOptions, function (rangeOptions, i) { var range = rangeOptions._range, // Disable buttons where the range exceeds what is allowed in the current view isTooGreatRange = range > dataMax - dataMin, // Disable buttons where the range is smaller than the minimum range isTooSmallRange = range < baseAxis.minRange, // Disable the All button if we're already showing all isAllButAlreadyShowingAll = rangeOptions.type === 'all' && baseAxis.max - baseAxis.min >= dataMax - dataMin && buttons[i].state !== 2, // Disable the YTD button if the complete range is within the same year isYTDButNotAvailable = rangeOptions.type === 'ytd' && dateFormat('%Y', dataMin) === dateFormat('%Y', dataMax); // The new zoom area happens to match the range for a button - mark it selected. // This happens when scrolling across an ordinal gap. It can be seen in the intraday // demos when selecting 1h and scroll across the night gap. if (range === mathRound(baseAxis.max - baseAxis.min) && i !== selected) { rangeSelector.setSelected(i); buttons[i].setState(2); } else if (isTooGreatRange || isTooSmallRange || isAllButAlreadyShowingAll || isYTDButNotAvailable) { buttons[i].setState(3); } else if (buttons[i].state === 3) { buttons[i].setState(0); } }); }, /** * Compute and cache the range for an individual button */ computeButtonRange: function (rangeOptions) { var type = rangeOptions.type, count = rangeOptions.count || 1, // these time intervals have a fixed number of milliseconds, as opposed // to month, ytd and year fixedTimes = { millisecond: 1, second: 1000, minute: 60 * 1000, hour: 3600 * 1000, day: 24 * 3600 * 1000, week: 7 * 24 * 3600 * 1000 }; // Store the range on the button object if (fixedTimes[type]) { rangeOptions._range = fixedTimes[type] * count; } else if (type === 'month' || type === 'year') { rangeOptions._range = { month: 30, year: 365 }[type] * 24 * 36e5 * count; } }, /** * Set the internal and displayed value of a HTML input for the dates * @param {String} name * @param {Number} time */ setInputValue: function (name, time) { var options = this.chart.options.rangeSelector; if (defined(time)) { this[name + 'Input'].HCTime = time; } this[name + 'Input'].value = dateFormat(options.inputEditDateFormat || '%Y-%m-%d', this[name + 'Input'].HCTime); this[name + 'DateBox'].attr({ text: dateFormat(options.inputDateFormat || '%b %e, %Y', this[name + 'Input'].HCTime) }); }, /** * Draw either the 'from' or the 'to' HTML input box of the range selector * @param {Object} name */ drawInput: function (name) { var rangeSelector = this, chart = rangeSelector.chart, chartStyle = chart.renderer.style, renderer = chart.renderer, options = chart.options.rangeSelector, lang = defaultOptions.lang, div = rangeSelector.div, isMin = name === 'min', input, label, dateBox, inputGroup = this.inputGroup; // Create the text label this[name + 'Label'] = label = renderer.label(lang[isMin ? 'rangeSelectorFrom' : 'rangeSelectorTo'], this.inputGroup.offset) .attr({ padding: 2 }) .css(merge(chartStyle, options.labelStyle)) .add(inputGroup); inputGroup.offset += label.width + 5; // Create an SVG label that shows updated date ranges and and records click events that // bring in the HTML input. this[name + 'DateBox'] = dateBox = renderer.label('', inputGroup.offset) .attr({ padding: 2, width: options.inputBoxWidth || 90, height: options.inputBoxHeight || 17, // docs stroke: options.inputBoxBorderColor || 'silver', 'stroke-width': 1 }) .css(merge({ textAlign: 'center', color: '#444' }, chartStyle, options.inputStyle)) .on('click', function () { rangeSelector[name + 'Input'].focus(); }) .add(inputGroup); inputGroup.offset += dateBox.width + (isMin ? 10 : 0); // Create the HTML input element. This is rendered as 1x1 pixel then set to the right size // when focused. this[name + 'Input'] = input = createElement('input', { name: name, className: PREFIX + 'range-selector', type: 'text' }, extend({ position: ABSOLUTE, border: 0, width: '1px', // Chrome needs a pixel to see it height: '1px', padding: 0, textAlign: 'center', fontSize: chartStyle.fontSize, fontFamily: chartStyle.fontFamily, top: chart.plotTop + PX // prevent jump on focus in Firefox }, options.inputStyle), div); // Blow up the input box input.onfocus = function () { css(this, { left: (inputGroup.translateX + dateBox.x) + PX, top: inputGroup.translateY + PX, width: (dateBox.width - 2) + PX, height: (dateBox.height - 2) + PX, border: '2px solid silver' }); }; // Hide away the input box input.onblur = function () { css(this, { border: 0, width: '1px', height: '1px' }); rangeSelector.setInputValue(name); }; // handle changes in the input boxes input.onchange = function () { var inputValue = input.value, value = (options.inputDateParser || Date.parse)(inputValue), xAxis = chart.xAxis[0], dataMin = xAxis.dataMin, dataMax = xAxis.dataMax; // If the value isn't parsed directly to a value by the browser's Date.parse method, // like YYYY-MM-DD in IE, try parsing it a different way if (isNaN(value)) { value = inputValue.split('-'); value = Date.UTC(pInt(value[0]), pInt(value[1]) - 1, pInt(value[2])); } if (!isNaN(value)) { // Correct for timezone offset (#433) if (!defaultOptions.global.useUTC) { value = value + new Date().getTimezoneOffset() * 60 * 1000; } // Validate the extremes. If it goes beyound the data min or max, use the // actual data extreme (#2438). if (isMin) { if (value > rangeSelector.maxInput.HCTime) { value = UNDEFINED; } else if (value < dataMin) { value = dataMin; } } else { if (value < rangeSelector.minInput.HCTime) { value = UNDEFINED; } else if (value > dataMax) { value = dataMax; } } // Set the extremes if (value !== UNDEFINED) { chart.xAxis[0].setExtremes( isMin ? value : xAxis.min, isMin ? xAxis.max : value, UNDEFINED, UNDEFINED, { trigger: 'rangeSelectorInput' } ); } } }; }, /** * Render the range selector including the buttons and the inputs. The first time render * is called, the elements are created and positioned. On subsequent calls, they are * moved and updated. * @param {Number} min X axis minimum * @param {Number} max X axis maximum */ render: function (min, max) { var rangeSelector = this, chart = rangeSelector.chart, renderer = chart.renderer, container = chart.container, chartOptions = chart.options, navButtonOptions = chartOptions.exporting && chartOptions.navigation && chartOptions.navigation.buttonOptions, options = chartOptions.rangeSelector, buttons = rangeSelector.buttons, lang = defaultOptions.lang, div = rangeSelector.div, inputGroup = rangeSelector.inputGroup, buttonTheme = options.buttonTheme, inputEnabled = options.inputEnabled !== false, states = buttonTheme && buttonTheme.states, plotLeft = chart.plotLeft, yAlign, buttonLeft; // create the elements if (!rangeSelector.rendered) { rangeSelector.zoomText = renderer.text(lang.rangeSelectorZoom, plotLeft, chart.plotTop - 20) .css(options.labelStyle) .add(); // button starting position buttonLeft = plotLeft + rangeSelector.zoomText.getBBox().width + 5; each(rangeSelector.buttonOptions, function (rangeOptions, i) { buttons[i] = renderer.button( rangeOptions.text, buttonLeft, chart.plotTop - 35, function () { rangeSelector.clickButton(i); rangeSelector.isActive = true; }, buttonTheme, states && states.hover, states && states.select ) .css({ textAlign: 'center' }) .add(); // increase button position for the next button buttonLeft += buttons[i].width + pick(options.buttonSpacing, 5); if (rangeSelector.selected === i) { buttons[i].setState(2); } }); rangeSelector.updateButtonStates(); // first create a wrapper outside the container in order to make // the inputs work and make export correct if (inputEnabled) { rangeSelector.div = div = createElement('div', null, { position: 'relative', height: 0, zIndex: 1 // above container }); container.parentNode.insertBefore(div, container); // Create the group to keep the inputs rangeSelector.inputGroup = inputGroup = renderer.g('input-group') .add(); inputGroup.offset = 0; rangeSelector.drawInput('min'); rangeSelector.drawInput('max'); } } if (inputEnabled) { // Update the alignment to the updated spacing box yAlign = chart.plotTop - 45; inputGroup.align(extend({ y: yAlign, width: inputGroup.offset, // detect collision with the exporting buttons x: navButtonOptions && (yAlign < (navButtonOptions.y || 0) + navButtonOptions.height - chart.spacing[0]) ? -40 : 0 }, options.inputPosition), true, chart.spacingBox); // Set or reset the input values rangeSelector.setInputValue('min', min); rangeSelector.setInputValue('max', max); } rangeSelector.rendered = true; }, /** * Destroys allocated elements. */ destroy: function () { var minInput = this.minInput, maxInput = this.maxInput, chart = this.chart, blurInputs = this.blurInputs, key; removeEvent(chart.container, 'mousedown', blurInputs); removeEvent(chart, 'resize', blurInputs); // Destroy elements in collections destroyObjectProperties(this.buttons); // Clear input element events if (minInput) { minInput.onfocus = minInput.onblur = minInput.onchange = null; } if (maxInput) { maxInput.onfocus = maxInput.onblur = maxInput.onchange = null; } // Destroy HTML and SVG elements for (key in this) { if (this[key] && key !== 'chart') { if (this[key].destroy) { // SVGElement this[key].destroy(); } else if (this[key].nodeType) { // HTML element discardElement(this[key]); } } this[key] = null; } } }; /** * Add logic to normalize the zoomed range in order to preserve the pressed state of range selector buttons */ Axis.prototype.toFixedRange = function (pxMin, pxMax, fixedMin, fixedMax) { var fixedRange = this.chart && this.chart.fixedRange, newMin = pick(fixedMin, this.translate(pxMin, true)), newMax = pick(fixedMax, this.translate(pxMax, true)), changeRatio = fixedRange && (newMax - newMin) / fixedRange; // If the difference between the fixed range and the actual requested range is // too great, the user is dragging across an ordinal gap, and we need to release // the range selector button. if (changeRatio > 0.7 && changeRatio < 1.3) { if (fixedMax) { newMin = newMax - fixedRange; } else { newMax = newMin + fixedRange; } } return { min: newMin, max: newMax }; }; // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'init', function () { if (this.options.rangeSelector.enabled) { this.rangeSelector = new RangeSelector(this); } }); proceed.call(this, options, callback); }); Highcharts.RangeSelector = RangeSelector; /* **************************************************************************** * End Range Selector code * *****************************************************************************/ Chart.prototype.callbacks.push(function (chart) { var extremes, scroller = chart.scroller, rangeSelector = chart.rangeSelector; function renderScroller() { extremes = chart.xAxis[0].getExtremes(); scroller.render(extremes.min, extremes.max); } function renderRangeSelector() { extremes = chart.xAxis[0].getExtremes(); if (!isNaN(extremes.min)) { rangeSelector.render(extremes.min, extremes.max); } } function afterSetExtremesHandlerScroller(e) { if (e.triggerOp !== 'navigator-drag') { scroller.render(e.min, e.max); } } function afterSetExtremesHandlerRangeSelector(e) { rangeSelector.render(e.min, e.max); } function destroyEvents() { if (scroller) { removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller); } if (rangeSelector) { removeEvent(chart, 'resize', renderRangeSelector); removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); } } // initiate the scroller if (scroller) { // redraw the scroller on setExtremes addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller); // redraw the scroller on chart resize or box resize wrap(chart, 'drawChartBox', function (proceed) { var isDirtyBox = this.isDirtyBox; proceed.call(this); if (isDirtyBox) { renderScroller(); } }); // do it now renderScroller(); } if (rangeSelector) { // redraw the scroller on setExtremes addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); // redraw the scroller chart resize addEvent(chart, 'resize', renderRangeSelector); // do it now renderRangeSelector(); } // Remove resize/afterSetExtremes at chart destroy addEvent(chart, 'destroy', destroyEvents); }); /** * A wrapper for Chart with all the default values for a Stock chart */ Highcharts.StockChart = function (options, callback) { var seriesOptions = options.series, // to increase performance, don't merge the data opposite, // Always disable startOnTick:true on the main axis when the navigator is enabled (#1090) navigatorEnabled = pick(options.navigator && options.navigator.enabled, true), disableStartOnTick = navigatorEnabled ? { startOnTick: false, endOnTick: false } : null, lineOptions = { marker: { enabled: false, radius: 2 }, // gapSize: 0, states: { hover: { lineWidth: 2 } } }, columnOptions = { shadow: false, borderWidth: 0 }; // apply X axis options to both single and multi y axes options.xAxis = map(splat(options.xAxis || {}), function (xAxisOptions) { return merge({ // defaults minPadding: 0, maxPadding: 0, ordinal: true, title: { text: null }, labels: { overflow: 'justify' }, showLastLabel: true }, xAxisOptions, // user options { // forced options type: 'datetime', categories: null }, disableStartOnTick ); }); // apply Y axis options to both single and multi y axes options.yAxis = map(splat(options.yAxis || {}), function (yAxisOptions) { opposite = pick(yAxisOptions.opposite, true); return merge({ // defaults labels: { y: -2 }, opposite: opposite, showLastLabel: false, title: { text: null } }, yAxisOptions // user options ); }); options.series = null; options = merge({ chart: { panning: true, pinchType: 'x' }, navigator: { enabled: true }, scrollbar: { enabled: true }, rangeSelector: { enabled: true }, title: { text: null, style: { fontSize: '16px' // docs } }, tooltip: { shared: true, crosshairs: true }, legend: { enabled: false }, plotOptions: { line: lineOptions, spline: lineOptions, area: lineOptions, areaspline: lineOptions, arearange: lineOptions, areasplinerange: lineOptions, column: columnOptions, columnrange: columnOptions, candlestick: columnOptions, ohlc: columnOptions } }, options, // user's options { // forced options _stock: true, // internal flag chart: { inverted: false } }); options.series = seriesOptions; return new Chart(options, callback); }; // Implement the pinchType option wrap(Pointer.prototype, 'init', function (proceed, chart, options) { var pinchType = options.chart.pinchType || ''; proceed.call(this, chart, options); // Pinch status this.pinchX = this.pinchHor = pinchType.indexOf('x') !== -1; this.pinchY = this.pinchVert = pinchType.indexOf('y') !== -1; this.hasZoom = this.hasZoom || this.pinchHor || this.pinchVert; }); // Override the automatic label alignment so that the first Y axis' labels // are drawn on top of the grid line, and subsequent axes are drawn outside wrap(Axis.prototype, 'autoLabelAlign', function (proceed) { if (this.chart.options._stock && this.coll === 'yAxis') { if (inArray(this, this.chart.yAxis) === 0) { if (this.options.labels.x === 15) { // default this.options.labels.x = 0; } return 'right'; } } return proceed.call(this); }); // Override getPlotLinePath to allow for multipane charts Axis.prototype.getPlotLinePath = function (value, lineWidth, old, force, translatedValue) { var axis = this, series = (this.isLinked && !this.series ? this.linkedParent.series : this.series), chart = axis.chart, renderer = chart.renderer, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, result = [], axes, axes2, uniqueAxes; // Get the related axes based on series axes = (axis.isXAxis ? (defined(axis.options.yAxis) ? [chart.yAxis[axis.options.yAxis]] : map(series, function (S) { return S.yAxis; }) ) : (defined(axis.options.xAxis) ? [chart.xAxis[axis.options.xAxis]] : map(series, function (S) { return S.xAxis; }) ) ); // Get the related axes based options.*Axis setting #2810 axes2 = (axis.isXAxis ? chart.yAxis : chart.xAxis); each(axes2, function (A) { if (defined(A.options.id) ? A.options.id.indexOf('navigator') === -1 : true) { var a = (A.isXAxis ? 'yAxis' : 'xAxis'), rax = (defined(A.options[a]) ? chart[a][A.options[a]] : chart[a][0]); if (axis === rax) { axes.push(A); } } }); // Remove duplicates in the axes array. If there are no axes in the axes array, // we are adding an axis without data, so we need to populate this with grid // lines (#2796). uniqueAxes = axes.length ? [] : [axis]; each(axes, function (axis2) { if (inArray(axis2, uniqueAxes) === -1) { uniqueAxes.push(axis2); } }); translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); if (!isNaN(translatedValue)) { if (axis.horiz) { each(uniqueAxes, function (axis2) { y1 = axis2.top; y2 = y1 + axis2.len; x1 = x2 = mathRound(translatedValue + axis.transB); if ((x1 >= axisLeft && x1 <= axisLeft + axis.width) || force) { result.push('M', x1, y1, 'L', x2, y2); } }); } else { each(uniqueAxes, function (axis2) { x1 = axis2.left; x2 = x1 + axis2.width; y1 = y2 = mathRound(axisTop + axis.height - translatedValue); if ((y1 >= axisTop && y1 <= axisTop + axis.height) || force) { result.push('M', x1, y1, 'L', x2, y2); } }); } } if (result.length > 0) { return renderer.crispPolyLine(result, lineWidth || 1); } }; // Override getPlotBandPath to allow for multipane charts Axis.prototype.getPlotBandPath = function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from), result = [], i; if (path && toPath) { // Go over each subpath for (i = 0; i < path.length; i += 6) { result.push('M', path[i + 1], path[i + 2], 'L', path[i + 4], path[i + 5], toPath[i + 4], toPath[i + 5], toPath[i + 1], toPath[i + 2]); } } else { // outside the axis area result = null; } return result; }; // Function to crisp a line with multiple segments SVGRenderer.prototype.crispPolyLine = function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line var i; for (i = 0; i < points.length; i = i + 6) { if (points[i + 1] === points[i + 4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[i + 1] = points[i + 4] = mathRound(points[i + 1]) - (width % 2 / 2); } if (points[i + 2] === points[i + 5]) { points[i + 2] = points[i + 5] = mathRound(points[i + 2]) + (width % 2 / 2); } } return points; }; if (Renderer === Highcharts.VMLRenderer) { VMLRenderer.prototype.crispPolyLine = SVGRenderer.prototype.crispPolyLine; } // Wrapper to hide the label wrap(Axis.prototype, 'hideCrosshair', function (proceed, i) { proceed.call(this, i); if (!defined(this.crossLabelArray)) { return; } if (defined(i)) { if (this.crossLabelArray[i]) { this.crossLabelArray[i].hide(); } } else { each(this.crossLabelArray, function (crosslabel) { crosslabel.hide(); }); } }); // Wrapper to draw the label wrap(Axis.prototype, 'drawCrosshair', function (proceed, e, point) { // Draw the crosshair proceed.call(this, e, point); // Check if the label has to be drawn if (!defined(this.crosshair.label) || !this.crosshair.label.enabled || !defined(point)) { return; } var chart = this.chart, options = this.options.crosshair.label, // the label's options axis = this.isXAxis ? 'x' : 'y', // axis name horiz = this.horiz, // axis orientation opposite = this.opposite, // axis position left = this.left, // left position top = this.top, // top position crossLabel = this.crossLabel, // reference to the svgElement posx, posy, crossBox, formatOption = options.format, formatFormat = '', limit; // If the label does not exist yet, create it. if (!crossLabel) { crossLabel = this.crossLabel = chart.renderer.label() .attr({ align: options.align || (horiz ? 'center' : opposite ? (this.labelAlign === 'right' ? 'right' : 'left') : (this.labelAlign === 'left' ? 'left' : 'center')), zIndex: 12, height: horiz ? 16 : UNDEFINED, fill: options.backgroundColor || (this.series[0] && this.series[0].color) || 'gray', padding: pick(options.padding, 2), stroke: options.borderColor || null, 'stroke-width': options.borderWidth || 0 }) .css(extend({ color: 'white', fontWeight: 'normal', fontSize: '11px', textAlign: 'center' }, options.style)) .add(); } if (horiz) { posx = point.plotX + left; posy = top + (opposite ? 0 : this.height); } else { posx = opposite ? this.width + left : 0; posy = point.plotY + top; } // if the crosshair goes out of view (too high or too low, hide it and hide the label) if (posy < top || posy > top + this.height) { this.hideCrosshair(); return; } // TODO: Dynamic date formats like in Series.tooltipHeaderFormat. if (!formatOption && !options.formatter) { if (this.isDatetimeAxis) { formatFormat = '%b %d, %Y'; } formatOption = '{value' + (formatFormat ? ':' + formatFormat : '') + '}'; } // show the label crossLabel.attr({ text: formatOption ? format(formatOption, {value: point[axis]}) : options.formatter.call(this, point[axis]), x: posx, y: posy, visibility: VISIBLE }); crossBox = crossLabel.getBBox(); // now it is placed we can correct its position if (horiz) { if (((this.options.tickPosition === 'inside') && !opposite) || ((this.options.tickPosition !== 'inside') && opposite)) { posy = crossLabel.y - crossBox.height; } } else { posy = crossLabel.y - (crossBox.height / 2); } // check the edges if (horiz) { limit = { left: left - crossBox.x, right: left + this.width - crossBox.x }; } else { limit = { left: this.labelAlign === 'left' ? left : 0, right: this.labelAlign === 'right' ? left + this.width : chart.chartWidth }; } // left edge if (crossLabel.translateX < limit.left) { posx += limit.left - crossLabel.translateX; } // right edge if (crossLabel.translateX + crossBox.width >= limit.right) { posx -= crossLabel.translateX + crossBox.width - limit.right; } // show the crosslabel crossLabel.attr({x: posx, y: posy, visibility: VISIBLE}); }); /* **************************************************************************** * Start value compare logic * *****************************************************************************/ var seriesInit = seriesProto.init, seriesProcessData = seriesProto.processData, pointTooltipFormatter = Point.prototype.tooltipFormatter; /** * Extend series.init by adding a method to modify the y value used for plotting * on the y axis. This method is called both from the axis when finding dataMin * and dataMax, and from the series.translate method. */ seriesProto.init = function () { // Call base method seriesInit.apply(this, arguments); // Set comparison mode this.setCompare(this.options.compare); }; /** * The setCompare method can be called also from the outside after render time */ seriesProto.setCompare = function (compare) { // Set or unset the modifyValue method this.modifyValue = (compare === 'value' || compare === 'percent') ? function (value, point) { var compareValue = this.compareValue; if (value !== UNDEFINED) { // #2601 // get the modified value value = compare === 'value' ? value - compareValue : // compare value value = 100 * (value / compareValue) - 100; // compare percent // record for tooltip etc. if (point) { point.change = value; } } return value; } : null; // Mark dirty if (this.chart.hasRendered) { this.isDirty = true; } }; /** * Extend series.processData by finding the first y value in the plot area, * used for comparing the following values */ seriesProto.processData = function () { var series = this, i = 0, processedXData, processedYData, length; // call base method seriesProcessData.apply(this, arguments); if (series.xAxis && series.processedYData) { // not pies // local variables processedXData = series.processedXData; processedYData = series.processedYData; length = processedYData.length; // find the first value for comparison for (; i < length; i++) { if (typeof processedYData[i] === NUMBER && processedXData[i] >= series.xAxis.min) { series.compareValue = processedYData[i]; break; } } } }; /** * Modify series extremes */ wrap(seriesProto, 'getExtremes', function (proceed) { proceed.call(this); if (this.modifyValue) { this.dataMax = this.modifyValue(this.dataMax); this.dataMin = this.modifyValue(this.dataMin); } }); /** * Add a utility method, setCompare, to the Y axis */ Axis.prototype.setCompare = function (compare, redraw) { if (!this.isXAxis) { each(this.series, function (series) { series.setCompare(compare); }); if (pick(redraw, true)) { this.chart.redraw(); } } }; /** * Extend the tooltip formatter by adding support for the point.change variable * as well as the changeDecimals option */ Point.prototype.tooltipFormatter = function (pointFormat) { var point = this; pointFormat = pointFormat.replace( '{point.change}', (point.change > 0 ? '+' : '') + numberFormat(point.change, pick(point.series.tooltipOptions.changeDecimals, 2)) ); return pointTooltipFormatter.apply(this, [pointFormat]); }; /* **************************************************************************** * End value compare logic * *****************************************************************************/ /** * Extend the Series prototype to create a separate series clip box. This is related * to using multiple panes, and a future pane logic should incorporate this feature. */ wrap(Series.prototype, 'render', function (proceed) { if (this.isCartesian && this.chart.options._stock) { // #2939 // First render, initial clip box if (!this.clipBox) { this.clipBox = merge(this.chart.clipBox); this.clipBox.width = this.xAxis.len; this.clipBox.height = this.yAxis.len; // On redrawing, resizing etc, update the clip rectangle } else if (this.chart[this.sharedClipKey]) { this.chart[this.sharedClipKey].attr({ width: this.xAxis.len, height: this.yAxis.len }); } } proceed.call(this); }); // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { 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; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, noop = helpers.noop, isScheduler = helpers.isScheduler, observableFromPromise = Observable.fromPromise, slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var argumentOutOfRange = 'Argument out of range'; function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver() { __super__.apply(this, arguments); } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new Error(argumentOutOfRange); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = 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 () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; return Rx; }));
montageDefine("6364dae","core/range-controller",{dependencies:["montage","core/promise","collections/generic-collection"],factory:function(require,exports,module){var Montage = require("montage").Montage; var Promise = require("core/promise").Promise; var GenericCollection = require("collections/generic-collection"); // The content controller is responsible for determining which content from a // source collection are visible, their order of appearance, and whether they // are selected. Multiple repetitions may share a single content controller // and thus their selection state. // The controller manages a series of visible iterations. Each iteration has a // corresponding "object" and whether that iteration is "selected". The // controller uses a bidirectional binding to ensure that the controller's // "selections" collection and the "selected" property of each iteration are in // sync. // The controller can determine which content to display and the order in which // to render them in a variety of ways. You can either use a "selector" to // filter and sort the content or use a "visibleIndexes" array. The controller // binds the content of "organizedContent" depending on which strategy you use. // // The content of "organizedContent" is then reflected with corresponding // incremental changes to "iterations". The "iterations" array will always // have an "iteration" corresponding to the "object" in "organizedContent" at // the same position. /** * A <code>RangeController</code> receives a <code>content</code> collection, * manages what portition of that content is visible and the order of its * appearance (<code>organizedContent</code>), and projects changes to the the * organized content into an array of iteration controllers * (<code>iterations</code>, containing instances of <code>Iteration</code>). * * The <code>RangeController</code> provides a variety of knobs for how to * project the content into the organized content, all of which are optional, * and the default behavior is to preserve the content and its order. You can * use the bindings path expression language (from FRB) to determine the * <code>sortPath</code> and <code>filterPath</code>. There is a * <code>reversed</code> flag to invert the order of appearance. The * <code>visibleIndexes</code> property will pluck values from the sorted and * filtered content by position, in arbitrary order. The <code>start</code> * and <code>length</code> properties manage a sliding window into the content. * * The <code>RangeController</code> is also responsible for managing which * content is selected and provides a variety of knobs for that purpose. */ var RangeController = exports.RangeController = Montage.specialize( { /** * @private */ constructor: { value: function RangeController() { this.content = null; this._selection = []; this.selection = []; this.defineBinding("_selection.rangeContent()", { "<->": "selection.rangeContent()" }); this.sortPath = null; this.filterPath = null; this.visibleIndexes = null; this.reversed = false; this.start = null; this.length = null; this.selectAddedContent = false; this.deselectInvisibleContent = false; this.clearSelectionOnOrderChange = false; this.avoidsEmptySelection = false; this.multiSelect = false; // The following establishes a pipeline for projecting the // underlying content into organizedContent. The filterPath, // sortedPath, reversed, and visibleIndexes are all optional stages // in that pipeline and used if non-null and in that order. // The _orderedContent variable is a necessary intermediate stage // From which visibleIndexes plucks visible values. this.organizedContent = []; this.organizedContent.addRangeChangeListener(this, "organizedContent"); this.defineBinding("_orderedContent", { "<-": "content" + ".($filterPath.defined() ? filter{path($filterPath)} : ())" + ".($sortPath.defined() ? sorted{path($sortPath)} : ())" + ".($reversed ?? 0 ? reversed() : ())" }); this.defineBinding("organizedContent.rangeContent()", { "<-": "_orderedContent.(" + "$visibleIndexes.defined() ?" + "$visibleIndexes" + ".filter{<$_orderedContent.length}" + ".map{$_orderedContent[()]}" + " : ()" + ").(" + "$start.defined() && $length.defined() ?" + "view($start, $length)" + " : ()" + ")" }); this._selection.addRangeChangeListener(this, "selection"); this.addRangeAtPathChangeListener("content", this, "handleContentRangeChange"); this.addPathChangeListener("sortPath", this, "handleOrderChange"); this.addPathChangeListener("reversed", this, "handleOrderChange"); this.addOwnPropertyChangeListener("multiSelect", this); this.iterations = []; } }, /** * Initializes a range controller with a backing collection. * @param content Any collection that produces range change events, like an * <code>Array</code> or <code>SortedSet</code>. * @returns this */ initWithContent: { value: function (content) { this.content = content; return this; } }, // Organizing Content // ------------------ /** * An FRB expression that determines how to sort the content, like "name" * to sort by name. If the <code>sortPath</code> is null, the content * is not sorted. */ sortPath: {value: null}, /** * Whether to reverse the order of the sorted content. */ reversed: {value: null}, /** * An FRB expression that determines how to filter content like * "name.startsWith('A')" to see only names starting with 'A'. If the * <code>filterPath</code> is null, all content is accepted. */ filterPath: {value: null}, /** * An array of indexes to pluck from the ordered and filtered content. The * output will be an array of the corresponding content. If the * <code>visibleIndexes</code> is null, all content is accepted. */ visibleIndexes: {value: null}, /** * The first index of a sliding window over the content, suitable for * binding (indirectly) to the scroll offset of a large list. * If <code>start</code> or <code>length</code> is null, all content is * accepted. */ start: {value: null}, /** * The length of a sliding window over the content, suitable for binding * (indirectly) to the scroll height. * If <code>start</code> or <code>length</code> is null, all content is * accepted. */ length: {value: null}, // Managing Selection // ------------------ /** * Whether to select new content automatically. * * Off by default. */ selectAddedContent: {value: false}, // TODO make this work /** * Whether to automatically deselect content that disappears from the * <code>organizedContent</code>. * * Off by default. */ deselectInvisibleContent: {value: false}, /** * Whether to automatically clear the selection whenever the * <code>sortPath</code>, <code>filterPath</code>, or <code>reversed</code> * knobs change. * * Off by default. */ clearSelectionOnOrderChange: {value: false}, /** * Whether to automatically reselect a value if it is the last value * removed from the selection. * * Off by default. */ avoidsEmptySelection: {value: false}, /** * Whether to automatically deselect all previously selected content when a * new selection is made. * * Off by default. */ multiSelect: {value: false}, // Properties managed by the controller // ------------------------------------ /** * The content after it has been sorted, reversed, and filtered, suitable * for plucking visible indexes and/or then the sliding window. * @private */ _orderedContent: {value: null}, /** * An array incrementally projected from <code>content</code> through sort, * reversed, filter, visibleIndexes, start, and length. */ organizedContent: {value: null}, /** * An array of iterations corresponding to each of the values in * <code>organizedContent</code>, providing an interface for getting or * setting whether each is selected. */ iterations: {value: null}, /** * A subset of the <code>content</code> that are selected. The user may * safely reassign this property and all iterations will react to the * change. The selection may be <code>null</code>. The selection may be * any collection that supports range change events like <code>Array</code> * or <code>SortedSet</code>. */ selection: {value: null}, /** * Because the user can replace the selection object, we use a range * content change listener on a hidden selection array that tracks the * actual selection. * @private */ _selection: {value: null}, /** * A managed interface for adding values to the selection, accounting for * <code>multiSelect</code>. * You can however directly manipulate the selection, but that will update * the selection asynchronously because the controller cannot change the * selection while handling a selection change event. */ select: { value: function (value) { if (!this.multiSelect && this._selection.length >= 1) { this._selection.clear(); } this._selection.add(value); } }, /* * A managed interface for removing values from the selection, accounting * for <code>avoidsEmptySelection</code>. * You can however directly manipulate the selection, but that will update * the selection asynchronously because the controller cannot change the * selection while handling a selection change event. */ deselect: { value: function (value) { if (!this.avoidsEmptySelection || this._selection.length > 1) { this._selection["delete"](value); } } }, /* * A managed interface for clearing the selection, accounting for * <code>avoidsEmptySelection</code>. * You can however directly manipulate the selection, but that will update * the selection asynchronously because the controller cannot change the * selection while handling a selection change event. */ clearSelection: { value: function () { if (!this.avoidsEmptySelection || this._selection.length > 1) { this._selection.clear(); } } }, /** * Proxies adding content to the underlying collection, accounting for * <code>selectAddedContent</code>. * @param value * @returns whether the value was added */ add: { value: function (value) { var result; if (!this.content) { this.content = []; } result = this.content.add(value); if (result) { this.handleAdd(value); } return result; } }, /** * Proxies pushing content to the underlying collection, accounting for * <code>selectAddedContent</code>. * @param ...values * @returns whether the value was added */ push: { value: function () { var result = this.content.push.apply(this.content, arguments); for (var index = 0; index < arguments.length; index++) { this.handleAdd(arguments[index]); } return result; } }, /** * Proxies popping content from the underlying collection. * @returns the popped values */ pop: { value: function () { return this.content.pop(); } }, /** * Proxies shifting content from the underlying collection. * @returns the shifted values */ shift: { value: function () { return this.content.shift(); } }, /** * Proxies unshifting content to the underlying collection, accounting for * <code>selectAddedContent</code>. * @param ...values * @returns whether the value was added */ unshift: { value: function () { var result = this.content.unshift.apply(this.content, arguments); for (var index = 0; index < arguments.length; index++) { this.handleAdd(arguments[index]); } return result; } }, /** * Proxies splicing values into the underlying collection. Accounts for * <code>selectAddedContent</code> */ splice: { value: function () { var result = this.content.splice.apply(this.content, arguments); for (var index = 2; index < arguments.length; index++) { this.handleAdd(arguments[index]); } return result; } }, /** * Proxies swapping values in the underlying collection. Accounts for * <code>selectAddedContent</code> */ swap: { value: function (index, length, values) { var result = this.content.splice.apply(this.content, values); for (var index = 2; index < values.length; index++) { this.handleAdd(values[index]); } return result; } }, /** * Proxies deleting content from the underlying collection. */ "delete": { value: function (value) { return this.content["delete"](value); } }, has: { value: function(value) { if (this.content) { return this.content.has(value); } else { return false; } } }, /** * Proxies adding each value into the underlying collection. */ addEach: { value: GenericCollection.prototype.addEach }, /** * Proxies deleting each value out from the underlying collection. */ deleteEach: { value: GenericCollection.prototype.deleteEach }, /** * Proxies clearing the underlying content collection. */ clear: { value: function () { this.content.clear(); } }, /** * Creates content and adds it to the controller and its backing * collection. Uses `add` and `contentConstructor`. */ addContent: { value: function () { var content = new this.contentConstructor(); this.add(content); return content; } }, _contentConstructor: { value: null }, /** * Creates a content value for this range controller. If the backing * collection has an intrinsict type, uses its `contentConstructor`. * Otherwise, creates and returns simple, empty objects. * * This property can be set to an alternate content constructor, which will * take precedence over either of the above defaults. */ contentConstructor: { get: function () { if (this._contentConstructor) { return this._contentConstructor; } else if (this.content && this.content.contentConstructor) { return this.content.contentConstructor; } else { return Object; } }, set: function (contentConstructor) { this._contentConstructor = contentConstructor; } }, /** * Dispatched by range changes to the controller's content, arranged in * constructor. Reacts to content changes to ensure that content that no * longer exists is removed from the selection, regardless of whether it is * from the user or any other entity modifying the backing collection. * @private */ handleContentRangeChange: { value: function (plus, minus, index) { // remove all values from the selection that were removed (but // not added back) minus.deleteEach(plus); this._selection.deleteEach(minus); } }, /** * Dispatched by a range-at-path change listener on the selection, arragned * in constructor. Reacts to managed (as by the select or deselect methods) * or unmanaged changes to the selection by enforcing the * <code>avoidsEmptySelection</code> and * <code>multiSelect</code> invariants. However, it must * schedule these changes for a separate event because it cannot interfere * with the change operation in progress. * @private */ handleSelectionRangeChange: { value: function (plus, minus, index) { var self = this; Promise.nextTick(function () { var length = self._selection.length; // Performing these in next tick avoids interfering with the // plan in the dispatcher, highlighting the fact that there is // a plan interference hazard inherent to the present // implementation of collection event dispatch. if (self.avoidsEmptySelection && length === 0) { self.select(minus[minus.length - 1]); } else if (!self.multiSelect && length > 1) { self._selection.splice(0, self._selection.length, plus[plus.length - 1]); } }); } }, /** * Dispatched by a range-at-path change listener arranged in constructor. * Synchronizes the <code>iterations</code> with changes to * <code>organizedContent</code>. Also manages the * <code>deselectInvisibleContent</code> invariant. * @private */ handleOrganizedContentRangeChange: { value: function (plus, minus, index) { if (this.deselectInvisibleContent) { var diff = minus.clone(1); diff.deleteEach(plus); this._selection.deleteEach(minus); } } }, /** * Dispatched by changes to sortPath, filterPath, and reversed to maintain * the <code>clearSelectionOnOrderChange</code> invariant. * @private */ handleOrderChange: { value: function () { if (this.clearSelectionOnOrderChange) { this._selection.clear(); } } }, /** * Dispatched manually by all of the managed methods for adding values to * the underlying content, like <code>add</code> and <code>push</code>, to * support <code>multiSelect</code>. * @private */ handleAdd: { value: function (value) { if (this.selectAddedContent) { if ( !this.multiSelect && this._selection.length >= 1 ) { this._selection.clear(); } this._selection.add(value); } } }, handleMultiSelectChange: { value: function() { var length = this._selection.length; if (!this.multiSelect && length > 1) { this._selection.splice(0, length - 1); } } } }, { blueprintModuleId:require("montage")._blueprintModuleIdDescriptor, blueprint:require("montage")._blueprintDescriptor }); // TODO @kriskowal scrollIndex, scrollDelegate -> scrollDelegate.scrollBy(offset) // TODO multiSelectWithModifiers to support ctrl/command/shift selection such // that individual values and ranges of values. // TODO @kriskowal decouple such that content controllers can be chained using // adapter pattern }}) ; //*/ montageDefine("6364dae","composer/composer",{dependencies:["montage","core/target"],factory:function(require,exports,module){/** * @module montage/composer/composer * @requires montage/core/core */ var Montage = require("montage").Montage, Target = require("core/target").Target; /** * @class Composer * @extends Target * @summary The Composer prototype is the base class for all composers in Montage. There are two types of composers. One type, called _gesture_ composers listen for and aggregrate low-level events into higher order events (for example, [PressComposer]{@link PressComposer}. The second type of composer is called _calculation_ composers */ exports.Composer = Target.specialize( /** @lends Composer# */ { _component: { value: null }, /** The Montage component that the composer will listen for mouse events on. @type {Component} @default null */ component: { get: function() { return this._component; }, set: function(component) { this._component = component; } }, _element: { value: null }, /** The DOM element that the composer will listen for events on. If no element is specified then the composer will use the element associated with its <code>component</code> property. @type {Component} @default null */ element: { get: function() { return this._element; }, set: function(element) { this._element = element; } }, /** * This property controls when a composer's <code>load()</code> method is called, which is where the composer create event listeners. If `false` * the composer's <code>load()</code> method is called immediately as part of the next draw * cycle after <code>addComposer()</code> has been called on its associated component. If * `true`, the loading of the composer is delayed until its associated component * has had its <code>prepareForActivationEvents()</code> called. Delaying the creation of event listeners until necessary can improve performance. * @default false */ lazyLoad: { value: false }, _needsFrame: { value: false }, /** This property should be set to 'true' when the composer wants to have its <code>frame()</code> method executed during the next draw cycle.Setting this property to 'true' will cause Montage to schedule a new draw cycle if one has not already been. @type {boolean} @default false */ needsFrame: { set: function(value) { if (this._needsFrame !== value) { this._needsFrame = value; if (this._component) { if (value) { this._component.scheduleComposer(this); } } } }, get: function() { return this._needsFrame; } }, /** This method will be invoked by the framework at the beginning of a draw cycle. This is where a composer implement its update logic. @function @param {Date} timestamp The time that the draw cycle started */ frame: { value: function(timestamp) { } }, /* Invoked by the framework to default the composer's element to the component's element if necessary. @private */ _resolveDefaults: { value: function() { if (this.element == null && this.component != null) { this.element = this.component.element; } } }, /* Invoked by the framework to load this composer @private */ _load: { value: function() { if (!this.element) { this._resolveDefaults(); } this.load(); } }, /** Called when a composer should be loaded. Any event listeners that the composer needs to install should be installed in this method. @function */ load: { value: function() { } }, /** Called when a component removes a composer. Any event listeners that the composer needs to remove should be removed in this method and any additional cleanup should be performed. @function */ unload: { value: function() { } }, /* Called when a composer is part of a template serialization. It's responsible for calling addComposer on the component. @private */ deserializedFromTemplate: { value: function() { if (this.component) { this.component.addComposer(this); } } } }); }}) ; //*/ montageDefine("5bf8252","ui/native-control",{dependencies:["montage/ui/component"],factory:function(require,exports,module){/** @module montage/ui/native-control */ var Component = require("montage/ui/component").Component; /** Base component for all native components, such as RadioButton and Checkbox. @class module:montage/ui/native-control.NativeControl @extends module:montage/ui/component.Component */ var NativeControl = exports.NativeControl = Component.specialize(/** @lends module:montage/ui/native-control.NativeControl# */ { hasTemplate: { value: false }, willPrepareForDraw: { value: function() { } } }); //http://www.w3.org/TR/html5/elements.html#global-attributes NativeControl.addAttributes( /** @lends module:montage/ui/native-control.NativeControl# */ { /** Specifies the shortcut key(s) that gives focuses to or activates the element. @see {@link http://www.w3.org/TR/html5/editing.html#the-accesskey-attribute} @type {string} @default null */ accesskey: null, /** Specifies if the content is editable or not. Valid values are "true", "false", and "inherit". @see {@link http://www.w3.org/TR/html5/editing.html#contenteditable} @type {string} @default null */ contenteditable: null, /** Specifies the ID of a <code>menu</code> element in the DOM to use as the element's context menu. @see {@link http://www.w3.org/TR/html5/interactive-elements.html#attr-contextmenu} @type {string} @default null */ contextmenu: null, /** Specifies the elements element's text directionality. Valid values are "ltr", "rtl", and "auto". @see {@link http://www.w3.org/TR/html5/elements.html#the-dir-attribute} @type {string} @default null */ dir: null, /** Specifies if the element is draggable. Valid values are "true", "false", and "auto". @type {string} @default null @see {@link http://www.w3.org/TR/html5/dnd.html#the-draggable-attribute} */ draggable: null, /** Specifies the behavior that's taken when an item is dropped on the element. Valid values are "copy", "move", and "link". @type {string} @see {@link http://www.w3.org/TR/html5/dnd.html#the-dropzone-attribute} */ dropzone: null, /** When specified on an element, it indicates that the element should not be displayed. @type {boolean} @default false */ hidden: {dataType: 'boolean'}, //id: null, /** Specifies the primary language for the element's contents and for any of the element's attributes that contain text. @type {string} @default null @see {@link http://www.w3.org/TR/html5/elements.html#attr-lang} */ lang: null, /** Specifies if element should have its spelling and grammar checked by the browser. Valid values are "true", "false". @type {string} @default null @see {@link http://www.w3.org/TR/html5/editing.html#attr-spellcheck} */ spellcheck: null, /** The CSS styling attribute. @type {string} @default null @see {@link http://www.w3.org/TR/html5/elements.html#the-style-attribute} */ style: null, /** Specifies the relative order of the element for the purposes of sequential focus navigation. @type {number} @default null @see {@link http://www.w3.org/TR/html5/editing.html#attr-tabindex} */ tabindex: null, /** Specifies advisory information about the element, used as a tooltip when hovering over the element, and other purposes. @type {string} @default null @see {@link http://www.w3.org/TR/html5/elements.html#the-title-attribute} */ title: null }); }}) ; //*/ montageDefine("262b1a4","package.json",{exports: {"name":"matte","version":"0.1.3","repository":{"type":"git","url":"https://github.com/montagejs/matte.git"},"dependencies":{"montage":"~0.13.0","native":"~0.1.1"},"devDependencies":{"montage-testing":"~0.2.0"},"exclude":["overview.html","overview","run-tests.html","test"],"readme":"matte\n==============\n\nThis is the Montage package template.\n\nNote: Before working on your package you will need to add montage to it.\n\n```\nnpm install .\n```\n\nLayout\n------\n\nThe template contains the following files and directories:\n\n* `ui/` – Directory containing all the UI .reel directories.\n* `package.json` – Describes your app and its dependencies\n* `README.md` – This readme. Replace the current content with a description of your app\n* `overview.html`\n* `overview/` – Directory that contains the files for the overview page. This is a different package so you will need to require the component using matte/*.\n * `main.reel` – The main interface component where you can add the components to show.\n* `node_modules/` – Directory containing all npm packages needed, including Montage. Any packages here must be included as `dependencies` in `package.json` for the Montage require to find them.\n* `test/` – Directory containing tests for your package.\n * `all.js` – Module that point the test runner to all your jasmine specs.\n* `run-tests.html` – Page to run jasmine tests manually in your browser\n* `testacular.conf.js` – This is the testacular configuration file. You can start testacular by running `node_modules/testacular/bin/testacular start`\n\nCreate the following directories if you need them:\n\n* `locale/` – Directory containing localized content.\n* `scripts/` – Directory containing other JS libraries. If a library doesn’t support the CommonJS \"exports\" object it will need to be loaded through a `<script>` tag.\n\n","readmeFilename":"README.md","description":"matte ==============","bugs":{"url":"https://github.com/montagejs/matte/issues"},"_id":"matte@0.1.3","_from":"matte@~0.1.3","directories":{"lib":"./"},"hash":"262b1a4","mappings":{"montage":{"name":"montage","hash":"6364dae","location":"../montage@6364dae/"},"native":{"name":"native","hash":"5bf8252","location":"../native@5bf8252/"}},"production":true,"useScriptInjection":true}}) ; //*/ montageDefine("5bf8252","ui/input-checkbox.reel/input-checkbox",{dependencies:["ui/check-input"],factory:function(require,exports,module){/** @module "montage/ui/native/input-checkbox.reel" @requires montage/core/core @requires montage/ui/check-input */ var CheckInput = require("ui/check-input").CheckInput; /** @class module:"montage/ui/native/input-checkbox.reel".InputCheckbox @extends module:montage/ui/check-input.CheckInput */ var InputCheckbox = exports.InputCheckbox = CheckInput.specialize({ }); InputCheckbox.addAttributes( /** @lends module:"montage/ui/native/input-checkbox.reel".InputCheckbox# */ { /** Specifies if the checkbox control should receive focus when the document loads. Because Montage components are loaded asynchronously after the document has loaded, setting this property has no effect on the element's focus state. @type {boolean} @default false */ autofocus: {value: false, dataType: 'boolean'}, /** Specifies if the checkbox control is disabled. @type {boolean} @default false */ disabled: {value: false, dataType: 'boolean'}, /** Specifies if the checkbox is in it checked state or not. @type {boolean} @default false */ checked: {value: false, dataType: 'boolean'}, /** The value of the id attribute of the form with which to associate the element. @type {string} @default null */ form: null, /** The name part of the name/value pair associated with this element for the purposes of form submission. @type {string} @default null */ name: null, /** Specifies if this control is readonly. @type {boolean} @default false */ readonly: {value: false, dataType: 'boolean'}, /** A string the browser displays in a tooltip when the user hovers their mouse over the element. @type {string} @default null */ title: null, /* The value associated with the checkbox. Per the WC3 specification, if the element has a <code>value</code> attribute then the value of that attribute's value is returned; otherwise, it returns "on". @type {string} @default "on" */ value: {value: 'on'} }); }}) bundleLoaded("index.html.bundle-1-0.js")
import React from 'react'; import { browserHistory} from 'react-router'; import DeleteNotification from '../containers/DeleteNotification'; import AttackDetails from '../containers/AttackDetails'; import axios from 'axios'; export default class AttackInspection extends React.Component { constructor() { super(); this.state = { showNotification: false, attack: {}, button: 'Pause' }; } toggleVictim = (deleted) => { axios.patch('/breach/victim/' + this.props.params.victim_id + '/', { victim_id: this.props.params.victim_id, deleted: deleted }) .then(res => { console.log(res); }) .catch(error => { console.log(error); }); } handleVictimState(button){ if (button === 'Pause') { this.setState({ button: 'Attack' }); } else { this.setState({ button: 'Pause' }); } axios.patch('/breach/victim/' + this.props.attack.id + '/', { victim_id: this.props.attack.id, state: this.state.attackState }) .then(res => { console.log(res) }) .catch(error => { console.log(error); }); } handleClick = () => { this.setState({ showNotification: true }); this.toggleVictim(true); setTimeout(() => { this.setState({ showNotification: false }); browserHistory.push('/');}, 3000); } onUndo = () => { this.setState({ showNotification: false }); this.toggleVictim(false); } onVerify = () => { this.setState({ showNotification: false }); browserHistory.push('/'); } getVictimDetails = () => { axios.get('/breach/victim/' + this.props.params.victim_id) .then(res => { this.setState({ attack: res.data }); }) .catch(error => { console.log(error); }); } componentWillMount = () => { this.getVictimDetails(); } render() { let attack = this.state.attack return( <div className='container'> <AttackDetails attack={ this.state.attack }/> <div className='deletepause'> <button type='button' className='btn btn-danger serialmargin' onClick={ () => this.handleClick(attack.id) }>Delete</button> { this.state.showNotification ? <DeleteNotification onUndo={ () => this.onUndo(attack.id) } onClose={ this.onVerify } /> : null } <button type='button' className='btn btn-primary serialmargin' onClick={ () => this.handleVictimState(this.state.button) }> { this.state.button } </button> </div> </div> ); } }
"use strict";exports.__esModule=!0,exports.default=void 0;var _Platform=_interopRequireDefault(require("../../../exports/Platform")),React=_interopRequireWildcard(require("react")),_ScrollView=_interopRequireDefault(require("../../../exports/ScrollView")),_VirtualizedSectionList=_interopRequireDefault(require("../VirtualizedSectionList"));function _getRequireWildcardCache(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return _getRequireWildcardCache=function(){return e},e}function _interopRequireWildcard(e){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache();if(t&&t.has(e))return t.get(e);var r,o={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&((r=i?Object.getOwnPropertyDescriptor(e,n):null)&&(r.get||r.set)?Object.defineProperty(o,n,r):o[n]=e[n])}return o.default=e,t&&t.set(e,o),o}function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e}).apply(this,arguments)}function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),(e.prototype.constructor=e).__proto__=t}function ownKeys(t,e){var r,o=Object.keys(t);return Object.getOwnPropertySymbols&&(r=Object.getOwnPropertySymbols(t),e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,r)),o}function _objectSpread(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?ownKeys(Object(r),!0).forEach(function(e){_defineProperty(t,e,r[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))})}return t}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var defaultProps=_objectSpread({},_VirtualizedSectionList.default.defaultProps,{stickySectionHeadersEnabled:"ios"===_Platform.default.OS}),SectionList=function(i){function e(){for(var t,e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];return(t=i.call.apply(i,[this].concat(r))||this)._captureRef=function(e){t._wrapperListRef=e},t}_inheritsLoose(e,i);var t=e.prototype;return t.scrollToLocation=function(e){null!=this._wrapperListRef&&this._wrapperListRef.scrollToLocation(e)},t.recordInteraction=function(){var e=this._wrapperListRef&&this._wrapperListRef.getListRef();e&&e.recordInteraction()},t.flashScrollIndicators=function(){var e=this._wrapperListRef&&this._wrapperListRef.getListRef();e&&e.flashScrollIndicators()},t.getScrollResponder=function(){var e=this._wrapperListRef&&this._wrapperListRef.getListRef();if(e)return e.getScrollResponder()},t.getScrollableNode=function(){var e=this._wrapperListRef&&this._wrapperListRef.getListRef();if(e)return e.getScrollableNode()},t.setNativeProps=function(e){var t=this._wrapperListRef&&this._wrapperListRef.getListRef();t&&t.setNativeProps(e)},t.render=function(){return React.createElement(_VirtualizedSectionList.default,_extends({},this.props,{ref:this._captureRef,getItemCount:function(e){return e.length},getItem:function(e,t){return e[t]}}))},e}(React.PureComponent);SectionList.defaultProps=defaultProps;var _default=SectionList;exports.default=SectionList,module.exports=exports.default;
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.cellx = factory()); }(this, (function () { 'use strict'; var ErrorLogger = { _handler: null, /** * @typesign (handler: (...msg)); */ setHandler: function setHandler(handler) { this._handler = handler; }, /** * @typesign (...msg); */ log: function log() { this._handler.apply(this, arguments); } }; var uidCounter = 0; /** * @typesign () -> string; */ function nextUID() { return String(++uidCounter); } var Symbol = Function('return this;')().Symbol; if (!Symbol) { Symbol = function Symbol(key) { return '__' + key + '_' + Math.floor(Math.random() * 1e9) + '_' + nextUID() + '__'; }; Symbol.iterator = Symbol('Symbol.iterator'); } var Symbol$1 = Symbol; var UID = Symbol$1('cellx.uid'); var CELLS = Symbol$1('cellx.cells'); var global$1 = Function('return this;')(); var hasOwn$1 = Object.prototype.hasOwnProperty; var Map = global$1.Map; if (!Map || Map.toString().indexOf('[native code]') == -1) { var entryStub = { value: undefined }; Map = function Map(entries) { this._entries = Object.create(null); this._objectStamps = {}; this._first = null; this._last = null; this.size = 0; if (entries) { for (var i = 0, l = entries.length; i < l; i++) { this.set(entries[i][0], entries[i][1]); } } }; Map.prototype = { constructor: Map, has: function has(key) { return !!this._entries[this._getValueStamp(key)]; }, get: function get(key) { return (this._entries[this._getValueStamp(key)] || entryStub).value; }, set: function set(key, value) { var entries = this._entries; var keyStamp = this._getValueStamp(key); if (entries[keyStamp]) { entries[keyStamp].value = value; } else { var entry = entries[keyStamp] = { key: key, keyStamp: keyStamp, value: value, prev: this._last, next: null }; if (this.size++) { this._last.next = entry; } else { this._first = entry; } this._last = entry; } return this; }, delete: function delete_(key) { var keyStamp = this._getValueStamp(key); var entry = this._entries[keyStamp]; if (!entry) { return false; } if (--this.size) { var prev = entry.prev; var next = entry.next; if (prev) { prev.next = next; } else { this._first = next; } if (next) { next.prev = prev; } else { this._last = prev; } } else { this._first = null; this._last = null; } delete this._entries[keyStamp]; delete this._objectStamps[keyStamp]; return true; }, clear: function clear() { var entries = this._entries; for (var stamp in entries) { delete entries[stamp]; } this._objectStamps = {}; this._first = null; this._last = null; this.size = 0; }, _getValueStamp: function _getValueStamp(value) { switch (typeof value) { case 'undefined': { return 'undefined'; } case 'object': { if (value === null) { return 'null'; } break; } case 'boolean': { return '?' + value; } case 'number': { return '+' + value; } case 'string': { return ',' + value; } } return this._getObjectStamp(value); }, _getObjectStamp: function _getObjectStamp(obj) { if (!hasOwn$1.call(obj, UID)) { if (!Object.isExtensible(obj)) { var stamps = this._objectStamps; var stamp; for (stamp in stamps) { if (hasOwn$1.call(stamps, stamp) && stamps[stamp] == obj) { return stamp; } } stamp = nextUID(); stamps[stamp] = obj; return stamp; } Object.defineProperty(obj, UID, { value: nextUID() }); } return obj[UID]; }, forEach: function forEach(cb, context) { var entry = this._first; while (entry) { cb.call(context, entry.value, entry.key, this); do { entry = entry.next; } while (entry && !this._entries[entry.keyStamp]); } }, toString: function toString() { return '[object Map]'; } }; [['keys', function keys(entry) { return entry.key; }], ['values', function values(entry) { return entry.value; }], ['entries', function entries(entry) { return [entry.key, entry.value]; }]].forEach((function (settings) { var getStepValue = settings[1]; Map.prototype[settings[0]] = function () { var entries = this._entries; var entry; var done = false; var map = this; return { next: function () { if (!done) { if (entry) { do { entry = entry.next; } while (entry && !entries[entry.keyStamp]); } else { entry = map._first; } if (entry) { return { value: getStepValue(entry), done: false }; } done = true; } return { value: undefined, done: true }; } }; }; })); } if (!Map.prototype[Symbol$1.iterator]) { Map.prototype[Symbol$1.iterator] = Map.prototype.entries; } var Map$1 = Map; var IS_EVENT = {}; /** * @typedef {{ * listener: (evt: cellx~Event) -> ?boolean, * context * }} cellx~EmitterEvent */ /** * @typedef {{ * target?: Object, * type: string, * bubbles?: boolean, * isPropagationStopped?: boolean * }} cellx~Event */ /** * @class cellx.EventEmitter * @extends {Object} * @typesign new EventEmitter() -> cellx.EventEmitter; */ function EventEmitter() { /** * @type {{ [type: string]: cellx~EmitterEvent | Array<cellx~EmitterEvent> }} */ this._events = new Map$1(); } EventEmitter.currentlySubscribing = false; EventEmitter.prototype = { constructor: EventEmitter, /** * @typesign () -> { [type: string]: Array<cellx~EmitterEvent> }; * @typesign (type: string) -> Array<cellx~EmitterEvent>; */ getEvents: function getEvents(type) { var events; if (type) { events = this._events.get(type); if (!events) { return []; } return events._isEvent === IS_EVENT ? [events] : events; } events = Object.create(null); this._events.forEach((function (typeEvents, type) { events[type] = typeEvents._isEvent === IS_EVENT ? [typeEvents] : typeEvents; })); return events; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.EventEmitter; * * @typesign ( * listeners: { [type: string]: (evt: cellx~Event) -> ?boolean }, * context? * ) -> cellx.EventEmitter; */ on: function on(type, listener, context) { if (typeof type == 'object') { context = arguments.length >= 2 ? listener : this; var listeners = type; for (type in listeners) { this._on(type, listeners[type], context); } } else { this._on(type, listener, arguments.length >= 3 ? context : this); } return this; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.EventEmitter; * * @typesign ( * listeners: { [type: string]: (evt: cellx~Event) -> ?boolean }, * context? * ) -> cellx.EventEmitter; * * @typesign () -> cellx.EventEmitter; */ off: function off(type, listener, context) { var argCount = arguments.length; if (argCount) { if (typeof type == 'object') { context = argCount >= 2 ? listener : this; var listeners = type; for (type in listeners) { this._off(type, listeners[type], context); } } else { this._off(type, listener, argCount >= 3 ? context : this); } } else { this._events.clear(); } return this; }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context * ); */ _on: function _on(type, listener, context) { var index = type.indexOf(':'); if (index != -1) { var propName = type.slice(index + 1); EventEmitter.currentlySubscribing = true; (this['_' + propName] || (this[propName], this['_' + propName])).on(type.slice(0, index), listener, context); EventEmitter.currentlySubscribing = false; } else { var events = this._events.get(type); var evt = { _isEvent: IS_EVENT, listener: listener, context: context }; if (!events) { this._events.set(type, evt); } else if (events._isEvent === IS_EVENT) { this._events.set(type, [events, evt]); } else { events.push(evt); } } }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context * ); */ _off: function _off(type, listener, context) { var index = type.indexOf(':'); if (index != -1) { var propName = type.slice(index + 1); (this['_' + propName] || (this[propName], this['_' + propName])).off(type.slice(0, index), listener, context); } else { var events = this._events.get(type); if (!events) { return; } var isEvent = events._isEvent === IS_EVENT; var evt; if (isEvent || events.length == 1) { evt = isEvent ? events : events[0]; if (evt.listener == listener && evt.context === context) { this._events.delete(type); } } else { for (var i = events.length; i;) { evt = events[--i]; if (evt.listener == listener && evt.context === context) { events.splice(i, 1); break; } } } } }, /** * @typesign ( * type: string, * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> (evt: cellx~Event) -> ?boolean; */ once: function once(type, listener, context) { if (arguments.length < 3) { context = this; } function wrapper(evt) { this._off(type, wrapper, context); return listener.call(this, evt); } this._on(type, wrapper, context); return wrapper; }, /** * @typesign (evt: cellx~Event) -> cellx~Event; * @typesign (type: string) -> cellx~Event; */ emit: function emit(evt) { if (typeof evt == 'string') { evt = { target: this, type: evt }; } else if (!evt.target) { evt.target = this; } else if (evt.target != this) { throw new TypeError('Event cannot be emitted on this object'); } this._handleEvent(evt); return evt; }, /** * @typesign (evt: cellx~Event); * * For override: * @example * function View(el) { * this.element = el; * el._view = this; * } * * View.prototype = { * __proto__: EventEmitter.prototype, * constructor: View, * * getParent: function() { * var node = this.element; * * while (node = node.parentNode) { * if (node._view) { * return node._view; * } * } * * return null; * }, * * _handleEvent: function(evt) { * EventEmitter.prototype._handleEvent.call(this, evt); * * if (evt.bubbles !== false && !evt.isPropagationStopped) { * var parent = this.getParent(); * * if (parent) { * parent._handleEvent(evt); * } * } * } * }; */ _handleEvent: function _handleEvent(evt) { var events = this._events.get(evt.type); if (!events) { return; } if (events._isEvent === IS_EVENT) { if (this._tryEventListener(events, evt) === false) { evt.isPropagationStopped = true; } } else { var eventCount = events.length; if (eventCount == 1) { if (this._tryEventListener(events[0], evt) === false) { evt.isPropagationStopped = true; } } else { events = events.slice(); for (var i = 0; i < eventCount; i++) { if (this._tryEventListener(events[i], evt) === false) { evt.isPropagationStopped = true; } } } } }, /** * @typesign (emEvt: cellx~EmitterEvent, evt: cellx~Event); */ _tryEventListener: function _tryEventListener(emEvt, evt) { try { return emEvt.listener.call(emEvt.context, evt); } catch (err) { this._logError(err); } }, /** * @typesign (...msg); */ _logError: function _logError() { ErrorLogger.log.apply(ErrorLogger, arguments); } }; function ObservableCollectionMixin() { /** * @type {Map<*, uint>} */ this._valueCounts = new Map$1(); } ObservableCollectionMixin.prototype = { /** * @typesign (evt: cellx~Event); */ _onItemChange: function _onItemChange(evt) { this._handleEvent(evt); }, /** * @typesign (value); */ _registerValue: function _registerValue(value) { var valueCounts = this._valueCounts; var valueCount = valueCounts.get(value); if (valueCount) { valueCounts.set(value, valueCount + 1); } else { valueCounts.set(value, 1); if (this.adoptsValueChanges && value instanceof EventEmitter) { value.on('change', this._onItemChange, this); } } }, /** * @typesign (value); */ _unregisterValue: function _unregisterValue(value) { var valueCounts = this._valueCounts; var valueCount = valueCounts.get(value); if (valueCount > 1) { valueCounts.set(value, valueCount - 1); } else { valueCounts.delete(value); if (this.adoptsValueChanges && value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } } } }; /** * @typesign (a, b) -> boolean; */ var is = Object.is || function is(a, b) { if (a === 0 && b === 0) { return 1 / a == 1 / b; } return a === b || a != a && b != b; }; /** * @typesign (target: Object, ...sources: Array<Object>) -> Object; */ function mixin(target, source) { var names = Object.getOwnPropertyNames(source); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; Object.defineProperty(target, name, Object.getOwnPropertyDescriptor(source, name)); } if (arguments.length > 2) { var i = 2; do { mixin(target, arguments[i]); } while (++i < arguments.length); } return target; } /** * @class cellx.ObservableMap * @extends {cellx.EventEmitter} * @implements {cellx.ObservableCollectionMixin} * * @typesign new ObservableMap(entries?: Object | cellx.ObservableMap | Map | Array<{ 0, 1 }>, opts?: { * adoptsValueChanges?: boolean * }) -> cellx.ObservableMap; * * @typesign new ObservableMap( * entries?: Object | cellx.ObservableMap | Map | Array<{ 0, 1 }>, * adoptsValueChanges?: boolean * ) -> cellx.ObservableMap; */ function ObservableMap(entries, opts) { EventEmitter.call(this); ObservableCollectionMixin.call(this); if (typeof opts == 'boolean') { opts = { adoptsValueChanges: opts }; } this._entries = new Map$1(); this.size = 0; /** * @type {boolean} */ this.adoptsValueChanges = !!(opts && opts.adoptsValueChanges); if (entries) { var mapEntries = this._entries; if (entries instanceof ObservableMap || entries instanceof Map$1) { entries._entries.forEach((function (value, key) { this._registerValue(value); mapEntries.set(key, value); }), this); } else if (Array.isArray(entries)) { for (var i = 0, l = entries.length; i < l; i++) { var entry = entries[i]; this._registerValue(entry[1]); mapEntries.set(entry[0], entry[1]); } } else { for (var key in entries) { this._registerValue(entries[key]); mapEntries.set(key, entries[key]); } } this.size = mapEntries.size; } } ObservableMap.prototype = mixin({ __proto__: EventEmitter.prototype }, ObservableCollectionMixin.prototype, { constructor: ObservableMap, /** * @typesign (key) -> boolean; */ has: function has(key) { return this._entries.has(key); }, /** * @typesign (value) -> boolean; */ contains: function contains(value) { return this._valueCounts.has(value); }, /** * @typesign (key) -> *; */ get: function get(key) { return this._entries.get(key); }, /** * @typesign (key, value) -> cellx.ObservableMap; */ set: function set(key, value) { var entries = this._entries; var hasKey = entries.has(key); var oldValue; if (hasKey) { oldValue = entries.get(key); if (is(value, oldValue)) { return this; } this._unregisterValue(oldValue); } this._registerValue(value); entries.set(key, value); if (!hasKey) { this.size++; } this.emit({ type: 'change', subtype: hasKey ? 'update' : 'add', key: key, oldValue: oldValue, value: value }); return this; }, /** * @typesign (key) -> boolean; */ delete: function delete_(key) { var entries = this._entries; if (!entries.has(key)) { return false; } var value = entries.get(key); this._unregisterValue(value); entries.delete(key); this.size--; this.emit({ type: 'change', subtype: 'delete', key: key, oldValue: value, value: undefined }); return true; }, /** * @typesign () -> cellx.ObservableMap; */ clear: function clear() { if (!this.size) { return this; } if (this.adoptsValueChanges) { this._valueCounts.forEach((function (value) { if (value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } }), this); } this._entries.clear(); this._valueCounts.clear(); this.size = 0; this.emit({ type: 'change', subtype: 'clear' }); return this; }, /** * @typesign ( * cb: (value, key, map: cellx.ObservableMap), * context? * ); */ forEach: function forEach(cb, context) { this._entries.forEach((function (value, key) { cb.call(context, value, key, this); }), this); }, /** * @typesign () -> { next: () -> { value, done: boolean } }; */ keys: function keys() { return this._entries.keys(); }, /** * @typesign () -> { next: () -> { value, done: boolean } }; */ values: function values() { return this._entries.values(); }, /** * @typesign () -> { next: () -> { value: { 0, 1 }, done: boolean } }; */ entries: function entries() { return this._entries.entries(); }, /** * @typesign () -> cellx.ObservableMap; */ clone: function clone() { return new this.constructor(this, { adoptsValueChanges: this.adoptsValueChanges }); } }); ObservableMap.prototype[Symbol$1.iterator] = ObservableMap.prototype.entries; var push = Array.prototype.push; var splice = Array.prototype.splice; /** * @typesign (a, b) -> -1 | 1 | 0; */ function defaultComparator(a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * @class cellx.ObservableList * @extends {cellx.EventEmitter} * @implements {cellx.ObservableCollectionMixin} * * @typesign new ObservableList(items?: Array | cellx.ObservableList, opts?: { * adoptsValueChanges?: boolean, * comparator?: (a, b) -> int, * sorted?: boolean * }) -> cellx.ObservableList; * * @typesign new ObservableList( * items?: Array | cellx.ObservableList, * adoptsValueChanges?: boolean * ) -> cellx.ObservableList; */ function ObservableList(items, opts) { EventEmitter.call(this); ObservableCollectionMixin.call(this); if (typeof opts == 'boolean') { opts = { adoptsValueChanges: opts }; } this._items = []; this.length = 0; /** * @type {boolean} */ this.adoptsValueChanges = !!(opts && opts.adoptsValueChanges); /** * @type {?(a, b) -> int} */ this.comparator = null; this.sorted = false; if (opts && (opts.sorted || opts.comparator && opts.sorted !== false)) { this.comparator = opts.comparator || defaultComparator; this.sorted = true; } if (items) { this._addRange(items); } } ObservableList.prototype = mixin({ __proto__: EventEmitter.prototype }, ObservableCollectionMixin.prototype, { constructor: ObservableList, /** * @typesign (index: ?int, allowedEndIndex?: boolean) -> ?uint; */ _validateIndex: function _validateIndex(index, allowedEndIndex) { if (index === undefined) { return index; } if (index < 0) { index += this.length; if (index < 0) { throw new RangeError('Index out of valid range'); } } else if (index >= this.length + (allowedEndIndex ? 1 : 0)) { throw new RangeError('Index out of valid range'); } return index; }, /** * @typesign (value) -> boolean; */ contains: function contains(value) { return this._valueCounts.has(value); }, /** * @typesign (value, fromIndex?: int) -> int; */ indexOf: function indexOf(value, fromIndex) { return this._items.indexOf(value, this._validateIndex(fromIndex, true)); }, /** * @typesign (value, fromIndex?: int) -> int; */ lastIndexOf: function lastIndexOf(value, fromIndex) { return this._items.lastIndexOf(value, fromIndex === undefined ? -1 : this._validateIndex(fromIndex, true)); }, /** * @typesign (index: int) -> *; */ get: function get(index) { return this._items[this._validateIndex(index, true)]; }, /** * @typesign (index: int, count?: uint) -> Array; */ getRange: function getRange(index, count) { index = this._validateIndex(index, true); var items = this._items; if (count === undefined) { return items.slice(index); } if (index + count > items.length) { throw new RangeError('Sum of "index" and "count" out of valid range'); } return items.slice(index, index + count); }, /** * @typesign (index: int, value) -> cellx.ObservableList; */ set: function set(index, value) { if (this.sorted) { throw new TypeError('Cannot set to sorted list'); } index = this._validateIndex(index, true); var items = this._items; if (is(value, items[index])) { return this; } this._unregisterValue(items[index]); this._registerValue(value); items[index] = value; this.emit('change'); return this; }, /** * @typesign (index: int, values: Array | cellx.ObservableList) -> cellx.ObservableList; */ setRange: function setRange(index, values) { if (this.sorted) { throw new TypeError('Cannot set to sorted list'); } index = this._validateIndex(index, true); if (values instanceof ObservableList) { values = values._items; } var valueCount = values.length; if (!valueCount) { return this; } if (index + valueCount > this.length) { throw new RangeError('Sum of "index" and "values.length" out of valid range'); } var items = this._items; var changed = false; for (var i = index + valueCount; i > index;) { var value = values[--i - index]; if (!is(value, items[i])) { this._unregisterValue(items[i]); this._registerValue(value); items[i] = value; changed = true; } } if (changed) { this.emit('change'); } return this; }, /** * @typesign (value) -> cellx.ObservableList; */ add: function add(value) { if (this.sorted) { this._insertValue(value); } else { this._registerValue(value); this._items.push(value); } this.length++; this.emit('change'); return this; }, /** * @typesign (values: Array | cellx.ObservableList) -> cellx.ObservableList; */ addRange: function addRange(values) { if (values.length) { this._addRange(values); this.emit('change'); } return this; }, /** * @typesign (values: Array | cellx.ObservableList); */ _addRange: function _addRange(values) { if (values instanceof ObservableList) { values = values._items; } if (this.sorted) { for (var i = 0, l = values.length; i < l; i++) { this._insertValue(values[i]); } this.length += values.length; } else { for (var j = values.length; j;) { this._registerValue(values[--j]); } this.length = push.apply(this._items, values); } }, /** * @typesign (value); */ _insertValue: function _insertValue(value) { this._registerValue(value); var items = this._items; var comparator = this.comparator; var low = 0; var high = items.length; while (low != high) { var mid = low + high >> 1; if (comparator(value, items[mid]) < 0) { high = mid; } else { low = mid + 1; } } items.splice(low, 0, value); }, /** * @typesign (index: int, value) -> cellx.ObservableList; */ insert: function insert(index, value) { if (this.sorted) { throw new TypeError('Cannot insert to sorted list'); } index = this._validateIndex(index, true); this._registerValue(value); this._items.splice(index, 0, value); this.length++; this.emit('change'); return this; }, /** * @typesign (index: int, values: Array | cellx.ObservableList) -> cellx.ObservableList; */ insertRange: function insertRange(index, values) { if (this.sorted) { throw new TypeError('Cannot insert to sorted list'); } index = this._validateIndex(index, true); if (values instanceof ObservableList) { values = values._items; } var valueCount = values.length; if (!valueCount) { return this; } for (var i = valueCount; i;) { this._registerValue(values[--i]); } splice.apply(this._items, [index, 0].concat(values)); this.length += valueCount; this.emit('change'); return this; }, /** * @typesign (value, fromIndex?: int) -> boolean; */ remove: function remove(value, fromIndex) { var index = this._items.indexOf(value, this._validateIndex(fromIndex, true)); if (index == -1) { return false; } this._unregisterValue(value); this._items.splice(index, 1); this.length--; this.emit('change'); return true; }, /** * @typesign (value, fromIndex?: int) -> boolean; */ removeAll: function removeAll(value, fromIndex) { var index = this._validateIndex(fromIndex, true); var items = this._items; var changed = false; while ((index = items.indexOf(value, index)) != -1) { this._unregisterValue(value); items.splice(index, 1); changed = true; } if (changed) { this.length = items.length; this.emit('change'); } return changed; }, /** * @typesign (values: Array | cellx.ObservableList, fromIndex?: int) -> boolean; */ removeEach: function removeEach(values, fromIndex) { fromIndex = this._validateIndex(fromIndex, true); if (values instanceof ObservableList) { values = values._items; } var items = this._items; var changed = false; for (var i = 0, l = values.length; i < l; i++) { var value = values[i]; var index = items.indexOf(value, fromIndex); if (index != -1) { this._unregisterValue(value); items.splice(index, 1); changed = true; } } if (changed) { this.length = items.length; this.emit('change'); } return changed; }, /** * @typesign (values: Array | cellx.ObservableList, fromIndex?: int) -> boolean; */ removeAllEach: function removeAllEach(values, fromIndex) { fromIndex = this._validateIndex(fromIndex, true); if (values instanceof ObservableList) { values = values._items; } var items = this._items; var changed = false; for (var i = 0, l = values.length; i < l; i++) { var value = values[i]; for (var index = fromIndex; (index = items.indexOf(value, index)) != -1;) { this._unregisterValue(value); items.splice(index, 1); changed = true; } } if (changed) { this.length = items.length; this.emit('change'); } return changed; }, /** * @typesign (index: int) -> *; */ removeAt: function removeAt(index) { var value = this._items.splice(this._validateIndex(index), 1)[0]; this._unregisterValue(value); this.length--; this.emit('change'); return value; }, /** * @typesign (index: int, count?: uint) -> Array; */ removeRange: function removeRange(index, count) { index = this._validateIndex(index, true); var items = this._items; if (count === undefined) { count = items.length - index; } else if (index + count > items.length) { throw new RangeError('Sum of "index" and "count" out of valid range'); } if (!count) { return []; } for (var i = index + count; i > index;) { this._unregisterValue(items[--i]); } var values = items.splice(index, count); this.length -= count; this.emit('change'); return values; }, /** * @typesign () -> cellx.ObservableList; */ clear: function clear() { if (!this.length) { return this; } if (this.adoptsValueChanges) { this._valueCounts.forEach((function (value) { if (value instanceof EventEmitter) { value.off('change', this._onItemChange, this); } }), this); } this._items.length = 0; this._valueCounts.clear(); this.length = 0; this.emit({ type: 'change', subtype: 'clear' }); return this; }, /** * @typesign (separator?: string) -> string; */ join: function join(separator) { return this._items.join(separator); }, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList), * context? * ); */ forEach: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> *, * context? * ) -> Array; */ map: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> Array; */ filter: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> *; */ find: function (cb, context) { var items = this._items; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; if (cb.call(context, item, i, this)) { return item; } } }, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> int; */ findIndex: function (cb, context) { var items = this._items; for (var i = 0, l = items.length; i < l; i++) { if (cb.call(context, items[i], i, this)) { return i; } } return -1; }, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> boolean; */ every: null, /** * @typesign ( * cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean, * context? * ) -> boolean; */ some: null, /** * @typesign ( * cb: (accumulator, item, index: uint, list: cellx.ObservableList) -> *, * initialValue? * ) -> *; */ reduce: null, /** * @typesign ( * cb: (accumulator, item, index: uint, list: cellx.ObservableList) -> *, * initialValue? * ) -> *; */ reduceRight: null, /** * @typesign () -> cellx.ObservableList; */ clone: function clone() { return new this.constructor(this, { adoptsValueChanges: this.adoptsValueChanges, comparator: this.comparator, sorted: this.sorted }); }, /** * @typesign () -> Array; */ toArray: function toArray() { return this._items.slice(); }, /** * @typesign () -> string; */ toString: function toString() { return this._items.join(); } }); ['forEach', 'map', 'filter', 'every', 'some'].forEach((function (name) { ObservableList.prototype[name] = function (cb, context) { return this._items[name]((function (item, index) { return cb.call(context, item, index, this); }), this); }; })); ['reduce', 'reduceRight'].forEach((function (name) { ObservableList.prototype[name] = function (cb, initialValue) { var items = this._items; var list = this; function wrapper(accumulator, item, index) { return cb(accumulator, item, index, list); } return arguments.length >= 2 ? items[name](wrapper, initialValue) : items[name](wrapper); }; })); [['keys', function keys(index) { return index; }], ['values', function values(index, item) { return item; }], ['entries', function entries(index, item) { return [index, item]; }]].forEach((function (settings) { var getStepValue = settings[1]; ObservableList.prototype[settings[0]] = function () { var items = this._items; var index = 0; var done = false; return { next: function () { if (!done) { if (index < items.length) { return { value: getStepValue(index, items[index++]), done: false }; } done = true; } return { value: undefined, done: true }; } }; }; })); ObservableList.prototype[Symbol$1.iterator] = ObservableList.prototype.values; /** * @typesign (cb: ()); */ var nextTick; /* istanbul ignore next */ if (global$1.process && process.toString() == '[object process]' && process.nextTick) { nextTick = process.nextTick; } else if (global$1.setImmediate) { nextTick = function nextTick(cb) { setImmediate(cb); }; } else if (global$1.Promise && Promise.toString().indexOf('[native code]') != -1) { var prm = Promise.resolve(); nextTick = function nextTick(cb) { prm.then((function () { cb(); })); }; } else { var queue; global$1.addEventListener('message', (function () { if (queue) { var track = queue; queue = null; for (var i = 0, l = track.length; i < l; i++) { try { track[i](); } catch (err) { ErrorLogger.log(err); } } } })); nextTick = function nextTick(cb) { if (queue) { queue.push(cb); } else { queue = [cb]; postMessage('__tic__', '*'); } }; } var nextTick$1 = nextTick; function noop() {} var slice$1 = Array.prototype.slice; var EventEmitterProto = EventEmitter.prototype; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 0x1fffffffffffff; var KEY_WRAPPERS = Symbol$1('wrappers'); var errorIndexCounter = 0; var pushingIndexCounter = 0; var releasePlan = new Map$1(); var releasePlanIndex = MAX_SAFE_INTEGER; var releasePlanToIndex = -1; var releasePlanned = false; var currentlyRelease = false; var currentCell = null; var error = { original: null }; var releaseVersion = 1; var transactionLevel = 0; var transactionFailure = false; var pendingReactions = []; var afterReleaseCallbacks; var STATE_INITED = 128; var STATE_CURRENTLY_PULLING = 64; var STATE_ACTIVE = 32; var STATE_HAS_FOLLOWERS = 16; var STATE_PENDING = 8; var STATE_FULFILLED = 4; var STATE_REJECTED = 2; var STATE_CAN_CANCEL_CHANGE = 1; function release() { if (!releasePlanned) { return; } releasePlanned = false; currentlyRelease = true; var queue = releasePlan.get(releasePlanIndex); for (;;) { var cell = queue && queue.shift(); if (!cell) { if (releasePlanIndex == releasePlanToIndex) { break; } queue = releasePlan.get(++releasePlanIndex); continue; } var level = cell._level; var changeEvent = cell._changeEvent; if (!changeEvent) { if (level > releasePlanIndex || cell._levelInRelease == -1) { if (!queue.length) { if (releasePlanIndex == releasePlanToIndex) { break; } queue = releasePlan.get(++releasePlanIndex); } continue; } cell.pull(); level = cell._level; if (level > releasePlanIndex) { if (!queue.length) { queue = releasePlan.get(++releasePlanIndex); } continue; } changeEvent = cell._changeEvent; } cell._levelInRelease = -1; if (changeEvent) { var oldReleasePlanIndex = releasePlanIndex; cell._fixedValue = cell._value; cell._changeEvent = null; cell._handleEvent(changeEvent); var pushingIndex = cell._pushingIndex; var slaves = cell._slaves; for (var i = 0, l = slaves.length; i < l; i++) { var slave = slaves[i]; if (slave._level <= level) { slave._level = level + 1; } if (pushingIndex >= slave._pushingIndex) { slave._pushingIndex = pushingIndex; slave._changeEvent = null; slave._addToRelease(); } } if (releasePlanIndex != oldReleasePlanIndex) { queue = releasePlan.get(releasePlanIndex); continue; } } if (!queue.length) { if (releasePlanIndex == releasePlanToIndex) { break; } queue = releasePlan.get(++releasePlanIndex); } } releasePlanIndex = MAX_SAFE_INTEGER; releasePlanToIndex = -1; currentlyRelease = false; releaseVersion++; if (afterReleaseCallbacks) { var callbacks = afterReleaseCallbacks; afterReleaseCallbacks = null; for (var j = 0, m = callbacks.length; j < m; j++) { callbacks[j](); } } } /** * @typesign (cell: Cell, value); */ function defaultPut(cell, value) { cell.push(value); } var config = { asynchronous: true }; /** * @class cellx.Cell * @extends {cellx.EventEmitter} * * @example * var a = new Cell(1); * var b = new Cell(2); * var c = new Cell(function() { * return a.get() + b.get(); * }); * * c.on('change', function() { * console.log('c = ' + c.get()); * }); * * console.log(c.get()); * // => 3 * * a.set(5); * b.set(10); * // => 'c = 15' * * @typesign new Cell(value?, opts?: { * debugKey?: string, * owner?: Object, * get?: (value) -> *, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx.Cell; * * @typesign new Cell(pull: (cell: Cell, next) -> *, opts?: { * debugKey?: string, * owner?: Object, * get?: (value) -> *, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx.Cell; */ function Cell(value, opts) { EventEmitter.call(this); this.debugKey = opts && opts.debugKey; this.owner = opts && opts.owner || this; this._pull = typeof value == 'function' ? value : null; this._get = opts && opts.get || null; this._validate = opts && opts.validate || null; this._merge = opts && opts.merge || null; this._put = opts && opts.put || defaultPut; this._onFulfilled = this._onRejected = null; this._reap = opts && opts.reap || null; if (this._pull) { this._fixedValue = this._value = undefined; } else { if (this._validate) { this._validate(value, undefined); } if (this._merge) { value = this._merge(value, undefined); } this._fixedValue = this._value = value; if (value instanceof EventEmitter) { value.on('change', this._onValueChange, this); } } this._error = null; this._selfErrorCell = null; this._errorCell = null; this._errorIndex = 0; this._pushingIndex = 0; this._version = 0; /** * Ведущие ячейки. * @type {?Array<cellx.Cell>} */ this._masters = undefined; /** * Ведомые ячейки. * @type {Array<cellx.Cell>} */ this._slaves = []; this._level = 0; this._levelInRelease = -1; this._selfPendingStatusCell = null; this._pendingStatusCell = null; this._status = null; this._changeEvent = null; this._lastErrorEvent = null; this._state = STATE_CAN_CANCEL_CHANGE; if (opts) { if (opts.onChange) { this.on('change', opts.onChange); } if (opts.onError) { this.on('error', opts.onError); } } } mixin(Cell, { /** * @typesign (cnfg: { asynchronous?: boolean }); */ configure: function configure(cnfg) { if (cnfg.asynchronous !== undefined) { if (releasePlanned) { release(); } config.asynchronous = cnfg.asynchronous; } }, /** * @type {boolean} */ get currentlyPulling() { return !!currentCell; }, /** * @typesign (cb: (), context?) -> (); */ autorun: function autorun(cb, context) { var disposer; new Cell(function () { var cell = this; if (!disposer) { disposer = function disposer() { cell.dispose(); }; } if (transactionLevel) { var index = pendingReactions.indexOf(this); if (index != -1) { pendingReactions.splice(index, 1); } pendingReactions.push(this); } else { cb.call(context, disposer); } }, { onChange: noop }); return disposer; }, /** * @typesign (); */ forceRelease: function forceRelease() { if (releasePlanned) { release(); } }, /** * @typesign (cb: ()); */ transaction: function transaction(cb) { if (!transactionLevel++ && releasePlanned) { release(); } try { cb(); } catch (err) { ErrorLogger.log(err); transactionFailure = true; } if (transactionFailure) { for (var iterator = releasePlan.values(), step; !(step = iterator.next()).done;) { var queue = step.value; for (var i = queue.length; i;) { var cell = queue[--i]; cell._value = cell._fixedValue; cell._levelInRelease = -1; cell._changeEvent = null; } } releasePlan.clear(); releasePlanIndex = MAX_SAFE_INTEGER; releasePlanToIndex = -1; releasePlanned = false; pendingReactions.length = 0; } if (! --transactionLevel && !transactionFailure) { for (var i = 0, l = pendingReactions.length; i < l; i++) { var reaction = pendingReactions[i]; if (reaction instanceof Cell) { reaction.pull(); } else { EventEmitterProto._handleEvent.call(reaction[1], reaction[0]); } } transactionFailure = false; pendingReactions.length = 0; if (releasePlanned) { release(); } } }, /** * @typesign (cb: ()); */ afterRelease: function afterRelease(cb) { (afterReleaseCallbacks || (afterReleaseCallbacks = [])).push(cb); } }); Cell.prototype = { __proto__: EventEmitter.prototype, constructor: Cell, _handleEvent: function _handleEvent(evt) { if (transactionLevel) { pendingReactions.push([evt, this]); } else { EventEmitterProto._handleEvent.call(this, evt); } }, /** * @override */ on: function on(type, listener, context) { if (releasePlanned) { release(); } this._activate(); if (typeof type == 'object') { EventEmitterProto.on.call(this, type, arguments.length >= 2 ? listener : this.owner); } else { EventEmitterProto.on.call(this, type, listener, arguments.length >= 3 ? context : this.owner); } this._state |= STATE_HAS_FOLLOWERS; return this; }, /** * @override */ off: function off(type, listener, context) { if (releasePlanned) { release(); } var argCount = arguments.length; if (argCount) { if (typeof type == 'object') { EventEmitterProto.off.call(this, type, argCount >= 2 ? listener : this.owner); } else { EventEmitterProto.off.call(this, type, listener, argCount >= 3 ? context : this.owner); } } else { EventEmitterProto.off.call(this); } if (!this._slaves.length && !this._events.has('change') && !this._events.has('error') && this._state & STATE_HAS_FOLLOWERS) { this._state ^= STATE_HAS_FOLLOWERS; this._deactivate(); if (this._reap) { this._reap.call(this.owner); } } return this; }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ addChangeListener: function addChangeListener(listener, context) { return this.on('change', listener, arguments.length >= 2 ? context : this.owner); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ removeChangeListener: function removeChangeListener(listener, context) { return this.off('change', listener, arguments.length >= 2 ? context : this.owner); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ addErrorListener: function addErrorListener(listener, context) { return this.on('error', listener, arguments.length >= 2 ? context : this.owner); }, /** * @typesign ( * listener: (evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ removeErrorListener: function removeErrorListener(listener, context) { return this.off('error', listener, arguments.length >= 2 ? context : this.owner); }, /** * @typesign ( * listener: (err: ?Error, evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ subscribe: function subscribe(listener, context) { var wrappers = listener[KEY_WRAPPERS]; if (wrappers && wrappers.has(listener)) { return this; } function wrapper(evt) { return listener.call(this, evt.error || null, evt); } (wrappers || (listener[KEY_WRAPPERS] = new Map$1())).set(this, wrapper); if (arguments.length < 2) { context = this.owner; } return this.on('change', wrapper, context).on('error', wrapper, context); }, /** * @typesign ( * listener: (err: ?Error, evt: cellx~Event) -> ?boolean, * context? * ) -> cellx.Cell; */ unsubscribe: function unsubscribe(listener, context) { if (arguments.length < 2) { context = this.owner; } var wrappers = listener[KEY_WRAPPERS]; var wrapper = wrappers && wrappers.get(this); if (!wrapper) { return this; } wrappers.delete(this); return this.off('change', wrapper, context).off('error', wrapper, context); }, /** * @typesign (slave: cellx.Cell); */ _registerSlave: function _registerSlave(slave) { this._activate(); this._slaves.push(slave); this._state |= STATE_HAS_FOLLOWERS; }, /** * @typesign (slave: cellx.Cell); */ _unregisterSlave: function _unregisterSlave(slave) { this._slaves.splice(this._slaves.indexOf(slave), 1); if (!this._slaves.length && !this._events.has('change') && !this._events.has('error')) { this._state ^= STATE_HAS_FOLLOWERS; this._deactivate(); if (this._reap) { this._reap.call(this.owner); } } }, /** * @typesign (); */ _activate: function _activate() { if (!this._pull || this._state & STATE_ACTIVE || this._masters === null) { return; } var masters = this._masters; if (this._version < releaseVersion) { var value = this._tryPull(); if (masters || this._masters || !(this._state & STATE_INITED)) { if (value === error) { this._fail(error.original, false); } else { this._push(value, false, false); } } masters = this._masters; } if (masters) { var i = masters.length; do { masters[--i]._registerSlave(this); } while (i); this._state |= STATE_ACTIVE; } }, /** * @typesign (); */ _deactivate: function _deactivate() { if (!(this._state & STATE_ACTIVE)) { return; } var masters = this._masters; var i = masters.length; do { masters[--i]._unregisterSlave(this); } while (i); if (this._levelInRelease != -1 && !this._changeEvent) { this._levelInRelease = -1; } this._state ^= STATE_ACTIVE; }, /** * @typesign (); */ _addToRelease: function _addToRelease() { var level = this._level; if (level <= this._levelInRelease) { return; } var queue; (releasePlan.get(level) || (releasePlan.set(level, queue = []), queue)).push(this); if (releasePlanIndex > level) { releasePlanIndex = level; } if (releasePlanToIndex < level) { releasePlanToIndex = level; } this._levelInRelease = level; if (!releasePlanned && !currentlyRelease) { releasePlanned = true; if (!transactionLevel && !config.asynchronous) { release(); } else { nextTick$1(release); } } }, /** * @typesign (evt: cellx~Event); */ _onValueChange: function _onValueChange(evt) { this._pushingIndex = ++pushingIndexCounter; if (this._changeEvent) { evt.prev = this._changeEvent; this._changeEvent = evt; if (this._value === this._fixedValue) { this._state &= ~STATE_CAN_CANCEL_CHANGE; } } else { evt.prev = null; this._changeEvent = evt; this._state &= ~STATE_CAN_CANCEL_CHANGE; this._addToRelease(); } }, /** * @typesign () -> *; */ get: function get() { if (releasePlanned && this._pull) { release(); } if (this._pull && !(this._state & STATE_ACTIVE) && this._version < releaseVersion && this._masters !== null) { var oldMasters = this._masters; var value = this._tryPull(); var masters = this._masters; if (oldMasters || masters || !(this._state & STATE_INITED)) { if (masters && this._state & STATE_HAS_FOLLOWERS) { var i = masters.length; do { masters[--i]._registerSlave(this); } while (i); this._state |= STATE_ACTIVE; } if (value === error) { this._fail(error.original, false); } else { this._push(value, false, false); } } } if (currentCell) { var currentCellMasters = currentCell._masters; var level = this._level; if (currentCellMasters) { if (currentCellMasters.indexOf(this) == -1) { currentCellMasters.push(this); if (currentCell._level <= level) { currentCell._level = level + 1; } } } else { currentCell._masters = [this]; currentCell._level = level + 1; } } return this._get ? this._get(this._value) : this._value; }, /** * @typesign () -> boolean; */ pull: function pull() { if (!this._pull) { return false; } if (releasePlanned) { release(); } var hasFollowers = this._state & STATE_HAS_FOLLOWERS; var oldMasters; var oldLevel; if (hasFollowers) { oldMasters = this._masters; oldLevel = this._level; } var value = this._tryPull(); if (hasFollowers) { var masters = this._masters; var newMasterCount = 0; if (masters) { var i = masters.length; do { var master = masters[--i]; if (!oldMasters || oldMasters.indexOf(master) == -1) { master._registerSlave(this); newMasterCount++; } } while (i); } if (oldMasters && (masters ? masters.length - newMasterCount : 0) < oldMasters.length) { for (var j = oldMasters.length; j;) { var oldMaster = oldMasters[--j]; if (!masters || masters.indexOf(oldMaster) == -1) { oldMaster._unregisterSlave(this); } } } if (masters && masters.length) { this._state |= STATE_ACTIVE; } else { this._state &= ~STATE_ACTIVE; } if (currentlyRelease && this._level > oldLevel) { this._addToRelease(); return false; } } if (value === error) { this._fail(error.original, false); return true; } return this._push(value, false, true); }, /** * @typesign () -> *; */ _tryPull: function _tryPull() { if (this._state & STATE_CURRENTLY_PULLING) { throw new TypeError('Circular pulling detected'); } var pull = this._pull; if (pull.length) { this._state |= STATE_PENDING; if (this._selfPendingStatusCell) { this._selfPendingStatusCell.set(true); } this._state &= ~(STATE_FULFILLED | STATE_REJECTED); } var prevCell = currentCell; currentCell = this; this._state |= STATE_CURRENTLY_PULLING; this._masters = null; this._level = 0; try { return pull.length ? pull.call(this.owner, this, this._value) : pull.call(this.owner); } catch (err) { error.original = err; return error; } finally { currentCell = prevCell; this._version = releaseVersion + currentlyRelease; var pendingStatusCell = this._pendingStatusCell; if (pendingStatusCell && pendingStatusCell._state & STATE_ACTIVE) { pendingStatusCell.pull(); } var errorCell = this._errorCell; if (errorCell && errorCell._state & STATE_ACTIVE) { errorCell.pull(); } this._state ^= STATE_CURRENTLY_PULLING; } }, /** * @typesign () -> ?Error; */ getError: function getError() { var errorCell = this._errorCell; if (!errorCell) { var debugKey = this.debugKey; this._selfErrorCell = new Cell(this._error, debugKey ? { debugKey: debugKey + '._selfErrorCell' } : null); errorCell = this._errorCell = new Cell(function () { this.get(); var err = this._selfErrorCell.get(); var index; if (err) { index = this._errorIndex; if (index == errorIndexCounter) { return err; } } var masters = this._masters; if (masters) { var i = masters.length; do { var master = masters[--i]; var masterError = master.getError(); if (masterError) { var masterErrorIndex = master._errorIndex; if (masterErrorIndex == errorIndexCounter) { return masterError; } if (!err || index < masterErrorIndex) { err = masterError; index = masterErrorIndex; } } } while (i); } return err; }, debugKey ? { debugKey: debugKey + '._errorCell', owner: this } : { owner: this }); } return errorCell.get(); }, /** * @typesign () -> boolean; */ isPending: function isPending() { var pendingStatusCell = this._pendingStatusCell; if (!pendingStatusCell) { var debugKey = this.debugKey; this._selfPendingStatusCell = new Cell(!!(this._state & STATE_PENDING), debugKey ? { debugKey: debugKey + '._selfPendingStatusCell' } : null); pendingStatusCell = this._pendingStatusCell = new Cell(function () { if (this._selfPendingStatusCell.get()) { return true; } this.get(); var masters = this._masters; if (masters) { var i = masters.length; do { if (masters[--i].isPending()) { return true; } } while (i); } return false; }, debugKey ? { debugKey: debugKey + '._pendingStatusCell', owner: this } : { owner: this }); } return pendingStatusCell.get(); }, getStatus: function getStatus() { var status = this._status; if (!status) { var cell = this; status = this._status = { get success() { return !cell.getError(); }, get pending() { return cell.isPending(); } }; } return status; }, /** * @typesign (value) -> cellx.Cell; */ set: function set(value) { if (this._validate) { this._validate(value, this._value); } if (this._merge) { value = this._merge(value, this._value); } this._state |= STATE_PENDING; if (this._selfPendingStatusCell) { this._selfPendingStatusCell.set(true); } this._state &= ~(STATE_FULFILLED | STATE_REJECTED); if (this._put.length >= 3) { this._put.call(this.owner, this, value, this._value); } else { this._put.call(this.owner, this, value); } return this; }, /** * @typesign (value) -> cellx.Cell; */ push: function push(value) { this._push(value, true, false); return this; }, /** * @typesign (value, external: boolean, pulling: boolean) -> boolean; */ _push: function _push(value, external, pulling) { this._state |= STATE_INITED; var oldValue = this._value; if (external && currentlyRelease && this._state & STATE_HAS_FOLLOWERS) { if (is(value, oldValue)) { this._setError(null); this._fulfill(value); return false; } var cell = this; (afterReleaseCallbacks || (afterReleaseCallbacks = [])).push((function () { cell._push(value, true, false); })); return true; } if (external || !currentlyRelease && pulling) { this._pushingIndex = ++pushingIndexCounter; } this._setError(null); if (is(value, oldValue)) { if (external || currentlyRelease && pulling) { this._fulfill(value); } return false; } this._value = value; if (oldValue instanceof EventEmitter) { oldValue.off('change', this._onValueChange, this); } if (value instanceof EventEmitter) { value.on('change', this._onValueChange, this); } if (this._state & STATE_HAS_FOLLOWERS || transactionLevel) { if (this._changeEvent) { if (is(value, this._fixedValue) && this._state & STATE_CAN_CANCEL_CHANGE) { this._levelInRelease = -1; this._changeEvent = null; } else { this._changeEvent = { target: this, type: 'change', oldValue: oldValue, value: value, prev: this._changeEvent }; } } else { this._changeEvent = { target: this, type: 'change', oldValue: oldValue, value: value, prev: null }; this._state |= STATE_CAN_CANCEL_CHANGE; this._addToRelease(); } } else { if (external || !currentlyRelease && pulling) { releaseVersion++; } this._fixedValue = value; this._version = releaseVersion + currentlyRelease; } if (external || currentlyRelease && pulling) { this._fulfill(value); } return true; }, /** * @typesign (value); */ _fulfill: function _fulfill(value) { this._resolvePending(); if (!(this._state & STATE_FULFILLED)) { this._state |= STATE_FULFILLED; if (this._onFulfilled) { this._onFulfilled(value); } } }, /** * @typesign (err) -> cellx.Cell; */ fail: function fail(err) { this._fail(err, true); return this; }, /** * @typesign (err, external: boolean); */ _fail: function _fail(err, external) { if (transactionLevel) { transactionFailure = true; } this._logError(err); if (!(err instanceof Error)) { err = new Error(String(err)); } this._setError(err); if (external) { this._reject(err); } }, /** * @typesign (err: ?Error); */ _setError: function _setError(err) { if (!err && !this._error) { return; } this._error = err; if (this._selfErrorCell) { this._selfErrorCell.set(err); } if (err) { this._errorIndex = ++errorIndexCounter; this._handleErrorEvent({ type: 'error', error: err }); } }, /** * @typesign (evt: cellx~Event{ error: Error }); */ _handleErrorEvent: function _handleErrorEvent(evt) { if (this._lastErrorEvent === evt) { return; } this._lastErrorEvent = evt; this._handleEvent(evt); var slaves = this._slaves; for (var i = 0, l = slaves.length; i < l; i++) { slaves[i]._handleErrorEvent(evt); } }, /** * @typesign (err: Error); */ _reject: function _reject(err) { this._resolvePending(); if (!(this._state & STATE_REJECTED)) { this._state |= STATE_REJECTED; if (this._onRejected) { this._onRejected(err); } } }, /** * @typesign (); */ _resolvePending: function _resolvePending() { if (this._state & STATE_PENDING) { this._state ^= STATE_PENDING; if (this._selfPendingStatusCell) { this._selfPendingStatusCell.set(false); } } }, /** * @typesign (onFulfilled: ?(value) -> *, onRejected?: (err) -> *) -> Promise; */ then: function then(onFulfilled, onRejected) { if (releasePlanned) { release(); } if (!this._pull || this._state & STATE_FULFILLED) { return Promise.resolve(this._get ? this._get(this._value) : this._value).then(onFulfilled); } if (this._state & STATE_REJECTED) { return Promise.reject(this._error).catch(onRejected); } var cell = this; var promise = new Promise(function (resolve, reject) { cell._onFulfilled = function onFulfilled(value) { cell._onFulfilled = cell._onRejected = null; resolve(cell._get ? cell._get(value) : value); }; cell._onRejected = function onRejected(err) { cell._onFulfilled = cell._onRejected = null; reject(err); }; }).then(onFulfilled, onRejected); if (!(this._state & STATE_PENDING)) { this.pull(); } if (cell.isPending()) { cell._pendingStatusCell.on('change', (function onPendingStatusCellChange() { cell._pendingStatusCell.off('change', onPendingStatusCellChange); if (!(cell._state & STATE_FULFILLED) && !(cell._state & STATE_REJECTED)) { var err = cell.getError(); if (err) { cell._reject(err); } else { cell._fulfill(cell._get ? cell._get(cell._value) : cell._value); } } })); } return promise; }, /** * @typesign (onRejected: (err) -> *) -> Promise; */ catch: function catch_(onRejected) { return this.then(null, onRejected); }, /** * @override */ _logError: function _logError() { var msg = slice$1.call(arguments); if (this.debugKey) { msg.unshift('[' + this.debugKey + ']'); } EventEmitterProto._logError.apply(this, msg); }, /** * @typesign () -> cellx.Cell; */ reap: function reap() { var slaves = this._slaves; for (var i = 0, l = slaves.length; i < l; i++) { slaves[i].reap(); } return this.off(); }, /** * @typesign () -> cellx.Cell; */ dispose: function dispose() { return this.reap(); } }; Cell.prototype[Symbol$1.iterator] = function () { return this._value[Symbol$1.iterator](); }; var map$1 = Array.prototype.map; /** * @typesign (...msg); */ function logError() { var console = global$1.console; (console && console.error || noop).call(console || global$1, map$1.call(arguments, (function (arg) { return arg === Object(arg) && arg.stack || arg; })).join(' ')); } var hasOwn = Object.prototype.hasOwnProperty; var slice = Array.prototype.slice; ErrorLogger.setHandler(logError); var assign = Object.assign || function (target, source) { for (var name in source) { target[name] = source[name]; } return target; }; /** * @typesign (value?, opts?: { * debugKey?: string, * owner?: Object, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx; * * @typesign (pull: (cell: Cell, next) -> *, opts?: { * debugKey?: string, * owner?: Object, * validate?: (value, oldValue), * merge: (value, oldValue) -> *, * put?: (cell: Cell, value, oldValue), * reap?: (), * onChange?: (evt: cellx~Event) -> ?boolean, * onError?: (evt: cellx~Event) -> ?boolean * }) -> cellx; */ function cellx(value, opts) { if (!opts) { opts = {}; } var initialValue = value; function cx(value) { var owner = this; if (!owner || owner == global$1) { owner = cx; } if (!hasOwn.call(owner, CELLS)) { Object.defineProperty(owner, CELLS, { value: new Map$1() }); } var cell = owner[CELLS].get(cx); if (!cell) { if (value === 'dispose' && arguments.length >= 2) { return; } cell = new Cell(initialValue, assign({ owner: owner }, opts)); owner[CELLS].set(cx, cell); } switch (arguments.length) { case 0: { return cell.get(); } case 1: { cell.set(value); return value; } default: { var method = value; switch (method) { case 'bind': { cx = cx.bind(owner); cx.constructor = cellx; return cx; } case 'unwrap': { return cell; } default: { var result = Cell.prototype[method].apply(cell, slice.call(arguments, 1)); return result === cell ? cx : result; } } } } } cx.constructor = cellx; if (opts.onChange || opts.onError) { cx.call(opts.owner || global$1); } return cx; } cellx.configure = function (config) { Cell.configure(config); }; cellx.ErrorLogger = ErrorLogger; cellx.EventEmitter = EventEmitter; cellx.ObservableCollectionMixin = ObservableCollectionMixin; cellx.ObservableMap = ObservableMap; cellx.ObservableList = ObservableList; cellx.Cell = Cell; cellx.autorun = Cell.autorun; cellx.transact = cellx.transaction = Cell.transaction; cellx.KEY_UID = UID; cellx.KEY_CELLS = CELLS; /** * @typesign ( * entries?: Object | Array<{ 0, 1 }> | cellx.ObservableMap, * opts?: { adoptsValueChanges?: boolean } * ) -> cellx.ObservableMap; * * @typesign ( * entries?: Object | Array<{ 0, 1 }> | cellx.ObservableMap, * adoptsValueChanges?: boolean * ) -> cellx.ObservableMap; */ function map(entries, opts) { return new ObservableMap(entries, opts); } cellx.map = map; /** * @typesign (items?: Array | cellx.ObservableList, opts?: { * adoptsValueChanges?: boolean, * comparator?: (a, b) -> int, * sorted?: boolean * }) -> cellx.ObservableList; * * @typesign (items?: Array | cellx.ObservableList, adoptsValueChanges?: boolean) -> cellx.ObservableList; */ function list(items, opts) { return new ObservableList(items, opts); } cellx.list = list; /** * @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter; */ function defineObservableProperty(obj, name, value) { var privateName = '_' + name; obj[privateName] = value instanceof Cell ? value : new Cell(value, { owner: obj }); Object.defineProperty(obj, name, { configurable: true, enumerable: true, get: function () { return this[privateName].get(); }, set: function (value) { this[privateName].set(value); } }); return obj; } cellx.defineObservableProperty = defineObservableProperty; /** * @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter; */ function defineObservableProperties(obj, props) { Object.keys(props).forEach((function (name) { defineObservableProperty(obj, name, props[name]); })); return obj; } cellx.defineObservableProperties = defineObservableProperties; /** * @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter; * @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter; */ function define(obj, name, value) { if (arguments.length == 3) { defineObservableProperty(obj, name, value); } else { defineObservableProperties(obj, name); } return obj; } cellx.define = define; cellx.JS = { is: is, Symbol: Symbol$1, Map: Map$1 }; cellx.Utils = { logError: logError, nextUID: nextUID, mixin: mixin, nextTick: nextTick$1, noop: noop }; cellx.cellx = cellx; cellx.__esModule = true; cellx.default = cellx; return cellx; })));
/** * 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. * * @emails react-core */ /*global global:true*/ 'use strict'; var mocks = require('mocks'); var React = require('React'); var ReactTestUtils = require('ReactTestUtils'); var reactComponentExpect = require('reactComponentExpect'); // TODO: Test render and all stock methods. describe('autobinding', function() { it('Holds reference to instance', function() { var mouseDidEnter = mocks.getMockFunction(); var mouseDidLeave = mocks.getMockFunction(); var mouseDidClick = mocks.getMockFunction(); var TestBindComponent = React.createClass({ getInitialState: function() { return {something: 'hi'}; }, onMouseEnter: mouseDidEnter, onMouseLeave: mouseDidLeave, onClick: mouseDidClick, // auto binding only occurs on top level functions in class defs. badIdeas: { badBind: function() { void this.state.something; }, }, render: function() { return ( <div onMouseOver={this.onMouseEnter} onMouseOut={this.onMouseLeave} onClick={this.onClick} /> ); }, }); var instance1 = <TestBindComponent />; var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); var rendered1 = reactComponentExpect(mountedInstance1) .expectRenderedChild() .instance(); var instance2 = <TestBindComponent />; var mountedInstance2 = ReactTestUtils.renderIntoDocument(instance2); var rendered2 = reactComponentExpect(mountedInstance2) .expectRenderedChild() .instance(); expect(function() { var badIdea = instance1.badIdeas.badBind; badIdea(); }).toThrow(); expect(mountedInstance1.onClick).not.toBe(mountedInstance2.onClick); ReactTestUtils.Simulate.click(rendered1); expect(mouseDidClick.mock.instances.length).toBe(1); expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); ReactTestUtils.Simulate.click(rendered2); expect(mouseDidClick.mock.instances.length).toBe(2); expect(mouseDidClick.mock.instances[1]).toBe(mountedInstance2); ReactTestUtils.Simulate.mouseOver(rendered1); expect(mouseDidEnter.mock.instances.length).toBe(1); expect(mouseDidEnter.mock.instances[0]).toBe(mountedInstance1); ReactTestUtils.Simulate.mouseOver(rendered2); expect(mouseDidEnter.mock.instances.length).toBe(2); expect(mouseDidEnter.mock.instances[1]).toBe(mountedInstance2); ReactTestUtils.Simulate.mouseOut(rendered1); expect(mouseDidLeave.mock.instances.length).toBe(1); expect(mouseDidLeave.mock.instances[0]).toBe(mountedInstance1); ReactTestUtils.Simulate.mouseOut(rendered2); expect(mouseDidLeave.mock.instances.length).toBe(2); expect(mouseDidLeave.mock.instances[1]).toBe(mountedInstance2); }); it('works with mixins', function() { var mouseDidClick = mocks.getMockFunction(); var TestMixin = { onClick: mouseDidClick, }; var TestBindComponent = React.createClass({ mixins: [TestMixin], render: function() { return <div onClick={this.onClick} />; }, }); var instance1 = <TestBindComponent />; var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); var rendered1 = reactComponentExpect(mountedInstance1) .expectRenderedChild() .instance(); ReactTestUtils.Simulate.click(rendered1); expect(mouseDidClick.mock.instances.length).toBe(1); expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); }); it('warns if you try to bind to this', function() { spyOn(console, 'error'); var TestBindComponent = React.createClass({ handleClick: function() { }, render: function() { return <div onClick={this.handleClick.bind(this)} />; }, }); ReactTestUtils.renderIntoDocument(<TestBindComponent />); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toBe( 'Warning: bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See TestBindComponent' ); }); it('does not warn if you pass an auto-bound method to setState', function() { spyOn(console, 'error'); var TestBindComponent = React.createClass({ getInitialState: function() { return {foo: 1}; }, componentDidMount: function() { this.setState({foo: 2}, this.handleUpdate); }, handleUpdate: function() { }, render: function() { return <div onClick={this.handleClick} />; }, }); ReactTestUtils.renderIntoDocument(<TestBindComponent />); expect(console.error.argsForCall.length).toBe(0); }); });
// Dependencies let React = require('react'); let type = require('focus').component.types; // Components let InputText = require('../../input/text').component; let DisplayText = require('../../display/text').component; let SelectClassic = require('../../select/classic').component; let Label = require('../../label').component; // Mixins let fieldGridBehaviourMixin = require('../../mixin/field-grid-behaviour'); let fieldBuiltInComponentsMixin = { mixins: [fieldGridBehaviourMixin], getDefaultProps() { return { /** * Does the component has a Label. * @type {Boolean} */ hasLabel: true, /** * Redefine complety the component. * @type {Object} */ FieldComponent: undefined, /** * Redefine only the input and label component. * @type {Object} */ InputLabelComponent: undefined, /** * Component for the input. * @type {Object} */ InputComponent: InputText, /** * Component for the select. * @type {Object} */ SelectComponent: SelectClassic, /** * Component for the display. * @type {Object} */ DisplayComponent: DisplayText }; }, /** @inheriteDoc */ propTypes: { hasLabel: type('bool'), labelSize: type('number'), FieldComponent: type(['object', 'function']), InputLabelComponent: type(['object', 'function']), InputComponent: type(['object', 'function']), SelectComponent: type(['object', 'function']), DisplayComponent: type(['object', 'function']) }, /** * Render the label part of the component. * @returns {[type]} [description] */ label() { if (this.props.FieldComponent || this.props.InputLabelComponent) { return undefined; } if (this.props.hasLabel) { let labelClassName = this._getLabelGridClassName(); return ( <Label style={{className: labelClassName}} name={this.props.name} key={this.props.name} isRequired={this.props.isRequired} isEdit={this.props.isEdit} /> ); } }, /** * Rendet the input part of the component. * @return {[type]} [description] */ input() { if (this.props.FieldComponent || this.props.InputLabelComponent) { return this.renderFieldComponent(); } let inputClassName = `form-control`; return ( <div className ={`${this._getContentGridClassName()} input-group`}> <this.props.InputComponent style={{class: inputClassName}} id={this.props.name} name={this.props.name} value={this.state.value} type={this.props.type} onChange={this.onInputChange} formatter={this.props.formatter} unformatter={this.props.unformatter} options={this.props.options} ref='input' /> </div> ); }, /** * [select description] * @return {[type]} [description] */ select() { if (this.props.FieldComponent || this.props.InputLabelComponent) { return this.renderFieldComponent(); } let selectClassName = `form-control`; return ( <div className ={`input-group ${this._getContentGridClassName()}`}> <this.props.SelectComponent style={{class: selectClassName}} id={this.props.name} name={this.props.name} value={this.state.value} values={this.state.values} type={this.props.type} onChange={this.onInputChange} options={this.props.options} ref='input' /> </div> ); }, /** * Render the display part of the component. * @return {object} - The display part of the compoennt if the mode is not edit. */ display() { if (this.props.FieldComponent || this.props.InputLabelComponent) { return this.renderFieldComponent(); } let displayClassName = ``; return ( <div className ={`input-group ${this._getContentGridClassName()}`}> <this.props.DisplayComponent style={{class: displayClassName}} id={this.props.name} name={this.props.name} value={this.state.value} type={this.props.type} ref='display' formatter={this.props.formatter} /> </div> ); }, /** * Render the error part of the component. * @return {object} - The error part of the component. */ error() { if (this.state.error) { if (this.props.FieldComponent) { return; } return ( /*<span class='glyphicon glyphicon-remove form-control-feedback' aria-hidden='true'></span>*/ <span className='help-block'> {this.state.error} </span> ) } }, /** * Render the help component. * @return {object} - The help part of the component. */ help() { if (this.props.help) { if (this.props.FieldComponent) { return; } return ( <span className='help-block'> {this.props.help} </span> ); } }, /** * Render the field component if it is overriden in the component definition. */ renderFieldComponent() { let Component = this.props.FieldComponent || this.props.InputLabelComponent; return React.createElement(Component, { id: this.props.name, name: this.props.name, label: this.props.label, value: this.state.value, type: this.props.type, style: this.props.style.input, labelSize: this.props.labelSize, error: this.state.error, help: this.props.help, onChange: this.onInputChange, ref: 'input' }); } }; module.exports = fieldBuiltInComponentsMixin;
/** * @jsx React.DOM */ var React = require('react'); var ApiUrl = React.createClass({ getInitialState: function(){ return { active: false } }, handleClick: function(){ var self = this; self.setState({ active: !self.state.active }); if (!self.state.active) { setTimeout(function(){ self.refs['input'].getDOMNode().focus(); }, 50); } }, handleInputSelect: function(e){ e.target.setSelectionRange(0, 9999); }, handleInputChange: function(e){ e.preventDefault(); }, render: function(){ return ( <div className="explorer-api-url"> <button className="btn btn-link field-secondary-control" title="API URL" type="button" onClick={this.handleClick}> <span className={"icon glyphicon glyphicon-chevron-" + (this.state.active ? "down" : "right") + " icon-chevron-" + (this.state.active ? "down" : "right")}></span> API Query URL </button> <div className={this.state.active ? "show" : "hide"}> <input ref="input" name="api-query" className="form-control input-sm" placeholder="API Query URL will appear here..." value={this.props.url} onClick={this.handleInputSelect} onFocus={this.handleInputSelect} onChange={this.handleInputChange} /> </div> </div> ); } }); module.exports = ApiUrl;
/** * Copyright 2013-present, 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 Danger */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var DOMLazyTree = require('./DOMLazyTree'); var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); var createNodesFromMarkup = require('fbjs/lib/createNodesFromMarkup'); var emptyFunction = require('fbjs/lib/emptyFunction'); var invariant = require('fbjs/lib/invariant'); var Danger = { /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger;
/*eslint-env mocha */ import React from 'react' import Route from '../Route' import assert from 'assert' import expect from 'expect' import { createLocation } from 'history' import { createRoutes } from '../RouteUtils' import matchRoutes from '../matchRoutes' describe('matchRoutes', function () { let routes, RootRoute, UsersRoute, UsersIndexRoute, UserRoute, PostRoute, FilesRoute, AboutRoute, TeamRoute, ProfileRoute, CatchAllRoute beforeEach(function () { /* <Route> <Route path="users"> <Index /> <Route path=":userID"> <Route path="/profile" /> </Route> <Route path="/team" /> </Route> </Route> <Route path="/about" /> <Route path="*" /> */ routes = [ RootRoute = { childRoutes: [ UsersRoute = { path: 'users', indexRoute: (UsersIndexRoute = {}), childRoutes: [ UserRoute = { path: ':userID', childRoutes: [ ProfileRoute = { path: '/profile' }, PostRoute = { path: ':postID' } ] }, TeamRoute = { path: '/team' } ] } ] }, FilesRoute = { path: '/files/*/*.jpg' }, AboutRoute = { path: '/about' }, CatchAllRoute = { path: '*' } ] }) function describeRoutes() { describe('when the location matches an index route', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/users'), function (error, match) { assert(match) expect(match.routes).toEqual([ RootRoute, UsersRoute, UsersIndexRoute ]) done() }) }) }) describe('when the location matches a nested route with params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/users/5'), function (error, match) { assert(match) expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute ]) expect(match.params).toEqual({ userID: '5' }) done() }) }) }) describe('when the location matches a deeply nested route with params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/users/5/abc'), function (error, match) { assert(match) expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute, PostRoute ]) expect(match.params).toEqual({ userID: '5', postID: 'abc' }) done() }) }) }) describe('when the location matches a nested route with multiple splat params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/files/a/b/c.jpg'), function (error, match) { assert(match) expect(match.routes).toEqual([ FilesRoute ]) expect(match.params).toEqual({ splat: [ 'a', 'b/c' ] }) done() }) }) }) describe('when the location matches a route with hash', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/users#about'), function (error, match) { assert(match) expect(match.routes).toEqual([ RootRoute, UsersRoute, UsersIndexRoute ]) done() }) }) }) describe('when the location matches a deeply nested route with params and hash', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/users/5/abc#about'), function (error, match) { assert(match) expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute, PostRoute ]) expect(match.params).toEqual({ userID: '5', postID: 'abc' }) done() }) }) }) describe('when the location matches an absolute route', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/about'), function (error, match) { assert(match) expect(match.routes).toEqual([ AboutRoute ]) done() }) }) }) describe('when the location does not match any routes', function () { it('matches the "catch-all" route', function (done) { matchRoutes(routes, createLocation('/not-found'), function (error, match) { assert(match) expect(match.routes).toEqual([ CatchAllRoute ]) done() }) }) }) } describe('a synchronous route config', function () { describeRoutes() describe('when the location matches a nested absolute route', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/team'), function (error, match) { assert(match) expect(match.routes).toEqual([ RootRoute, UsersRoute, TeamRoute ]) done() }) }) }) describe('when the location matches an absolute route nested under a route with params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/profile'), function (error, match) { assert(match) expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute, ProfileRoute ]) expect(match.params).toEqual({}) // no userID param done() }) }) }) }) describe('an asynchronous route config', function () { function makeAsyncRouteConfig(routes) { routes.forEach(function (route) { const { childRoutes, indexRoute } = route if (childRoutes) { delete route.childRoutes route.getChildRoutes = function (location, callback) { setTimeout(function () { callback(null, childRoutes) }) } makeAsyncRouteConfig(childRoutes) } if (indexRoute) { delete route.indexRoute route.getIndexRoute = function (location, callback) { setTimeout(function () { callback(null, indexRoute) }) } } }) } beforeEach(function () { makeAsyncRouteConfig(routes) }) describeRoutes() }) describe('an asynchronous JSX route config', function () { let getChildRoutes, getIndexRoute, jsxRoutes beforeEach(function () { getChildRoutes = function (location, callback) { setTimeout(function () { callback(null, <Route path=":userID" />) }) } getIndexRoute = function (location, callback) { setTimeout(function () { callback(null, <Route name='jsx' />) }) } jsxRoutes = createRoutes([ <Route name="users" path="users" getChildRoutes={getChildRoutes} getIndexRoute={getIndexRoute} /> ]) }) it('when getChildRoutes callback returns reactElements', function(done) { matchRoutes(jsxRoutes, createLocation('/users/5'), function (error, match) { assert(match) expect(match.routes.map(r => r.path)).toEqual([ 'users', ':userID' ]) expect(match.params).toEqual({ userID: '5' }) done() }) }) it('when getIndexRoute callback returns reactElements', function(done) { matchRoutes(jsxRoutes, createLocation('/users'), function (error, match) { assert(match) expect(match.routes.map(r => r.name)).toEqual([ 'users', 'jsx' ]) done() }) }) }) })
/*! ReactInstantSearch 4.0.0-beta.4 | © Algolia, inc. | https://community.algolia.com/react-instantsearch/ */ (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["Dom"] = factory(require("react"), require("react-dom")); else root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Dom"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_429__) { 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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 432); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (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; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, 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. */ if (false) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(208)(); } /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEqual2 = __webpack_require__(104); var _isEqual3 = _interopRequireDefault(_isEqual2); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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 _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; }; }(); exports.default = createConnector; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); 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; } /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = (0, _has3.default)(connectorDesc, 'refine'); var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters'); var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata'); var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState'); var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { _inherits(Connector, _Component); function Connector(props, context) { _classCallCheck(this, Connector); var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais; var store = _context$ais.store; var widgetsManager = _context$ais.widgetsManager; var multiIndexContext = context.multiIndexContext; _this.state = { props: _this.getProvidedProps(props) }; _this.unsubscribe = store.subscribe(function () { _this.setState({ props: _this.getProvidedProps(_this.props) }); }); var getSearchParameters = hasSearchParameters ? function (searchParameters) { return connectorDesc.getSearchParameters.call(_this, searchParameters, _this.props, store.getState().widgets); } : null; var getMetadata = hasMetadata ? function (nextWidgetsState) { return connectorDesc.getMetadata.call(_this, _this.props, nextWidgetsState); } : null; var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) { return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState); } : null; if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget({ getSearchParameters: getSearchParameters, getMetadata: getMetadata, transitionState: transitionState, multiIndexContext: multiIndexContext }); } return _this; } _createClass(Connector, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!(0, _isEqual3.default)(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); //will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange((0, _utils.removeEmptyKey)(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props); } }, { key: 'render', value: function render() { var _this2 = this; if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues, searchForFacetValues: function searchForFacetValues(facetName, query) { if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.'); } _this2.searchForFacetValues(facetName, query); } } : {}; return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: _propTypes2.default.object.isRequired, multiIndexContext: _propTypes2.default.object }, _initialiseProps = function _initialiseProps() { var _this3 = this; this.getProvidedProps = function (props) { var store = _this3.context.ais.store; var _store$getState = store.getState(); var results = _store$getState.results; var searching = _store$getState.searching; var error = _store$getState.error; var widgets = _store$getState.widgets; var metadata = _store$getState.metadata; var resultsFacetValues = _store$getState.resultsFacetValues; var searchState = { results: results, searching: searching, error: error }; return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args)); }; }, _temp; }; } /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(78); /** 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) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _get2 = __webpack_require__(73); var _get3 = _interopRequireDefault(_get2); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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; }; exports.getIndex = getIndex; exports.getResults = getResults; exports.hasMultipleIndex = hasMultipleIndex; exports.refineValue = refineValue; exports.getCurrentRefinementValue = getCurrentRefinementValue; exports.cleanUpValue = cleanUpValue; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function getIndex(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndex(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndex(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var index = getIndex(context); var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, nextRefinement, page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) { var _extends4; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], (_extends4 = {}, _defineProperty(_extends4, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), _defineProperty(_extends4, 'page', 1), _extends4)))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends(_defineProperty({}, namespace, nextRefinement), page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page); } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) { var index = getIndex(context); var refinements = hasMultipleIndex(context) && (0, _has3.default)(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && (0, _has3.default)(searchState, id); if (refinements) { var currentRefinement = hasMultipleIndex(context) ? (0, _get3.default)(searchState.indices[index], id) : (0, _get3.default)(searchState, id); return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var index = getIndex(context); return hasMultipleIndex(context) ? (0, _omit3.default)(searchState, 'indices.' + index + '.' + id) : (0, _omit3.default)(searchState, '' + id); } /***/ }), /* 6 */ /***/ (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; /***/ }), /* 7 */ /***/ (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; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), getRawTag = __webpack_require__(157), objectToString = __webpack_require__(184); /** `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; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(88), baseKeys = __webpack_require__(76), isArrayLike = __webpack_require__(11); /** * 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; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(136), getValue = __webpack_require__(159); /** * 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; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isLength = __webpack_require__(48); /** * 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; /***/ }), /* 12 */ /***/ (function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(265), baseMatchesProperty = __webpack_require__(266), identity = __webpack_require__(24), isArray = __webpack_require__(0), property = __webpack_require__(335); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNames; var _classnames = __webpack_require__(418); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var prefix = 'ais'; function classNames(block) { return function () { for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } return { className: (0, _classnames2.default)(elements.filter(function (element) { return element !== undefined && element !== false; }).map(function (element) { return prefix + '-' + block + '__' + element; })) }; }; } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { var baseKeys = __webpack_require__(76), getTag = __webpack_require__(56), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isArrayLike = __webpack_require__(11), isBuffer = __webpack_require__(26), isPrototype = __webpack_require__(37), isTypedArray = __webpack_require__(36); /** `Object#toString` result references. */ var mapTag = '[object Map]', setTag = '[object Set]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } module.exports = isEmpty; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), baseMap = __webpack_require__(138), isArray = __webpack_require__(0); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, baseIteratee(iteratee, 3)); } module.exports = map; /***/ }), /* 18 */ /***/ (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; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObject = __webpack_require__(6); /** `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; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24), overRest = __webpack_require__(185), setToString = __webpack_require__(100); /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } module.exports = baseRest; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isKey = __webpack_require__(72), stringToPath = __webpack_require__(196), toString = __webpack_require__(75); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(90), baseAssignValue = __webpack_require__(42); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }), /* 24 */ /***/ (function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(134), isObjectLike = __webpack_require__(7); /** 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; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3), stubFalse = __webpack_require__(206); /** 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__(55)(module))) /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(169), listCacheDelete = __webpack_require__(170), listCacheGet = __webpack_require__(171), listCacheHas = __webpack_require__(172), listCacheSet = __webpack_require__(173); /** * 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; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18); /** * 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; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(166); /** * 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; /***/ }), /* 31 */ /***/ (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; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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; }; exports.default = translatable; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); var _propTypes = __webpack_require__(403); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function translatable(defaultTranslations) { return function (Composed) { function Translatable(props) { var translations = props.translations; var otherProps = _objectWithoutProperties(props, ['translations']); var translate = function translate(key) { for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } var translation = translations && (0, _has3.default)(translations, key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { return translation.apply(undefined, params); } return translation; }; return _react2.default.createElement(Composed, _extends({ translate: translate }, otherProps)); } Translatable.displayName = 'Translatable(' + (0, _utils.getDisplayName)(Composed) + ')'; Translatable.propTypes = { translations: (0, _propTypes.withKeysPropType)(Object.keys(defaultTranslations)) }; return Translatable; }; } /***/ }), /* 34 */ /***/ (function(module, exports) { /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } module.exports = replaceHolders; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(85), baseEach = __webpack_require__(63), castFunction = __webpack_require__(143), isArray = __webpack_require__(0); /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, castFunction(iteratee)); } module.exports = forEach; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(137), baseUnary = __webpack_require__(45), nodeUtil = __webpack_require__(183); /* 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; /***/ }), /* 37 */ /***/ (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; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseClone = __webpack_require__(256), baseUnset = __webpack_require__(278), castPath = __webpack_require__(21), copyObject = __webpack_require__(22), customOmitClone = __webpack_require__(302), flatRest = __webpack_require__(155), getAllKeysIn = __webpack_require__(96); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); module.exports = omit; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(174), mapCacheDelete = __webpack_require__(175), mapCacheGet = __webpack_require__(176), mapCacheHas = __webpack_require__(177), mapCacheSet = __webpack_require__(178); /** * 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; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), stackClear = __webpack_require__(191), stackDelete = __webpack_require__(192), stackGet = __webpack_require__(193), stackHas = __webpack_require__(194), stackSet = __webpack_require__(195); /** * 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; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(152); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(132), keys = __webpack_require__(9); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(130), baseIsNaN = __webpack_require__(263), strictIndexOf = __webpack_require__(317); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }), /* 45 */ /***/ (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; /***/ }), /* 46 */ /***/ (function(module, exports) { /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } module.exports = getHolder; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { var createFind = __webpack_require__(298), findIndex = __webpack_require__(198); /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); module.exports = find; /***/ }), /* 48 */ /***/ (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; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), getPrototype = __webpack_require__(70), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** 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 infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isArray = __webpack_require__(0), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } module.exports = isString; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(88), baseKeysIn = __webpack_require__(264), isArrayLike = __webpack_require__(11); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @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; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(89), baseEach = __webpack_require__(63), baseIteratee = __webpack_require__(13), baseReduce = __webpack_require__(273), isArray = __webpack_require__(0); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach); } module.exports = reduce; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(219); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }), /* 54 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 55 */ /***/ (function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if(!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { var DataView = __webpack_require__(122), Map = __webpack_require__(39), Promise = __webpack_require__(125), Set = __webpack_require__(126), WeakMap = __webpack_require__(84), baseGetTag = __webpack_require__(8), toSource = __webpack_require__(80); /** `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; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(133), hasPath = __webpack_require__(97); /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } module.exports = has; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defer = undefined; var _isPlainObject2 = __webpack_require__(49); var _isPlainObject3 = _interopRequireDefault(_isPlainObject2); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); exports.shallowEqual = shallowEqual; exports.isSpecialClick = isSpecialClick; exports.capitalize = capitalize; exports.assertFacetDefined = assertFacetDefined; exports.getDisplayName = getDisplayName; exports.removeEmptyKey = removeEmptyKey; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } 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 hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); } function capitalize(key) { return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1); } function assertFacetDefined(searchParameters, searchResults, facet) { var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet); var wasReceived = Boolean(searchResults.getFacetByName(facet)); if (searchResults.nbHits > 0 && wasRequested && !wasReceived) { // eslint-disable-next-line no-console console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.'); } } function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; } var resolved = Promise.resolve(); var defer = exports.defer = function defer(f) { resolved.then(f); }; function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if ((0, _isEmpty3.default)(value) && (0, _isPlainObject3.default)(value)) { delete obj[key]; } else if ((0, _isPlainObject3.default)(value)) { removeEmptyKey(value); } }); return obj; } /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(40), setCacheAdd = __webpack_require__(186), setCacheHas = __webpack_require__(187); /** * * 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; /***/ }), /* 60 */ /***/ (function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }), /* 61 */ /***/ (function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); module.exports = baseCreate; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43), createBaseEach = __webpack_require__(294); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), toKey = __webpack_require__(23); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(135), isObjectLike = __webpack_require__(7); /** * 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 {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), arrayMap = __webpack_require__(12), isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }), /* 67 */ /***/ (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; /***/ }), /* 68 */ /***/ (function(module, exports) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), isObject = __webpack_require__(6); /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } module.exports = createCtor; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(86), stubArray = __webpack_require__(107); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(0), isSymbol = __webpack_require__(27); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44), toInteger = __webpack_require__(53); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } module.exports = indexOf; /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(66); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(37), nativeKeys = __webpack_require__(182); /** 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; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arraySome = __webpack_require__(128), cacheHas = __webpack_require__(67); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_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 & COMPARE_UNORDERED_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, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 79 */ /***/ (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; /***/ }), /* 80 */ /***/ (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; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var keys = __webpack_require__(9); var intersection = __webpack_require__(328); var forOwn = __webpack_require__(326); var forEach = __webpack_require__(35); var filter = __webpack_require__(102); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var omit = __webpack_require__(38); var indexOf = __webpack_require__(74); var isNaN = __webpack_require__(218); var isArray = __webpack_require__(0); var isEmpty = __webpack_require__(16); var isEqual = __webpack_require__(104); var isUndefined = __webpack_require__(203); var isString = __webpack_require__(50); var isFunction = __webpack_require__(19); var find = __webpack_require__(47); var trim = __webpack_require__(207); var defaults = __webpack_require__(101); var merge = __webpack_require__(105); var valToNumber = __webpack_require__(246); var filterState = __webpack_require__(242); var RefinementList = __webpack_require__(241); /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find(array, function(currentValue) { return isEqual(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * seperated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each facetted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach(numberKeys, function(k) { var value = partialState[k]; if (isString(value)) { var parsedValue = parseFloat(value); numbers[k] = isNaN(parsedValue) ? value : parsedValue; } }); if (partialState.numericRefinements) { var numericRefinements = {}; forEach(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach(operators, function(values, operator) { var parsedValues = map(values, function(v) { if (isArray(v)) { return map(v, function(vPrime) { if (isString(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optionnal string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) facetting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive facetting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge({}, this.numericRefinements); mod[attribute] = merge({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optionnal string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined(attribute)) { return {}; } else if (isString(attribute)) { return omit(this.numericRefinements, attribute); } else if (isFunction(attribute)) { return reduce(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach(operators, function(values, operator) { var outValues = []; forEach(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty(outValues)) operatorList[operator] = outValues; }); if (!isEmpty(operatorList)) memo[key] = operatorList; return memo; }, {}); } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the facetting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the facetting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the facetted attribute. * @method * @param {string} facet name of the attribute used for facetting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for facetting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for facetting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value, optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for facetting * @param {string} [value] optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value optionnal, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value optionnal, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined(value) && isUndefined(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined(this.numericRefinements[attribute][operator]); if (isUndefined(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber(value); var isAttributeValueDefined = !isUndefined( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection( keys(this.numericRefinements), this.disjunctiveFacets ); return keys(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map(this.hierarchicalFacets, 'name'), keys(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter(this.disjunctiveFacets, function(f) { return indexOf(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn(this, function(paramValue, paramName) { if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys(params); forEach(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map(path, trim); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ module.exports = SearchParameters; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), baseLodash = __webpack_require__(92); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; module.exports = LazyWrapper; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(3); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }), /* 85 */ /***/ (function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }), /* 86 */ /***/ (function(module, exports) { /** * A specialized version of `_.filter` 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 {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(142), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isIndex = __webpack_require__(31), isTypedArray = __webpack_require__(36); /** 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; /***/ }), /* 89 */ /***/ (function(module, exports) { /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } module.exports = arrayReduce; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), eq = __webpack_require__(18); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), isArray = __webpack_require__(0); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }), /* 92 */ /***/ (function(module, exports) { /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } module.exports = baseLodash; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { var Uint8Array = __webpack_require__(83); /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } module.exports = cloneArrayBuffer; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(140), createBind = __webpack_require__(296), createCurry = __webpack_require__(297), createHybrid = __webpack_require__(150), createPartial = __webpack_require__(300), getData = __webpack_require__(156), mergeData = __webpack_require__(312), setData = __webpack_require__(188), setWrapToString = __webpack_require__(189), toInteger = __webpack_require__(53); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } module.exports = createWrap; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(91), getSymbols = __webpack_require__(71), keys = __webpack_require__(9); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(91), getSymbolsIn = __webpack_require__(158), keysIn = __webpack_require__(51); /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } module.exports = getAllKeysIn; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isIndex = __webpack_require__(31), isLength = __webpack_require__(48), toKey = __webpack_require__(23); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; /***/ }), /* 98 */ /***/ (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; /***/ }), /* 99 */ /***/ (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; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(275), shortOut = __webpack_require__(190); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), assignInWith = __webpack_require__(322), baseRest = __webpack_require__(20), customDefaultsAssignIn = __webpack_require__(301); /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, customDefaultsAssignIn); return apply(assignInWith, undefined, args); }); module.exports = defaults; /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(86), baseFilter = __webpack_require__(258), baseIteratee = __webpack_require__(13), isArray = __webpack_require__(0); /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, baseIteratee(predicate, 3)); } module.exports = filter; /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(11), isObjectLike = __webpack_require__(7); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(65); /** * 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 compared by strict equality, i.e. `===`. * * @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; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { var baseMerge = __webpack_require__(267), createAssigner = __webpack_require__(149); /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); module.exports = merge; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { var baseOrderBy = __webpack_require__(269), isArray = __webpack_require__(0); /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } module.exports = orderBy; /***/ }), /* 107 */ /***/ (function(module, exports) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); exports.arrayToObject = function (source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function (target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { target[source] = true; } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (Object.prototype.hasOwnProperty.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function (str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D || // - c === 0x2E || // . c === 0x5F || // _ c === 0x7E || // ~ (c >= 0x30 && c <= 0x39) || // 0-9 (c >= 0x41 && c <= 0x5A) || // a-z (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function (obj, references) { if (typeof obj !== 'object' || obj === null) { return obj; } var refs = references || []; var lookup = refs.indexOf(obj); if (lookup !== -1) { return refs[lookup]; } refs.push(obj); if (Array.isArray(obj)) { var compacted = []; for (var i = 0; i < obj.length; ++i) { if (obj[i] && typeof obj[i] === 'object') { compacted.push(exports.compact(obj[i], refs)); } else if (typeof obj[i] !== 'undefined') { compacted.push(obj[i]); } } return compacted; } var keys = Object.keys(obj); keys.forEach(function (key) { obj[key] = exports.compact(obj[key], refs); }); return obj; }; exports.isRegExp = function (obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function (obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; /***/ }), /* 109 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 110 */ /***/ (function(module, exports) { var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { var basePick = __webpack_require__(270), flatRest = __webpack_require__(155); /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); module.exports = pick; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - Name of the attribute for faceting * @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied */ function getId(props) { return props.attributeName; } var namespace = 'range'; function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), {}, function (currentRefinement) { var min = currentRefinement.min; var max = currentRefinement.max; if (typeof min === 'string') { min = parseInt(min, 10); } if (typeof max === 'string') { max = parseInt(max, 10); } return { min: min, max: max }; }); } function _refine(props, searchState, nextRefinement, context) { if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) { throw new Error("You can't provide non finite values to the range connector"); } var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaRange', propTypes: { id: _propTypes2.default.string, attributeName: _propTypes2.default.string.isRequired, defaultRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number.isRequired, max: _propTypes2.default.number.isRequired }), min: _propTypes2.default.number, max: _propTypes2.default.number }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var min = props.min; var max = props.max; var hasMin = typeof min !== 'undefined'; var hasMax = typeof max !== 'undefined'; var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!hasMin || !hasMax) { if (!results) { return { canRefine: false }; } var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; if (!stats) { return { canRefine: false }; } if (!hasMin) { min = stats.min; } if (!hasMax) { max = stats.max; } } var count = results ? results.getFacetValues(attributeName).map(function (v) { return { value: v.name, count: v.count }; }) : []; var _getCurrentRefinement = getCurrentRefinement(props, searchState, this.context); var _getCurrentRefinement2 = _getCurrentRefinement.min; var valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2; var _getCurrentRefinement3 = _getCurrentRefinement.max; var valueMax = _getCurrentRefinement3 === undefined ? max : _getCurrentRefinement3; return { min: min, max: max, currentRefinement: { min: valueMin, max: valueMax }, count: count, canRefine: count.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState, this.context); params = params.addDisjunctiveFacet(attributeName); var min = currentRefinement.min; var max = currentRefinement.max; if (typeof min !== 'undefined') { params = params.addNumericRefinement(attributeName, '>=', min); } if (typeof max !== 'undefined') { params = params.addNumericRefinement(attributeName, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); var item = void 0; var hasMin = typeof currentRefinement.min !== 'undefined'; var hasMax = typeof currentRefinement.max !== 'undefined'; if (hasMin || hasMax) { var itemLabel = ''; if (hasMin) { itemLabel += currentRefinement.min + ' <= '; } itemLabel += props.attributeName; if (hasMax) { itemLabel += ' <= ' + currentRefinement.max; } item = { label: itemLabel, currentRefinement: currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _cleanUp(props, nextState, _this.context); } }; } return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: item ? [item] : [] }; } }); /***/ }), /* 113 */ /***/ (function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(239); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(238); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54), __webpack_require__(109))) /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var compact = __webpack_require__(324); var indexOf = __webpack_require__(74); var findIndex = __webpack_require__(198); var get = __webpack_require__(73); var sumBy = __webpack_require__(337); var find = __webpack_require__(47); var includes = __webpack_require__(327); var map = __webpack_require__(17); var orderBy = __webpack_require__(106); var defaults = __webpack_require__(101); var merge = __webpack_require__(105); var isArray = __webpack_require__(0); var isFunction = __webpack_require__(19); var partial = __webpack_require__(332); var partialRight = __webpack_require__(333); var formatSort = __webpack_require__(116); var generateHierarchicalTree = __webpack_require__(244); /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the facetting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objets matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} value the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric fitlers. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach(result.facets, function(facetResults, dfacet) { var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state)); this.facets = compact(this.facets); this.disjunctiveFacets = compact(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the attribute facetted * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find(this.facets, predicate) || find(this.disjunctiveFacets, predicate) || find(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the facetted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find(results.facets, predicate); if (!facet) return []; return map(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map(node.data, partial(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (isArray(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (isArray(facetValues)) { return orderBy(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight(orderBy, order[0], order[1]), facetValues); } else if (isFunction(options.sortBy)) { if (isArray(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the facetted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach(state.facetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach(state.facetsExcludes, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach(state.numericRefinements, function(operators, attributeName) { forEach(operators, function(values, operator) { forEach(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find(resultsFacets, {name: attributeName}); var count = get(facet, 'data[' + name + ']'); var exhaustive = get(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find(facet.data, {name: splitted[i]}); } var count = get(facet, 'count'); var exhaustive = get(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } module.exports = SearchResults; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var reduce = __webpack_require__(52); var find = __webpack_require__(47); var startsWith = __webpack_require__(336); /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ module.exports = function formatSort(sortBy, defaults) { return reduce(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find(defaults, function(predicate) { return startsWith(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var shortener = __webpack_require__(243); var SearchParameters = __webpack_require__(81); var qs = __webpack_require__(342); var bind = __webpack_require__(323); var forEach = __webpack_require__(35); var pick = __webpack_require__(111); var map = __webpack_require__(17); var mapKeys = __webpack_require__(329); var mapValues = __webpack_require__(330); var isString = __webpack_require__(50); var isPlainObject = __webpack_require__(49); var isArray = __webpack_require__(0); var invert = __webpack_require__(201); var encode = __webpack_require__(108).encode; function recursiveEncode(input) { if (isPlainObject(input)) { return mapValues(input, recursiveEncode); } if (isArray(input)) { return map(input, recursiveEncode); } if (isString(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ exports.getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert(mapping); var partialStateWithPrefix = qs.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState); return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ exports.getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert(mapping); var foreignConfig = {}; var config = qs.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ exports.getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (moreAttributes) { var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = qs.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return qs.stringify(encodedState, {encode: safe, sort: sort}); }; /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = '2.19.0'; /***/ }), /* 119 */ /***/ (function(module, exports) { module.exports = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, 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. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, 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. * */ /** * 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. */ var validateFormat = function validateFormat(format) {}; if (false) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); 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; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(160), hashDelete = __webpack_require__(161), hashGet = __webpack_require__(162), hashHas = __webpack_require__(163), hashSet = __webpack_require__(164); /** * 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; /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), baseLodash = __webpack_require__(92); /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; module.exports = LodashWrapper; /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10), root = __webpack_require__(3); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }), /* 127 */ /***/ (function(module, exports) { /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } module.exports = arrayIncludesWith; /***/ }), /* 128 */ /***/ (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; /***/ }), /* 129 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), eq = __webpack_require__(18); /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignMergeValue; /***/ }), /* 130 */ /***/ (function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), isFlattenable = __webpack_require__(310); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(295); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }), /* 133 */ /***/ (function(module, exports) { /** 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 `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } module.exports = baseHas; /***/ }), /* 134 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `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; /***/ }), /* 135 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), equalArrays = __webpack_require__(77), equalByTag = __webpack_require__(153), equalObjects = __webpack_require__(154), getTag = __webpack_require__(56), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isTypedArray = __webpack_require__(36); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; 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, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_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, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isMasked = __webpack_require__(167), isObject = __webpack_require__(6), toSource = __webpack_require__(80); /** * 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; /***/ }), /* 137 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isLength = __webpack_require__(48), isObjectLike = __webpack_require__(7); /** `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; /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(63), isArrayLike = __webpack_require__(11); /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } module.exports = baseMap; /***/ }), /* 139 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64), baseSet = __webpack_require__(274), castPath = __webpack_require__(21); /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } module.exports = basePickBy; /***/ }), /* 140 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24), metaMap = __webpack_require__(181); /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; module.exports = baseSetData; /***/ }), /* 141 */ /***/ (function(module, exports) { /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } module.exports = baseSlice; /***/ }), /* 142 */ /***/ (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; /***/ }), /* 143 */ /***/ (function(module, exports, __webpack_require__) { var identity = __webpack_require__(24); /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } module.exports = castFunction; /***/ }), /* 144 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3); /** 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, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93); /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } module.exports = cloneTypedArray; /***/ }), /* 146 */ /***/ (function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } module.exports = composeArgs; /***/ }), /* 147 */ /***/ (function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } module.exports = composeArgsRight; /***/ }), /* 148 */ /***/ (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; /***/ }), /* 149 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), isIterateeCall = __webpack_require__(217); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; /***/ }), /* 150 */ /***/ (function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(146), composeArgsRight = __webpack_require__(147), countHolders = __webpack_require__(293), createCtor = __webpack_require__(69), createRecurry = __webpack_require__(151), getHolder = __webpack_require__(46), reorder = __webpack_require__(316), replaceHolders = __webpack_require__(34), root = __webpack_require__(3); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_ARY_FLAG = 128, WRAP_FLIP_FLAG = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } module.exports = createHybrid; /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { var isLaziable = __webpack_require__(311), setData = __webpack_require__(188), setWrapToString = __webpack_require__(189); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } module.exports = createRecurry; /***/ }), /* 152 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(10); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }), /* 153 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), Uint8Array = __webpack_require__(83), eq = __webpack_require__(18), equalArrays = __webpack_require__(77), mapToArray = __webpack_require__(98), setToArray = __webpack_require__(99); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @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, bitmask, customizer, equalFunc, 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 & COMPARE_PARTIAL_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 |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(95); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(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, bitmask, customizer, 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; /***/ }), /* 155 */ /***/ (function(module, exports, __webpack_require__) { var flatten = __webpack_require__(199), overRest = __webpack_require__(185), setToString = __webpack_require__(100); /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } module.exports = flatRest; /***/ }), /* 156 */ /***/ (function(module, exports, __webpack_require__) { var metaMap = __webpack_require__(181), noop = __webpack_require__(331); /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; module.exports = getData; /***/ }), /* 157 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** 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; /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(61), getPrototype = __webpack_require__(70), getSymbols = __webpack_require__(71), stubArray = __webpack_require__(107); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; module.exports = getSymbolsIn; /***/ }), /* 159 */ /***/ (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; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** * 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; /***/ }), /* 161 */ /***/ (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; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(32); /** 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; /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(62), getPrototype = __webpack_require__(70), isPrototype = __webpack_require__(37); /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } module.exports = initCloneObject; /***/ }), /* 166 */ /***/ (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; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(148); /** 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; /***/ }), /* 168 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }), /* 169 */ /***/ (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; /***/ }), /* 170 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** 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; /***/ }), /* 171 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * 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; /***/ }), /* 172 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * 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; /***/ }), /* 173 */ /***/ (function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(29); /** * 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; /***/ }), /* 174 */ /***/ (function(module, exports, __webpack_require__) { var Hash = __webpack_require__(123), ListCache = __webpack_require__(28), Map = __webpack_require__(39); /** * 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; /***/ }), /* 175 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(30); /** * 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; /***/ }), /* 179 */ /***/ (function(module, exports) { /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; /***/ }), /* 180 */ /***/ (function(module, exports, __webpack_require__) { var memoize = __webpack_require__(205); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }), /* 181 */ /***/ (function(module, exports, __webpack_require__) { var WeakMap = __webpack_require__(84); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; module.exports = metaMap; /***/ }), /* 182 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(79); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(78); /** 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 && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }), /* 184 */ /***/ (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; /***/ }), /* 185 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; /***/ }), /* 186 */ /***/ (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; /***/ }), /* 187 */ /***/ (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; /***/ }), /* 188 */ /***/ (function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(140), shortOut = __webpack_require__(190); /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); module.exports = setData; /***/ }), /* 189 */ /***/ (function(module, exports, __webpack_require__) { var getWrapDetails = __webpack_require__(305), insertWrapDetails = __webpack_require__(309), setToString = __webpack_require__(100), updateWrapDetails = __webpack_require__(320); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } module.exports = setWrapToString; /***/ }), /* 190 */ /***/ (function(module, exports) { /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; /***/ }), /* 191 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28); /** * 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; /***/ }), /* 192 */ /***/ (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; /***/ }), /* 193 */ /***/ (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; /***/ }), /* 194 */ /***/ (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; /***/ }), /* 195 */ /***/ (function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(28), Map = __webpack_require__(39), MapCache = __webpack_require__(40); /** 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; /***/ }), /* 196 */ /***/ (function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(180); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }), /* 197 */ /***/ (function(module, exports) { /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; /***/ }), /* 198 */ /***/ (function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(130), baseIteratee = __webpack_require__(13), toInteger = __webpack_require__(53); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, baseIteratee(predicate, 3), index); } module.exports = findIndex; /***/ }), /* 199 */ /***/ (function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(131); /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } module.exports = flatten; /***/ }), /* 200 */ /***/ (function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(259), hasPath = __webpack_require__(97); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }), /* 201 */ /***/ (function(module, exports, __webpack_require__) { var constant = __webpack_require__(197), createInverter = __webpack_require__(299), identity = __webpack_require__(24); /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); module.exports = invert; /***/ }), /* 202 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(8), isObjectLike = __webpack_require__(7); /** `Object#toString` result references. */ var numberTag = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } module.exports = isNumber; /***/ }), /* 203 */ /***/ (function(module, exports) { /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } module.exports = isUndefined; /***/ }), /* 204 */ /***/ (function(module, exports) { /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } module.exports = last; /***/ }), /* 205 */ /***/ (function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(40); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }), /* 206 */ /***/ (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; /***/ }), /* 207 */ /***/ (function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(66), castSlice = __webpack_require__(281), charsEndIndex = __webpack_require__(282), charsStartIndex = __webpack_require__(283), stringToArray = __webpack_require__(318), toString = __webpack_require__(75); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } module.exports = trim; /***/ }), /* 208 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2013-present, 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. */ var emptyFunction = __webpack_require__(120); var invariant = __webpack_require__(121); module.exports = function() { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); }; shim.isRequired = shim; function getShim() { return shim; }; var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 209 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var replace = String.prototype.replace; var percentTwenties = /%20/g; module.exports = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; /***/ }), /* 210 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items); } } return res; }, []); return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); /***/ }), /* 211 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _highlight = __webpack_require__(237); var _highlight2 = _interopRequireDefault(_highlight); var _highlightTags = __webpack_require__(213); var _highlightTags2 = _interopRequireDefault(_highlightTags); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var highlight = function highlight(_ref) { var attributeName = _ref.attributeName; var hit = _ref.hit; var highlightProperty = _ref.highlightProperty; return (0, _highlight2.default)({ attributeName: attributeName, hit: hit, preTag: _highlightTags2.default.highlightPreTag, postTag: _highlightTags2.default.highlightPostTag, highlightProperty: highlightProperty }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`. * @example * const CustomHighlight = connectHighlight(({highlight, attributeName, hit, highlightProperty) => { * const parsedHit = highlight({attributeName, hit, highlightProperty}); * return parsedHit.map(part => { * if(part.isHighlighted) return <em>{part.value}</em>; * return part.value: * }); * }); */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /***/ }), /* 212 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _SearchBox = __webpack_require__(346); var _SearchBox2 = _interopRequireDefault(_SearchBox); 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 itemsPropType = _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.any, label: _propTypes2.default.string.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var List = function (_Component) { _inherits(List, _Component); function List() { _classCallCheck(this, List); var _this = _possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this)); _this.defaultProps = { isFromSearch: false }; _this.onShowMoreClick = function () { _this.setState(function (state) { return { extended: !state.extended }; }); }; _this.getLimit = function () { var _this$props = _this.props; var limitMin = _this$props.limitMin; var limitMax = _this$props.limitMax; var extended = _this.state.extended; return extended ? limitMax : limitMin; }; _this.resetQuery = function () { _this.setState({ query: '' }); }; _this.renderItem = function (item, resetQuery) { var items = item.items && _react2.default.createElement( 'div', _this.props.cx('itemItems'), item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }) ); return _react2.default.createElement( 'div', _extends({ key: item.key || item.label }, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')), _this.props.renderItem(item, resetQuery), items ); }; _this.state = { extended: false, query: '' }; return _this; } _createClass(List, [{ key: 'renderShowMore', value: function renderShowMore() { var _props = this.props; var showMore = _props.showMore; var translate = _props.translate; var cx = _props.cx; var extended = this.state.extended; var disabled = this.props.limitMin >= this.props.items.length; if (!showMore) { return null; } return _react2.default.createElement( 'button', _extends({ disabled: disabled }, cx('showMore', disabled && 'showMoreDisabled'), { onClick: this.onShowMoreClick }), translate('showMore', extended) ); } }, { key: 'renderSearchBox', value: function renderSearchBox() { var _this2 = this; var _props2 = this.props; var cx = _props2.cx; var searchForItems = _props2.searchForItems; var isFromSearch = _props2.isFromSearch; var translate = _props2.translate; var items = _props2.items; var selectItem = _props2.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? _react2.default.createElement( 'div', cx('noResults'), translate('noResults') ) : null; return _react2.default.createElement( 'div', cx('SearchBox'), _react2.default.createElement(_SearchBox2.default, { currentRefinement: this.state.query, refine: function refine(value) { _this2.setState({ query: value }); searchForItems(value); }, focusShortcuts: [], translate: translate, onSubmit: function onSubmit(e) { e.preventDefault(); e.stopPropagation(); if (isFromSearch) { selectItem(items[0], _this2.resetQuery); } } }), noResults ); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props; var cx = _props3.cx; var items = _props3.items; var withSearchBox = _props3.withSearchBox; var canRefine = _props3.canRefine; var searchBox = withSearchBox ? this.renderSearchBox() : null; if (items.length === 0) { return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), searchBox ); } // Always limit the number of items we show on screen, since the actual // number of retrieved items might vary with the `maxValuesPerFacet` config // option. var limit = this.getLimit(); return _react2.default.createElement( 'div', cx('root', !this.props.canRefine && 'noRefinement'), searchBox, _react2.default.createElement( 'div', cx('items'), items.slice(0, limit).map(function (item) { return _this3.renderItem(item, _this3.resetQuery); }) ), this.renderShowMore() ); } }]); return List; }(_react.Component); List.propTypes = { cx: _propTypes2.default.func.isRequired, // Only required with showMore. translate: _propTypes2.default.func, items: itemsPropType, renderItem: _propTypes2.default.func.isRequired, selectItem: _propTypes2.default.func, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, limit: _propTypes2.default.number, show: _propTypes2.default.func, searchForItems: _propTypes2.default.func, withSearchBox: _propTypes2.default.bool, isFromSearch: _propTypes2.default.bool, canRefine: _propTypes2.default.bool }; exports.default = List; /***/ }), /* 213 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var timestamp = Date.now().toString(); exports.default = { highlightPreTag: "<ais-highlight-" + timestamp + ">", highlightPostTag: "</ais-highlight-" + timestamp + ">" }; /***/ }), /* 214 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var AlgoliaSearchHelper = __webpack_require__(245); var SearchParameters = __webpack_require__(81); var SearchResults = __webpack_require__(115); /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new AlgoliaSearchHelper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = __webpack_require__(118); /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = __webpack_require__(117); module.exports = algoliasearchHelper; /***/ }), /* 215 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // This file hosts our error definitions // We use custom error "types" so that we can act on them when we need it // e.g.: if error instanceof errors.UnparsableJSON then.. var inherits = __webpack_require__(349); function AlgoliaSearchError(message, extraProperties) { var forEach = __webpack_require__(110); var error = this; // try to get a stacktrace if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old'; } this.name = 'AlgoliaSearchError'; this.message = message || 'Unknown error'; if (extraProperties) { forEach(extraProperties, function addToErrorObject(value, key) { error[key] = value; }); } } inherits(AlgoliaSearchError, Error); function createCustomError(name, message) { function AlgoliaSearchCustomError() { var args = Array.prototype.slice.call(arguments, 0); // custom message not set, use default if (typeof args[0] !== 'string') { args.unshift(message); } AlgoliaSearchError.apply(this, args); this.name = 'AlgoliaSearch' + name + 'Error'; } inherits(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place module.exports = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timedout before getting a response' ), Network: createCustomError( 'Network', 'Network issue, see err.more for details' ), JSONPScriptFail: createCustomError( 'JSONPScriptFail', '<script> was loaded but did not call our provided callback' ), JSONPScriptError: createCustomError( 'JSONPScriptError', '<script> unable to load due to an `error` event on it' ), Unknown: createCustomError( 'Unknown', 'Unknown error occured' ) }; /***/ }), /* 216 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __webpack_require__(419); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109))) /***/ }), /* 217 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18), isArrayLike = __webpack_require__(11), isIndex = __webpack_require__(31), isObject = __webpack_require__(6); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }), /* 218 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(202); /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } module.exports = isNaN; /***/ }), /* 219 */ /***/ (function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(338); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } module.exports = toFinite; /***/ }), /* 220 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys2 = __webpack_require__(9); var _keys3 = _interopRequireDefault(_keys2); var _difference2 = __webpack_require__(325); var _difference3 = _interopRequireDefault(_difference2); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); 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 _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function getId() { return 'configure'; } exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = (0, _omit3.default)(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = (0, _omit3.default)(props, 'children'); var nonPresentKeys = this._props ? (0, _difference3.default)((0, _keys3.default)(this._props), (0, _keys3.default)(props)) : []; this._props = props; var nextValue = _defineProperty({}, id, _extends({}, (0, _omit3.default)(nextSearchState[id], nonPresentKeys), items)); return (0, _indexUtils.refineValue)(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = (0, _indexUtils.getIndex)(this.context); var subState = (0, _indexUtils.hasMultipleIndex)(this.context) && searchState.indices ? searchState.indices[index] : searchState; var configureKeys = subState[id] ? Object.keys(subState[id]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = subState[id][item]; } return acc; }, {}); var nextValue = _defineProperty({}, id, configureState); return (0, _indexUtils.refineValue)(searchState, nextValue, this.context); } }); /***/ }), /* 221 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getId = undefined; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _algoliasearchHelper = __webpack_require__(214); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } var getId = exports.getId = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue(path, props, searchState, context) { var id = props.id; var attributes = props.attributes; var separator = props.separator; var rootPath = props.rootPath; var showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement(props, searchState, context); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new _algoliasearchHelper.SearchParameters({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue(value, limit, props, searchState, context) { return value.slice(0, limit).map(function (v) { return { label: v.name, value: getValue(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, limit, props, searchState, context) }; }); } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement || ''); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: _propTypes2.default.string, rootPath: _propTypes2.default.string, showParentLevel: _propTypes2.default.bool, defaultRefinement: _propTypes2.default.string, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var id = getId(props); var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: false }; } var limit = showMore ? limitMax : limitMin; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue(value.data, limit, props, searchState, this.context) : []; return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes; var separator = props.separator; var rootPath = props.rootPath; var showParentLevel = props.showParentLevel; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var id = getId(props); var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); var currentRefinement = getCurrentRefinement(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attributeName: rootAttribute, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /***/ }), /* 222 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var hits = results ? results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); /***/ }), /* 223 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function getId() { return 'hitsPerPage'; } function getCurrentRefinement(props, searchState, context) { var id = getId(); return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: _propTypes2.default.number.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string, value: _propTypes2.default.number.isRequired })).isRequired, transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }), /* 224 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function getId() { return 'page'; } function getCurrentRefinement(props, searchState, context) { var id = getId(); var page = 1; return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var hits = results.hits; var page = results.page; var nbPages = results.nbPages; var hitsPerPage = results.hitsPerPage; if (page === 0) { this._allResults = hits; } else { var previousPage = this._allResults.length / hitsPerPage - 1; if (page > previousPage) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits)); } else if (page < previousPage) { this._allResults = hits; } // If it is the same page we do not touch the page result list } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId(); var nextPage = getCurrentRefinement(props, searchState, this.context) + 1; var nextValue = _defineProperty({}, id, nextPage); var resetPage = false; return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage); } }); /***/ }), /* 225 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _orderBy2 = __webpack_require__(106); var _orderBy3 = _interopRequireDefault(_orderBy2); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } var namespace = 'menu'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue(name, props, searchState, context) { var currentRefinement = getCurrentRefinement(props, searchState, context); return name === currentRefinement ? '' : name; } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } var sortBy = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user tha ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [withSearchBox=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaMenu', propTypes: { attributeName: _propTypes2.default.string.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, defaultRefinement: _propTypes2.default.string, transformItems: _propTypes2.default.func, withSearchBox: _propTypes2.default.bool, searchForFacetValues: _propTypes2.default.bool }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.'); } // Search For Facet Values is not available with derived helper (used for multi index search) if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) { return { label: v.name, value: getValue(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = withSearchBox && !isFromSearch ? (0, _orderBy3.default)(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters.addDisjunctiveFacet(attributeName); var currentRefinement = getCurrentRefinement(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: currentRefinement === null ? [] : [{ label: props.attributeName + ': ' + currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _refine(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); /***/ }), /* 226 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _find3 = __webpack_require__(47); var _find4 = _interopRequireDefault(_find3); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'); var _value$split2 = _slicedToArray(_value$split, 2); var startStr = _value$split2[0]; var endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace = 'multiRange'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attributeName, results, value) { var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine(props, searchState, nextRefinement, context) { var nextValue = _defineProperty({}, getId(props, searchState), nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } /** * connectMultiRange connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectMultiRange * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @kind connector * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaMultiRange', propTypes: { id: _propTypes2.default.string, attributeName: _propTypes2.default.string.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.node, start: _propTypes2.default.number, end: _propTypes2.default.number })).isRequired, transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState, this.context); var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId(props), results, value) : false }; }); var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var refinedItem = (0, _find4.default)(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: (0, _isEmpty3.default)(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var _parseItem = parseItem(getCurrentRefinement(props, searchState, this.context)); var start = _parseItem.start; var end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attributeName); if (start) { searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var value = getCurrentRefinement(props, searchState, this.context); var items = []; var index = (0, _indexUtils.getIndex)(this.context); if (value !== '') { var _find2 = (0, _find4.default)(props.items, function (item) { return stringifyItem(item) === value; }); var label = _find2.label; items.push({ label: props.attributeName + ': ' + label, attributeName: props.attributeName, currentRefinement: label, value: function value(nextState) { return _refine(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); /***/ }), /* 227 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function getId() { return 'page'; } function getCurrentRefinement(props, searchState, context) { var id = getId(); var page = 1; return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine(props, searchState, nextPage, context) { var id = getId(); var nextValue = _defineProperty({}, id, nextPage); var resetPage = false; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage); } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }), /* 228 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps() { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /***/ }), /* 229 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } var namespace = 'refinementList'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue(name, props, searchState, context) { var currentRefinement = getCurrentRefinement(props, searchState, context); var isAnewValue = currentRefinement.indexOf(name) === -1; var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates : currentRefinement.filter(function (selectedValue) { return selectedValue !== name; }); // cannot use .splice(), it mutates return nextRefinement; } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); // Setting the value to an empty string ensures that it is persisted in // the URL as an empty value. // This is necessary in the case where `defaultRefinement` contains one // item and we try to deselect it. `nextSelected` would be an empty array, // which would not be persisted to the URL. // {foo: ['bar']} => "foo[0]=bar" // {foo: []} => "" var nextValue = _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } /** * connectRefinementList connector provides the logic to build a widget that will * give the user the ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy = ['isRefined', 'count:desc', 'name:asc']; exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaRefinementList', propTypes: { id: _propTypes2.default.string, attributeName: _propTypes2.default.string.isRequired, operator: _propTypes2.default.oneOf(['and', 'or']), showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, defaultRefinement: _propTypes2.default.arrayOf(_propTypes2.default.string), withSearchBox: _propTypes2.default.bool, searchForFacetValues: _propTypes2.default.bool, // @deprecated transformItems: _propTypes2.default.func }, defaultProps: { operator: 'or', showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.'); } // Search For Facet Values is not available with derived helper (used for multi index search) if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, withSearchBox: withSearchBox }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) { return { label: v.name, value: getValue(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var operator = props.operator; var showMore = props.showMore; var limitMin = props.limitMin; var limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters[addKey](attributeName); return getCurrentRefinement(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attributeName, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var context = this.context; return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: getCurrentRefinement(props, searchState, context).length > 0 ? [{ attributeName: props.attributeName, label: props.attributeName + ': ', currentRefinement: getCurrentRefinement(props, searchState, context), value: function value(nextState) { return _refine(props, nextState, [], context); }, items: getCurrentRefinement(props, searchState, context).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement(props, nextState, context).filter(function (other) { return other !== item; }); return _refine(props, searchState, nextSelectedItems, context); } }; }) }] : [] }; } }); /***/ }), /* 230 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectScrollTo connector provides the logic to build a widget that will * let the page scroll to a certain point. * @name connectScrollTo * @kind connector * @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget. * @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: _propTypes2.default.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = (0, _indexUtils.getCurrentRefinementValue)(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); return { value: value }; } }); /***/ }), /* 231 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function getId() { return 'query'; } function getCurrentRefinement(props, searchState, context) { var id = getId(props); return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine(props, searchState, nextRefinement, context) { var id = getId(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, getId()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query. * @name connectSearchBox * @kind connector * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the query to search for. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: _propTypes2.default.string }, getProvidedProps: function getProvidedProps(props, searchState) { return { currentRefinement: getCurrentRefinement(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: (0, _indexUtils.getIndex)(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /***/ }), /* 232 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _indexUtils = __webpack_require__(5); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function getId() { return 'sortBy'; } function getCurrentRefinement(props, searchState, context) { var id = getId(props); return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * The connectSortBy connector provides the logic to build a widget that will * display a list of indices. This allows a user to change how the hits are being sorted. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: _propTypes2.default.string, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string, value: _propTypes2.default.string.isRequired })).isRequired, transformItems: _propTypes2.default.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }), /* 233 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var index = (0, _indexUtils.getIndex)(this.context); var results = (0, _indexUtils.getResults)(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); /***/ }), /* 234 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _createConnector = __webpack_require__(2); var _createConnector2 = _interopRequireDefault(_createConnector); var _indexUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } function getId(props) { return props.attributeName; } var namespace = 'toggle'; function getCurrentRefinement(props, searchState, context) { return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } function _refine(props, searchState, nextRefinement, context) { var id = getId(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props)); } /** * connectToggle connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization. * @name connectToggle * @kind connector * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName`. * @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {boolean} currentRefinement - the refinement currently applied */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaToggle', propTypes: { label: _propTypes2.default.string, filter: _propTypes2.default.func, attributeName: _propTypes2.default.string, value: _propTypes2.default.any, defaultRefinement: _propTypes2.default.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var value = props.value; var filter = props.filter; var checked = getCurrentRefinement(props, searchState, this.context); if (checked) { if (attributeName) { searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId(props); var checked = getCurrentRefinement(props, searchState, this.context); var items = []; var index = (0, _indexUtils.getIndex)(this.context); if (checked) { items.push({ label: props.label, currentRefinement: props.label, attributeName: props.attributeName, value: function value(nextState) { return _refine(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); /***/ }), /* 235 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(211); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Highlight = __webpack_require__(380); var _Highlight2 = _interopRequireDefault(_Highlight); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Highlight * @kind widget * @propType {string} attributeName - the location of the highlighted attribute in the hit * @propType {object} hit - the hit object containing the highlighted attribute * @propType {string} [tagName='em'] - the tag to be used for highlighted parts of the hit * @example * import React from 'react'; * * import { connectHits, Highlight, InstantSearch } from 'react-instantsearch/dom'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Highlight attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Highlight2.default); /***/ }), /* 236 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); 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 Link = function (_Component) { _inherits(Link, _Component); function Link() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) { if ((0, _utils.isSpecialClick)(e)) { return; } _this.props.onClick(); e.preventDefault(); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Link, [{ key: 'render', value: function render() { return _react2.default.createElement('a', _extends({}, (0, _omit3.default)(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(_react.Component); Link.propTypes = { onClick: _propTypes2.default.func.isRequired }; exports.default = Link; /***/ }), /* 237 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _get2 = __webpack_require__(73); var _get3 = _interopRequireDefault(_get2); exports.default = parseAlgoliaHit; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attributeName - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseAlgoliaHit(_ref) { var _ref$preTag = _ref.preTag; var preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag; var _ref$postTag = _ref.postTag; var postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag; var highlightProperty = _ref.highlightProperty; var attributeName = _ref.attributeName; var hit = _ref.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = (0, _get3.default)(hit[highlightProperty], attributeName); var highlightedValue = !highlightObject ? '' : highlightObject.value; return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue }); } /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref2) { var preTag = _ref2.preTag; var postTag = _ref2.postTag; var highlightedValue = _ref2.highlightedValue; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } /***/ }), /* 238 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 239 */ /***/ (function(module, exports) { module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } /***/ }), /* 240 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util = __webpack_require__(114); var events = __webpack_require__(113); /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; module.exports = DerivedHelper; /***/ }), /* 241 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var isUndefined = __webpack_require__(203); var isString = __webpack_require__(50); var isFunction = __webpack_require__(19); var isEmpty = __webpack_require__(16); var defaults = __webpack_require__(101); var reduce = __webpack_require__(52); var filter = __webpack_require__(102); var omit = __webpack_require__(38); var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated prefinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * behaviors can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optionnal parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined(attribute)) { return {}; } else if (isString(attribute)) { return omit(refinementList, attribute); } else if (isFunction(attribute)) { return reduce(refinementList, function(memo, values, key) { var facetList = filter(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty(facetList)) memo[key] = facetList; return memo; }, {}); } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = __webpack_require__(74); var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; module.exports = lib; /***/ }), /* 242 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var filter = __webpack_require__(102); var map = __webpack_require__(17); var isEmpty = __webpack_require__(16); var indexOf = __webpack_require__(74); function filterState(state, filters) { var partialState = {}; var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf(attributes, '*') === -1) { forEach(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } module.exports = filterState; /***/ }), /* 243 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var invert = __webpack_require__(201); var keys = __webpack_require__(9); var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert(keys2Short); module.exports = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; /***/ }), /* 244 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = generateTrees; var last = __webpack_require__(204); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var orderBy = __webpack_require__(106); var trim = __webpack_require__(207); var find = __webpack_require__(47); var pickBy = __webpack_require__(334); var prepareHierarchicalFacetSortBy = __webpack_require__(116); function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy( map( pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim(last(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /***/ }), /* 245 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var SearchParameters = __webpack_require__(81); var SearchResults = __webpack_require__(115); var DerivedHelper = __webpack_require__(240); var requestBuilder = __webpack_require__(247); var util = __webpack_require__(114); var events = __webpack_require__(113); var flatten = __webpack_require__(199); var forEach = __webpack_require__(35); var isEmpty = __webpack_require__(16); var map = __webpack_require__(17); var url = __webpack_require__(117); var version = __webpack_require__(118); /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when the search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version); this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occcurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occured it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder._getQueries(tempState.index, tempState); if (cb) { return this.client.search( queries, function(err, content) { if (err) cb(err, null, tempState); else cb(err, new SearchResults(tempState, content.results), tempState); } ); } return this.client.search(queries).then(function(content) { return { content: new SearchResults(tempState, content.results), state: tempState, _originalResponse: content }; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {objet} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query insde the engine */ /** * Search for facet values based on an query and the name of a facetted attribute. This * triggers a search and will retrun a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} query the string query for the search * @param {string} facet the name of the facetted attribute * @return {promise<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query) { var state = this.state; var index = this.client.initIndex(this.state.index); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, this.state); return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) { content.facetHits = forEach(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this.state = this.state.setPage(0).setQuery(q); this._change(); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this.state = this.state.setPage(0).clearRefinements(name); this._change(); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this.state = this.state.setPage(0).clearTags(); this._change(); return this; }; /** * Adds a disjunctive filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value); this._change(); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Adds a filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).addExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this.state = this.state.setPage(0).addTagRefinement(tag); this._change(); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optionnals, triggering different behaviors: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Removes a disjunctive filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet); this._change(); return this; }; /** * Removes a filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).removeExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this.state = this.state.setPage(0).removeTagRefinement(tag); this._change(); return this; }; /** * Adds or removes an exclusion filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).toggleFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this.state = this.state.setPage(0).toggleTagRefinement(tag); this._change(); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this.state = this.state.setPage(page); this._change(); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this.state = this.state.setPage(0).setIndex(name); this._change(); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { var newState = this.state.setPage(0).setQueryParameter(parameter, value); if (this.state === newState) return this; this.state = newState; this._change(); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this.state = new SearchParameters(newState); this._change(); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optionnal filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optionnal parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific facetted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for facetting * @param {string} [value] optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for facetting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten(derivedQueries)); var queryId = this._queryId++; this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId)); }; /** * Transform the responses as sent by the server and transform them into a user * usable objet that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {Error} err error if any, null otherwise * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._lastQueryIdReceived = queryId; if (err) { this.emit('error', err); return; } var results = content.results; forEach(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults(state, specificResults); helper.emit('result', formattedResponse, state); }); }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function() { this.emit('change', this.state, this.lastResults); }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the facetting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } module.exports = AlgoliaSearchHelper; /***/ }), /* 246 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var map = __webpack_require__(17); var isArray = __webpack_require__(0); var isNumber = __webpack_require__(202); var isString = __webpack_require__(50); function valToNumber(v) { if (isNumber(v)) { return v; } else if (isString(v)) { return parseFloat(v); } else if (isArray(v)) { return map(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } module.exports = valToNumber; /***/ }), /* 247 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(35); var map = __webpack_require__(17); var reduce = __webpack_require__(52); var merge = __webpack_require__(105); var isArray = __webpack_require__(0); var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach(state.numericRefinements, function(operators, attribute) { forEach(operators, function(values, operator) { if (facetName !== attribute) { forEach(values, function(value) { if (isArray(value)) { var vs = map(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach(state.facetsRefinements, function(facetValues, facetName) { forEach(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach(state.facetsExcludes, function(facetValues, facetName) { forEach(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var queries = merge(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), { facetQuery: query, facetName: facetName }); return queries; } }; module.exports = requestBuilder; /***/ }), /* 248 */ /***/ (function(module, exports, __webpack_require__) { var foreach = __webpack_require__(110); module.exports = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; /***/ }), /* 249 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /* 250 */ /***/ (function(module, exports) { /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } module.exports = addMapEntry; /***/ }), /* 251 */ /***/ (function(module, exports) { /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } module.exports = addSetEntry; /***/ }), /* 252 */ /***/ (function(module, exports) { /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } module.exports = asciiToArray; /***/ }), /* 253 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keys = __webpack_require__(9); /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } module.exports = baseAssign; /***/ }), /* 254 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keysIn = __webpack_require__(51); /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } module.exports = baseAssignIn; /***/ }), /* 255 */ /***/ (function(module, exports) { /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } module.exports = baseClamp; /***/ }), /* 256 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), arrayEach = __webpack_require__(85), assignValue = __webpack_require__(90), baseAssign = __webpack_require__(253), baseAssignIn = __webpack_require__(254), cloneBuffer = __webpack_require__(144), copyArray = __webpack_require__(68), copySymbols = __webpack_require__(291), copySymbolsIn = __webpack_require__(292), getAllKeys = __webpack_require__(95), getAllKeysIn = __webpack_require__(96), getTag = __webpack_require__(56), initCloneArray = __webpack_require__(307), initCloneByTag = __webpack_require__(308), initCloneObject = __webpack_require__(165), isArray = __webpack_require__(0), isBuffer = __webpack_require__(26), isObject = __webpack_require__(6), keys = __webpack_require__(9); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', 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 supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } module.exports = baseClone; /***/ }), /* 257 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arrayIncludes = __webpack_require__(87), arrayIncludesWith = __webpack_require__(127), arrayMap = __webpack_require__(12), baseUnary = __webpack_require__(45), cacheHas = __webpack_require__(67); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } module.exports = baseDifference; /***/ }), /* 258 */ /***/ (function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(63); /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } module.exports = baseFilter; /***/ }), /* 259 */ /***/ (function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }), /* 260 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(59), arrayIncludes = __webpack_require__(87), arrayIncludesWith = __webpack_require__(127), arrayMap = __webpack_require__(12), baseUnary = __webpack_require__(45), cacheHas = __webpack_require__(67); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseIntersection; /***/ }), /* 261 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43); /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } module.exports = baseInverter; /***/ }), /* 262 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), baseIsEqual = __webpack_require__(65); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }), /* 263 */ /***/ (function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }), /* 264 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6), isPrototype = __webpack_require__(37), nativeKeysIn = __webpack_require__(313); /** 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 `_.keysIn` 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 baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }), /* 265 */ /***/ (function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(262), getMatchData = __webpack_require__(304), matchesStrictComparable = __webpack_require__(179); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }), /* 266 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(65), get = __webpack_require__(73), hasIn = __webpack_require__(200), isKey = __webpack_require__(72), isStrictComparable = __webpack_require__(168), matchesStrictComparable = __webpack_require__(179), toKey = __webpack_require__(23); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; /***/ }), /* 267 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(41), assignMergeValue = __webpack_require__(129), baseFor = __webpack_require__(132), baseMergeDeep = __webpack_require__(268), isObject = __webpack_require__(6), keysIn = __webpack_require__(51); /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } module.exports = baseMerge; /***/ }), /* 268 */ /***/ (function(module, exports, __webpack_require__) { var assignMergeValue = __webpack_require__(129), cloneBuffer = __webpack_require__(144), cloneTypedArray = __webpack_require__(145), copyArray = __webpack_require__(68), initCloneObject = __webpack_require__(165), isArguments = __webpack_require__(25), isArray = __webpack_require__(0), isArrayLikeObject = __webpack_require__(103), isBuffer = __webpack_require__(26), isFunction = __webpack_require__(19), isObject = __webpack_require__(6), isPlainObject = __webpack_require__(49), isTypedArray = __webpack_require__(36), toPlainObject = __webpack_require__(339); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } module.exports = baseMergeDeep; /***/ }), /* 269 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), baseMap = __webpack_require__(138), baseSortBy = __webpack_require__(276), baseUnary = __webpack_require__(45), compareMultiple = __webpack_require__(290), identity = __webpack_require__(24); /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } module.exports = baseOrderBy; /***/ }), /* 270 */ /***/ (function(module, exports, __webpack_require__) { var basePickBy = __webpack_require__(139), hasIn = __webpack_require__(200); /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } module.exports = basePick; /***/ }), /* 271 */ /***/ (function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }), /* 272 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }), /* 273 */ /***/ (function(module, exports) { /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } module.exports = baseReduce; /***/ }), /* 274 */ /***/ (function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(90), castPath = __webpack_require__(21), isIndex = __webpack_require__(31), isObject = __webpack_require__(6), toKey = __webpack_require__(23); /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } module.exports = baseSet; /***/ }), /* 275 */ /***/ (function(module, exports, __webpack_require__) { var constant = __webpack_require__(197), defineProperty = __webpack_require__(152), identity = __webpack_require__(24); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; /***/ }), /* 276 */ /***/ (function(module, exports) { /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } module.exports = baseSortBy; /***/ }), /* 277 */ /***/ (function(module, exports) { /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } module.exports = baseSum; /***/ }), /* 278 */ /***/ (function(module, exports, __webpack_require__) { var castPath = __webpack_require__(21), last = __webpack_require__(204), parent = __webpack_require__(314), toKey = __webpack_require__(23); /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } module.exports = baseUnset; /***/ }), /* 279 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12); /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } module.exports = baseValues; /***/ }), /* 280 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(103); /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } module.exports = castArrayLikeObject; /***/ }), /* 281 */ /***/ (function(module, exports, __webpack_require__) { var baseSlice = __webpack_require__(141); /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } module.exports = castSlice; /***/ }), /* 282 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } module.exports = charsEndIndex; /***/ }), /* 283 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44); /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } module.exports = charsStartIndex; /***/ }), /* 284 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93); /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } module.exports = cloneDataView; /***/ }), /* 285 */ /***/ (function(module, exports, __webpack_require__) { var addMapEntry = __webpack_require__(250), arrayReduce = __webpack_require__(89), mapToArray = __webpack_require__(98); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } module.exports = cloneMap; /***/ }), /* 286 */ /***/ (function(module, exports) { /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } module.exports = cloneRegExp; /***/ }), /* 287 */ /***/ (function(module, exports, __webpack_require__) { var addSetEntry = __webpack_require__(251), arrayReduce = __webpack_require__(89), setToArray = __webpack_require__(99); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } module.exports = cloneSet; /***/ }), /* 288 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } module.exports = cloneSymbol; /***/ }), /* 289 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(27); /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } module.exports = compareAscending; /***/ }), /* 290 */ /***/ (function(module, exports, __webpack_require__) { var compareAscending = __webpack_require__(289); /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } module.exports = compareMultiple; /***/ }), /* 291 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), getSymbols = __webpack_require__(71); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols; /***/ }), /* 292 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), getSymbolsIn = __webpack_require__(158); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn; /***/ }), /* 293 */ /***/ (function(module, exports) { /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } module.exports = countHolders; /***/ }), /* 294 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(11); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }), /* 295 */ /***/ (function(module, exports) { /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }), /* 296 */ /***/ (function(module, exports, __webpack_require__) { var createCtor = __webpack_require__(69), root = __webpack_require__(3); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } module.exports = createBind; /***/ }), /* 297 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), createCtor = __webpack_require__(69), createHybrid = __webpack_require__(150), createRecurry = __webpack_require__(151), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34), root = __webpack_require__(3); /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } module.exports = createCurry; /***/ }), /* 298 */ /***/ (function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(13), isArrayLike = __webpack_require__(11), keys = __webpack_require__(9); /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = baseIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } module.exports = createFind; /***/ }), /* 299 */ /***/ (function(module, exports, __webpack_require__) { var baseInverter = __webpack_require__(261); /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } module.exports = createInverter; /***/ }), /* 300 */ /***/ (function(module, exports, __webpack_require__) { var apply = __webpack_require__(60), createCtor = __webpack_require__(69), root = __webpack_require__(3); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } module.exports = createPartial; /***/ }), /* 301 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(18); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } module.exports = customDefaultsAssignIn; /***/ }), /* 302 */ /***/ (function(module, exports, __webpack_require__) { var isPlainObject = __webpack_require__(49); /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } module.exports = customOmitClone; /***/ }), /* 303 */ /***/ (function(module, exports, __webpack_require__) { var realNames = __webpack_require__(315); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } module.exports = getFuncName; /***/ }), /* 304 */ /***/ (function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(168), keys = __webpack_require__(9); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }), /* 305 */ /***/ (function(module, exports) { /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } module.exports = getWrapDetails; /***/ }), /* 306 */ /***/ (function(module, exports) { /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } module.exports = hasUnicode; /***/ }), /* 307 */ /***/ (function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; /***/ }), /* 308 */ /***/ (function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(93), cloneDataView = __webpack_require__(284), cloneMap = __webpack_require__(285), cloneRegExp = __webpack_require__(286), cloneSet = __webpack_require__(287), cloneSymbol = __webpack_require__(288), cloneTypedArray = __webpack_require__(145); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', 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]', 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]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } module.exports = initCloneByTag; /***/ }), /* 309 */ /***/ (function(module, exports) { /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } module.exports = insertWrapDetails; /***/ }), /* 310 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), isArguments = __webpack_require__(25), isArray = __webpack_require__(0); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } module.exports = isFlattenable; /***/ }), /* 311 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), getData = __webpack_require__(156), getFuncName = __webpack_require__(303), lodash = __webpack_require__(341); /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } module.exports = isLaziable; /***/ }), /* 312 */ /***/ (function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(146), composeArgsRight = __webpack_require__(147), replaceHolders = __webpack_require__(34); /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } module.exports = mergeData; /***/ }), /* 313 */ /***/ (function(module, exports) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }), /* 314 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(64), baseSlice = __webpack_require__(141); /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } module.exports = parent; /***/ }), /* 315 */ /***/ (function(module, exports) { /** Used to lookup unminified function names. */ var realNames = {}; module.exports = realNames; /***/ }), /* 316 */ /***/ (function(module, exports, __webpack_require__) { var copyArray = __webpack_require__(68), isIndex = __webpack_require__(31); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } module.exports = reorder; /***/ }), /* 317 */ /***/ (function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }), /* 318 */ /***/ (function(module, exports, __webpack_require__) { var asciiToArray = __webpack_require__(252), hasUnicode = __webpack_require__(306), unicodeToArray = __webpack_require__(319); /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } module.exports = stringToArray; /***/ }), /* 319 */ /***/ (function(module, exports) { /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange + ']', rsCombo = '[' + rsComboRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } module.exports = unicodeToArray; /***/ }), /* 320 */ /***/ (function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(85), arrayIncludes = __webpack_require__(87); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } module.exports = updateWrapDetails; /***/ }), /* 321 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), LodashWrapper = __webpack_require__(124), copyArray = __webpack_require__(68); /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } module.exports = wrapperClone; /***/ }), /* 322 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), createAssigner = __webpack_require__(149), keysIn = __webpack_require__(51); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); module.exports = assignInWith; /***/ }), /* 323 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; module.exports = bind; /***/ }), /* 324 */ /***/ (function(module, exports) { /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } module.exports = compact; /***/ }), /* 325 */ /***/ (function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(257), baseFlatten = __webpack_require__(131), baseRest = __webpack_require__(20), isArrayLikeObject = __webpack_require__(103); /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); module.exports = difference; /***/ }), /* 326 */ /***/ (function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(43), castFunction = __webpack_require__(143); /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, castFunction(iteratee)); } module.exports = forOwn; /***/ }), /* 327 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(44), isArrayLike = __webpack_require__(11), isString = __webpack_require__(50), toInteger = __webpack_require__(53), values = __webpack_require__(340); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } module.exports = includes; /***/ }), /* 328 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIntersection = __webpack_require__(260), baseRest = __webpack_require__(20), castArrayLikeObject = __webpack_require__(280); /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); module.exports = intersection; /***/ }), /* 329 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), baseForOwn = __webpack_require__(43), baseIteratee = __webpack_require__(13); /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = baseIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } module.exports = mapKeys; /***/ }), /* 330 */ /***/ (function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(42), baseForOwn = __webpack_require__(43), baseIteratee = __webpack_require__(13); /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = baseIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } module.exports = mapValues; /***/ }), /* 331 */ /***/ (function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }), /* 332 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; module.exports = partial; /***/ }), /* 333 */ /***/ (function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(20), createWrap = __webpack_require__(94), getHolder = __webpack_require__(46), replaceHolders = __webpack_require__(34); /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; module.exports = partialRight; /***/ }), /* 334 */ /***/ (function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(12), baseIteratee = __webpack_require__(13), basePickBy = __webpack_require__(139), getAllKeysIn = __webpack_require__(96); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = baseIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } module.exports = pickBy; /***/ }), /* 335 */ /***/ (function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(271), basePropertyDeep = __webpack_require__(272), isKey = __webpack_require__(72), toKey = __webpack_require__(23); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }), /* 336 */ /***/ (function(module, exports, __webpack_require__) { var baseClamp = __webpack_require__(255), baseToString = __webpack_require__(66), toInteger = __webpack_require__(53), toString = __webpack_require__(75); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } module.exports = startsWith; /***/ }), /* 337 */ /***/ (function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(13), baseSum = __webpack_require__(277); /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, baseIteratee(iteratee, 2)) : 0; } module.exports = sumBy; /***/ }), /* 338 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(6), isSymbol = __webpack_require__(27); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }), /* 339 */ /***/ (function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(22), keysIn = __webpack_require__(51); /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } module.exports = toPlainObject; /***/ }), /* 340 */ /***/ (function(module, exports, __webpack_require__) { var baseValues = __webpack_require__(279), keys = __webpack_require__(9); /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } module.exports = values; /***/ }), /* 341 */ /***/ (function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(82), LodashWrapper = __webpack_require__(124), baseLodash = __webpack_require__(92), isArray = __webpack_require__(0), isObjectLike = __webpack_require__(7), wrapperClone = __webpack_require__(321); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; module.exports = lodash; /***/ }), /* 342 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var stringify = __webpack_require__(344); var parse = __webpack_require__(343); var formats = __webpack_require__(209); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }), /* 343 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(108); var has = Object.prototype.hasOwnProperty; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseValues(str, options) { var obj = {}; var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; var key, val; if (pos === -1) { key = options.decoder(part); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos)); val = options.decoder(part.slice(pos + 1)); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function parseObject(chain, val, options) { if (!chain.length) { return val; } var root = chain.shift(); var obj; if (root === '[]') { obj = []; obj = obj.concat(parseObject(chain, val, options)); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = parseObject(chain, val, options); } else { obj[cleanRoot] = parseObject(chain, val, options); } } return obj; }; var parseKeys = function parseKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey; // The regex chunks var parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Stash the parent if it exists var keys = []; if (segment[1]) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, segment[1])) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) { if (!options.allowPrototypes) { continue; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; module.exports = function (str, opts) { var options = opts || {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; /***/ }), /* 344 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(108); var formats = __webpack_require__(209); var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var toISO = Date.prototype.toISOString; var defaults = { delimiter: '&', encode: true, encoder: utils.encode, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder ? encoder(prefix) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } } return values; }; module.exports = function (object, opts) { var obj = object; var options = opts || {}; var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; if (typeof options.format === 'undefined') { options.format = formats.default; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } return keys.join(delimiter); }; /***/ }), /* 345 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Highlighter; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlighter(_ref) { var hit = _ref.hit; var attributeName = _ref.attributeName; var highlight = _ref.highlight; var highlightProperty = _ref.highlightProperty; var tagName = _ref.tagName; var parsedHighlightedValue = highlight({ hit: hit, attributeName: attributeName, highlightProperty: highlightProperty }); var reactHighlighted = parsedHighlightedValue.map(function (v, i) { var key = 'split-' + i + '-' + v.value; if (!v.isHighlighted) { return _react2.default.createElement( 'span', { key: key, className: 'ais-Highlight__nonHighlighted' }, v.value ); } var HighlightedTag = tagName ? tagName : 'em'; return _react2.default.createElement( HighlightedTag, { key: key, className: 'ais-Highlight__highlighted' }, v.value ); }); return _react2.default.createElement( 'span', { className: 'ais-Highlight' }, reactHighlighted ); } Highlighter.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, highlightProperty: _propTypes2.default.string.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 346 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } 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 cx = (0, _classNames2.default)('SearchBox'); var SearchBox = function (_Component) { _inherits(SearchBox, _Component); function SearchBox(props) { _classCallCheck(this, SearchBox); var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this)); _this.getQuery = function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }; _this.setQuery = function (val) { var _this$props = _this.props; var refine = _this$props.refine; var searchAsYouType = _this$props.searchAsYouType; if (searchAsYouType) { refine(val); } else { _this.setState({ query: val }); } }; _this.onInputMount = function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }; _this.onKeyDown = function (e) { if (!_this.props.focusShortcuts) { return; } var shortcuts = _this.props.focusShortcuts.map(function (key) { return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key; }); var elt = e.target || e.srcElement; var tagName = elt.tagName; if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') { // already in an input return; } var which = e.which || e.keyCode; if (shortcuts.indexOf(which) === -1) { // not the right shortcut return; } _this.input.focus(); e.stopPropagation(); e.preventDefault(); }; _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); _this.input.blur(); var _this$props2 = _this.props; var refine = _this$props2.refine; var searchAsYouType = _this$props2.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }; _this.onChange = function (e) { _this.setQuery(e.target.value); if (_this.props.onChange) { _this.props.onChange(e); } }; _this.onReset = function () { _this.setQuery(''); _this.input.focus(); if (_this.props.onReset) { _this.props.onReset(); } }; _this.state = { query: props.searchAsYouType ? null : props.currentRefinement }; return _this; } _createClass(SearchBox, [{ key: 'componentDidMount', value: function componentDidMount() { document.addEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { document.removeEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Reset query when the searchParameters query has changed. // This is kind of an anti-pattern (props in state), but it works here // since we know for sure that searchParameters having changed means a // new search has been triggered. if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: nextProps.currentRefinement }); } } // From https://github.com/algolia/autocomplete.js/pull/86 }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var autoFocus = _props.autoFocus; var query = this.getQuery(); var submitComponent = this.props.submitComponent ? this.props.submitComponent : _react2.default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-search-13' }) ); var resetComponent = this.props.resetComponent ? this.props.resetComponent : _react2.default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' }) ); var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) { if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) { return _extends({}, props, _defineProperty({}, prop, _this2.props[prop])); } return props; }, {}); /* eslint-disable max-len */ return _react2.default.createElement( 'form', _extends({ noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset }, cx('root'), { action: '', role: 'search' }), _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } }, _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-search-13', viewBox: '0 0 40 40' }, _react2.default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z', fillRule: 'evenodd' }) ), _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-clear-3', viewBox: '0 0 20 20' }, _react2.default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z', fillRule: 'evenodd' }) ) ), _react2.default.createElement( 'div', _extends({ role: 'search' }, cx('wrapper')), _react2.default.createElement('input', _extends({ ref: this.onInputMount, type: 'search', placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: 'off', autoCorrect: 'off', autoCapitalize: 'off', spellCheck: 'false', required: true, value: query, onChange: this.onChange }, searchInputEvents, cx('input'))), _react2.default.createElement( 'button', _extends({ type: 'submit', title: translate('submitTitle') }, cx('submit')), submitComponent ), _react2.default.createElement( 'button', _extends({ type: 'reset', title: translate('resetTitle') }, cx('reset'), { onClick: this.onReset }), resetComponent ) ) ); /* eslint-enable */ } }]); return SearchBox; }(_react.Component); SearchBox.propTypes = { currentRefinement: _propTypes2.default.string, refine: _propTypes2.default.func.isRequired, translate: _propTypes2.default.func.isRequired, resetComponent: _propTypes2.default.element, submitComponent: _propTypes2.default.element, focusShortcuts: _propTypes2.default.arrayOf(_propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number])), autoFocus: _propTypes2.default.bool, searchAsYouType: _propTypes2.default.bool, onSubmit: _propTypes2.default.func, onReset: _propTypes2.default.func, onChange: _propTypes2.default.func, // For testing purposes __inputRef: _propTypes2.default.func }; SearchBox.defaultProps = { currentRefinement: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true }; exports.default = (0, _translatable2.default)({ resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); /***/ }), /* 347 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); 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 Select = function (_Component) { _inherits(Select, _Component); function Select() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Select); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.onSelect(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Select, [{ key: 'render', value: function render() { var _props = this.props; var cx = _props.cx; var items = _props.items; var selectedItem = _props.selectedItem; return _react2.default.createElement( 'select', _extends({}, cx('root'), { value: selectedItem, onChange: this.onChange }), items.map(function (item) { return _react2.default.createElement( 'option', { key: (0, _has3.default)(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, (0, _has3.default)(item, 'label') ? item.label : item.value ); }) ); } }]); return Select; }(_react.Component); Select.propTypes = { cx: _propTypes2.default.func.isRequired, onSelect: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]).isRequired, key: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), label: _propTypes2.default.string, disabled: _propTypes2.default.bool })).isRequired, selectedItem: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]).isRequired }; exports.default = Select; /***/ }), /* 348 */ /***/ (function(module, exports, __webpack_require__) { module.exports = buildSearchMethod; var errors = __webpack_require__(215); /** * Creates a search method to be used in clients * @param {string} queryParam the name of the attribute used for the query * @param {string} url the url * @return {function} the search method */ function buildSearchMethod(queryParam, url) { /** * The search method. Prepares the data and send the query to Algolia. * @param {string} query the string used for query search * @param {object} args additional parameters to send with the search * @param {function} [callback] the callback to be called with the client gets the answer * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise */ return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } // Normalizing the function signature if (arguments.length === 0 || typeof query === 'function') { // Usage : .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // Usage : .search(query/args), .search(query, cb) callback = args; args = undefined; } // At this point we have 3 arguments with values // Usage : .search(args) // careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } var additionalUA; if (args !== undefined) { if (args.additionalUA) { additionalUA = args.additionalUA; delete args.additionalUA; } // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback, additionalUA); }; } /***/ }), /* 349 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 350 */, /* 351 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); exports.default = createIndex; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Index = __webpack_require__(398); var _Index2 = _interopRequireDefault(_Index); 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; } /** * Creates a specialized root Index component. It accepts * a specification of the root Element. * @param {object} root - the defininition of the root of an Index sub tree. * @returns {object} a Index root */ function createIndex(root) { var _class, _temp; return _temp = _class = function (_Component) { _inherits(CreateIndex, _Component); function CreateIndex() { _classCallCheck(this, CreateIndex); return _possibleConstructorReturn(this, (CreateIndex.__proto__ || Object.getPrototypeOf(CreateIndex)).apply(this, arguments)); } _createClass(CreateIndex, [{ key: 'render', value: function render() { return _react2.default.createElement(_Index2.default, { indexName: this.props.indexName, root: root, children: this.props.children }); } }]); return CreateIndex; }(_react.Component), _class.propTypes = { children: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]), indexName: _propTypes2.default.string.isRequired }, _temp; } /***/ }), /* 352 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); exports.default = createInstantSearch; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _InstantSearch = __webpack_require__(399); var _InstantSearch2 = _interopRequireDefault(_InstantSearch); 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 _name$author$descript = { name: 'react-instantsearch', author: { name: 'Algolia, Inc.', url: 'https://www.algolia.com' }, description: '\u26A1 Lightning-fast search for React and React Native apps', version: '4.0.0-beta.4', scripts: { build: './scripts/build.sh', 'build-and-publish': './scripts/build-and-publish.sh' }, homepage: 'https://community.algolia.com/react-instantsearch/', repository: { type: 'git', url: 'https://github.com/algolia/react-instantsearch/' }, dependencies: { algoliasearch: '^3.21.1', 'algoliasearch-helper': '2.19.0', classnames: '^2.2.5', lodash: '^4.17.4', 'prop-types': '^15.5.8' }, license: 'MIT', devDependencies: { enzyme: '^2.8.1', react: '^15.5.4', 'react-dom': '^15.5.4', 'react-native': '^0.41.2', 'react-test-renderer': '^15.5.4' } }; var version = _name$author$descript.version; /** * Creates a specialized root InstantSearch component. It accepts * an algolia client and a specification of the root Element. * @param {function} defaultAlgoliaClient - a function that builds an Algolia client * @param {object} root - the defininition of the root of an InstantSearch sub tree. * @returns {object} an InstantSearch root */ function createInstantSearch(defaultAlgoliaClient, root) { var _class, _temp; return _temp = _class = function (_Component) { _inherits(CreateInstantSearch, _Component); function CreateInstantSearch(props) { _classCallCheck(this, CreateInstantSearch); var _this = _possibleConstructorReturn(this, (CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call(this)); _this.client = props.algoliaClient || defaultAlgoliaClient(props.appId, props.apiKey); _this.client.addAlgoliaAgent('react-instantsearch ' + version); return _this; } _createClass(CreateInstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } this.client.addAlgoliaAgent('react-instantsearch ' + version); } }, { key: 'render', value: function render() { return _react2.default.createElement(_InstantSearch2.default, { createURL: this.props.createURL, indexName: this.props.indexName, searchParameters: this.props.searchParameters, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, root: root, algoliaClient: this.client, children: this.props.children }); } }]); return CreateInstantSearch; }(_react.Component), _class.propTypes = { algoliaClient: _propTypes2.default.object, appId: _propTypes2.default.string, apiKey: _propTypes2.default.string, children: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]), indexName: _propTypes2.default.string.isRequired, searchParameters: _propTypes2.default.object, createURL: _propTypes2.default.func, searchState: _propTypes2.default.object, onSearchStateChange: _propTypes2.default.func }, _temp; } /***/ }), /* 353 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(210); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _ClearAll = __webpack_require__(376); var _ClearAll2 = _interopRequireDefault(_ClearAll); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ClearAll widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearAll * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query * @themeKey ais-ClearAll__root - the widget button * @translationKey reset - the clear all button value * @example * import React from 'react'; * * import { ClearAll, RefinementList, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ClearAll /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_ClearAll2.default); /***/ }), /* 354 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectConfigure = __webpack_require__(220); var _connectConfigure2 = _interopRequireDefault(_connectConfigure); var _Configure = __webpack_require__(377); var _Configure2 = _interopRequireDefault(_Configure); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * * import { Configure, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure distinct={1} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectConfigure2.default)(_Configure2.default); /***/ }), /* 355 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(210); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _CurrentRefinements = __webpack_require__(378); var _CurrentRefinements2 = _interopRequireDefault(_CurrentRefinements); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The CurrentRefinements widget displays the list of currently applied filters. * * It allows the user to selectively remove them. * @name CurrentRefinements * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-CurrentRefinements__root - the root div of the widget * @themeKey ais-CurrentRefinements__items - the container of the filters * @themeKey ais-CurrentRefinements__item - a single filter * @themeKey ais-CurrentRefinements__itemLabel - the label of a filter * @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter * @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * * import { CurrentRefinements, RefinementList, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CurrentRefinements /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_CurrentRefinements2.default); /***/ }), /* 356 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHierarchicalMenu = __webpack_require__(221); var _connectHierarchicalMenu2 = _interopRequireDefault(_connectHierarchicalMenu); var _HierarchicalMenu = __webpack_require__(379); var _HierarchicalMenu2 = _interopRequireDefault(_HierarchicalMenu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The hierarchical menu lets the user browse attributes using a tree-like structure. * * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * * @name HierarchicalMenu * @kind widget * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HierarchicalMenu__root - Container of the widget * @themeKey ais-HierarchicalMenu__items - Container of the items * @themeKey ais-HierarchicalMenu__item - Id for a single list item * @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list * @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed * @themeKey HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected * @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count * @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry * @themeKey ais-HierarchicalMenu__itemCount - the count of the entry * @themeKey ais-HierarchicalMenu__itemItems - id representing a children * @themeKey ais-HierarchicalMenu__showMore - container for the show more button * @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement * @translationKey showMore - Label value of the button which toggles the number of items * @example * import React from 'react'; * import { HierarchicalMenu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HierarchicalMenu * id="categories" * key="categories" * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHierarchicalMenu2.default)(_HierarchicalMenu2.default); /***/ }), /* 357 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHits = __webpack_require__(222); var _connectHits2 = _interopRequireDefault(_connectHits); var _Hits = __webpack_require__(381); var _Hits2 = _interopRequireDefault(_Hits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays a list of hits. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name Hits * @kind widget * @propType {Component} [hitComponent] - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-Hits__root - the root of the component * @example * import React from 'react'; * import { Hits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHits2.default)(_Hits2.default); /***/ }), /* 358 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHitsPerPage = __webpack_require__(223); var _connectHitsPerPage2 = _interopRequireDefault(_connectHitsPerPage); var _HitsPerPage = __webpack_require__(382); var _HitsPerPage2 = _interopRequireDefault(_HitsPerPage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The HitsPerPage widget displays a dropdown menu to let the user change the number * of displayed hits. * * If you only want to configure the number of hits per page without * displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure /> documentation`](widgets/Configure.html) * * @name HitsPerPage * @kind widget * @propType {{value: number, label: string}[]} items - List of available options. * @propType {number} defaultRefinement - The number of items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HitsPerPage__root - the root of the component. * @example * import React from 'react'; * import { HitsPerPage, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HitsPerPage * defaultRefinement={20} * items={[{value: '30', label: 'Show 20 hits'}, {value: '50', label: 'Show 50 hits'}]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHitsPerPage2.default)(_HitsPerPage2.default); /***/ }), /* 359 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectInfiniteHits = __webpack_require__(224); var _connectInfiniteHits2 = _interopRequireDefault(_connectInfiniteHits); var _InfiniteHits = __webpack_require__(383); var _InfiniteHits2 = _interopRequireDefault(_InfiniteHits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays an infinite list of hits along with a **load more** button. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name InfiniteHits * @kind widget * @propType {Component} hitComponent - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey root - the root of the component * @translationKey loadMore - the label of load more button * @example * import React from 'react'; * import { InfiniteHits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <InfiniteHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectInfiniteHits2.default)(_InfiniteHits2.default); /***/ }), /* 360 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMenu = __webpack_require__(225); var _connectMenu2 = _interopRequireDefault(_connectMenu); var _Menu = __webpack_require__(385); var _Menu2 = _interopRequireDefault(_Menu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Menu component displays a menu that lets the user choose a single value for a specific attribute. * @name Menu * @kind widget * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values * @themeKey ais-Menu__root - the root of the component * @themeKey ais-Menu__items - the container of all items in the menu * @themeKey ais-Menu__item - a single item * @themeKey ais-Menu__itemLinkSelected - the selected menu item * @themeKey ais-Menu__itemLink - the item link * @themeKey ais-Menu__itemLabelSelected - the selected item label * @themeKey ais-Menu__itemLabel - the item label * @themeKey ais-Menu__itemCount - the item count * @themeKey ais-Menu__itemCountSelected - the selected item count * @themeKey ais-Menu__noRefinement - present when there is no refinement * @themeKey ais-Menu__showMore - the button that let the user toggle more results * @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @example * import React from 'react'; * * import { Menu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Menu * attributeName="category" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMenu2.default)(_Menu2.default); /***/ }), /* 361 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMultiRange = __webpack_require__(226); var _connectMultiRange2 = _interopRequireDefault(_connectMultiRange); var _MultiRange = __webpack_require__(386); var _MultiRange2 = _interopRequireDefault(_MultiRange); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * MultiRange is a widget used for selecting the range value of a numeric attribute. * @name MultiRange * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max". * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-MultiRange__root - The root component of the widget * @themeKey ais-MultiRange__items - The container of the items * @themeKey ais-MultiRange__item - A single item * @themeKey ais-MultiRange__itemSelected - The selected item * @themeKey ais-MultiRange__itemLabel - The label of an item * @themeKey ais-MultiRange__itemLabelSelected - The selected label item * @themeKey ais-MultiRange__itemRadio - The radio of an item * @themeKey ais-MultiRange__itemRadioSelected - The selected radio item * @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges * @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range * @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * * import { MultiRange, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <MultiRange * attributeName="price" * items={[ * { end: 10, label: '<$10' }, * { start: 10, end: 100, label: '$10-$100' }, * { start: 100, end: 500, label: '$100-$500' }, * { start: 500, label: '>$500' }, * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMultiRange2.default)(_MultiRange2.default); /***/ }), /* 362 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPagination = __webpack_require__(227); var _connectPagination2 = _interopRequireDefault(_connectPagination); var _Pagination = __webpack_require__(387); var _Pagination2 = _interopRequireDefault(_Pagination); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Pagination widget displays a simple pagination system allowing the user to * change the current page. * @name Pagination * @kind widget * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @themeKey ais-Pagination__root - The root component of the widget * @themeKey ais-Pagination__itemFirst - The first page link item * @themeKey ais-Pagination__itemPrevious - The previous page link item * @themeKey ais-Pagination__itemPage - The page link item * @themeKey ais-Pagination__itemNext - The next page link item * @themeKey ais-Pagination__itemLast - The last page link item * @themeKey ais-Pagination__itemDisabled - a disabled item * @themeKey ais-Pagination__itemSelected - a selected item * @themeKey ais-Pagination__itemLink - The link of an item * @themeKey ais-Pagination__noRefinement - present when there is no refinement * @translationKey previous - Label value for the previous page link * @translationKey next - Label value for the next page link * @translationKey first - Label value for the first page link * @translationKey last - Label value for the last page link * @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string * @translationKey ariaPrevious - Accessibility label value for the previous page link * @translationKey ariaNext - Accessibility label value for the next page link * @translationKey ariaFirst - Accessibility label value for the first page link * @translationKey ariaLast - Accessibility label value for the last page link * @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string * @example * import React from 'react'; * * import { Pagination, InstantSearch } from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Pagination /> * </InstantSearch> * ); * } */ exports.default = (0, _connectPagination2.default)(_Pagination2.default); /***/ }), /* 363 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _Panel = __webpack_require__(388); var _Panel2 = _interopRequireDefault(_Panel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Panel widget wraps other widgets in a consistent panel design. * * It also reacts, indicates and set CSS classes when widgets are no more * relevant for refining. E.g. when a RefinementList becomes empty because of * the current search results. * @name Panel * @kind widget * @propType {string} title - The panel title * @themeKey ais-Panel__root - Container of the widget * @themeKey ais-Panel__title - The panel title * @themeKey ais-Panel__noRefinement - Present if the panel content is empty * @example * import React from 'react'; * * import { Panel, RefinementList, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Panel title="category"> * <RefinementList attributeName="category" /> * </Panel> * </InstantSearch> * ); * } */ exports.default = _Panel2.default; /***/ }), /* 364 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPoweredBy = __webpack_require__(228); var _connectPoweredBy2 = _interopRequireDefault(_connectPoweredBy); var _PoweredBy = __webpack_require__(389); var _PoweredBy2 = _interopRequireDefault(_PoweredBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * PoweredBy displays an Algolia logo. * * Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing). * @name PoweredBy * @kind widget * @themeKey ais-PoweredBy__root - The root component of the widget * @themeKey ais-PoweredBy__searchBy - The powered by label * @themeKey ais-PoweredBy__algoliaLink - The algolia logo link * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * * import { PoweredBy, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <PoweredBy /> * </InstantSearch> * ); * } */ exports.default = (0, _connectPoweredBy2.default)(_PoweredBy2.default); /***/ }), /* 365 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _RangeInput = __webpack_require__(390); var _RangeInput2 = _interopRequireDefault(_RangeInput); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * RangeInput allows a user to select a numeric range using a minimum and maximum input. * @name RangeInput * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the record * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @themeKey ais-RangeInput__root - The root component of the widget * @themeKey ais-RangeInput__labelMin - The label for the min input * @themeKey ais-RangeInput__inputMin - The min input * @themeKey ais-RangeInput__separator - The separator between input * @themeKey ais-RangeInput__labelMax - The label for the max input * @themeKey ais-RangeInput__inputMax - The max input * @themeKey ais-RangeInput__submit - The submit button * @themeKey ais-RangeInput__noRefinement - present when there is no refinement * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * * import { RangeInput, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RangeInput attributeName="price"/> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_RangeInput2.default); /***/ }), /* 366 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Since a lot of sliders already exist, we did not include one by default. * However you can easily connect React InstantSearch to an existing one * using the [connectRange connector](connectors/connectRange.html). * * @name RangeSlider * @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values. * @kind widget * @example * * // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the * // range connector import PropTypes from 'prop-types'; import React, {Component} from 'react'; import {connectRange} from 'react-instantsearch/connectors'; import Rheostat from 'rheostat'; class Range extends React.Component { static propTypes = { min: PropTypes.number, max: PropTypes.number, currentRefinement: PropTypes.object, refine: PropTypes.func.isRequired, canRefine: PropTypes.bool.isRequired, }; state = {currentValues: {min: this.props.min, max: this.props.max}}; componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}}); } } onValuesUpdated = (sliderState) => { this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}}); }; onChange = (sliderState) => { if (this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1]) { this.props.refine({min: sliderState.values[0], max: sliderState.values[1]}); } }; render() { const {min, max, currentRefinement} = this.props; const {currentValues} = this.state; return min !== max ? <div> <Rheostat min={min} max={max} values={[currentRefinement.min, currentRefinement.max]} onChange={this.onChange} onValuesUpdated={this.onValuesUpdated} /> <div style={{display: 'flex', justifyContent: 'space-between'}}> <div>{currentValues.min}</div> <div>{currentValues.max}</div> </div> </div> : null; } } const ConnectedRange = connectRange(Range); */ exports.default = (0, _connectRange2.default)(function () { return _react2.default.createElement( 'div', null, 'We do not provide any Slider, see the documentation to learn how to connect one easily:', _react2.default.createElement( 'a', { target: '_blank', href: 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' }, 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' ) ); }); /***/ }), /* 367 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRefinementList = __webpack_require__(229); var _connectRefinementList2 = _interopRequireDefault(_connectRefinementList); var _RefinementList = __webpack_require__(391); var _RefinementList2 = _interopRequireDefault(_RefinementList); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximum number of displayed items. Only used when showMore is set to `true` * @propType {string[]} [defaultRefinement] - the values of the items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-RefinementList__root - the root of the component * @themeKey ais-RefinementList__items - the container of all items in the list * @themeKey ais-RefinementList__itemSelected - the selected list item * @themeKey ais-RefinementList__itemCheckbox - the item checkbox * @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox * @themeKey ais-RefinementList__itemLabel - the item label * @themeKey ais-RefinementList__itemLabelSelected - the selected item label * @themeKey RefinementList__itemCount - the item count * @themeKey RefinementList__itemCountSelected - the selected item count * @themeKey ais-RefinementList__showMore - the button that let the user toggle more results * @themeKey ais-RefinementList__noRefinement - present when there is no refinement * @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @example * import React from 'react'; * * import { RefinementList, InstantSearch } from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RefinementList attributeName="colors" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRefinementList2.default)(_RefinementList2.default); /***/ }), /* 368 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectScrollTo = __webpack_require__(230); var _connectScrollTo2 = _interopRequireDefault(_connectScrollTo); var _ScrollTo = __webpack_require__(392); var _ScrollTo2 = _interopRequireDefault(_ScrollTo); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ScrollTo component will made the page scroll to the component wrapped by it when one of the * [search state](guide/Search_state.html) prop is updated. By default when the page number changes, * the scroll goes to the wrapped component. * * @name ScrollTo * @kind widget * @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes. * @example * import React from 'react'; * * import { ScrollTo, Hits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); * } */ exports.default = (0, _connectScrollTo2.default)(_ScrollTo2.default); /***/ }), /* 369 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSearchBox = __webpack_require__(231); var _connectSearchBox2 = _interopRequireDefault(_connectSearchBox); var _SearchBox = __webpack_require__(346); var _SearchBox2 = _interopRequireDefault(_SearchBox); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SearchBox component displays a search box that lets the user search for a specific query. * @name SearchBox * @kind widget * @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes. * @propType {boolean} [autoFocus=false] - Should the search box be focused on render? * @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused. * @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container. * @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container. * @propType {function} [on*] - Listen to any events sent form the search input itself. * @propType {React.Element} [submitComponent] - Change the apparence of the default submit button (magnifying glass). * @propType {React.Element} [resetComponent] - Change the apparence of the default reset button (cross). * @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted. * @themeKey ais-SearchBox__root - the root of the component * @themeKey ais-SearchBox__wrapper - the search box wrapper * @themeKey ais-SearchBox__input - the search box input * @themeKey ais-SearchBox__submit - the submit button * @themeKey ais-SearchBox__reset - the reset button * @translationkey submitTitle - The submit button title * @translationkey resetTitle - The reset button title * @translationkey placeholder - The label of the input placeholder * @example * import React from 'react'; * * import { SearchBox, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSearchBox2.default)(_SearchBox2.default); /***/ }), /* 370 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(211); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Snippet = __webpack_require__(393); var _Snippet2 = _interopRequireDefault(_Snippet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted snippet form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Snippet * @kind widget * @propType {string} attributeName - the location of the highlighted snippet attribute in the hit * @propType {object} hit - the hit object containing the highlighted snippet attribute * @propType {string} [tagName='em'] - the tag to be used for highlighted parts of the attribute * @example * import React from 'react'; * * import { connectHits, Snippet, InstantSearch } from 'react-instantsearch/dom'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Snippet attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Snippet2.default); /***/ }), /* 371 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSortBy = __webpack_require__(232); var _connectSortBy2 = _interopRequireDefault(_connectSortBy); var _SortBy = __webpack_require__(394); var _SortBy2 = _interopRequireDefault(_SortBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SortBy component displays a list of indexes allowing a user to change the hits are sorting. * @name SortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind widget * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {string} defaultRefinement - The default selected index. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-SortBy__root - the root of the component * @example * import React from 'react'; * * import { SortBy, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SortBy * items={[ * { value: 'ikea', label: 'Featured' }, * { value: 'ikea_price_asc', label: 'Price asc.' }, * { value: 'ikea_price_desc', label: 'Price desc.' }, * ]} * defaultRefinement="ikea" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSortBy2.default)(_SortBy2.default); /***/ }), /* 372 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(112); var _connectRange2 = _interopRequireDefault(_connectRange); var _StarRating = __webpack_require__(395); var _StarRating2 = _interopRequireDefault(_StarRating); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * StarRating lets the user refine search results by clicking on stars. * * The stars are based on the selected `attributeName`. * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @name StarRating * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating. * @themeKey ais-StarRating__root - The root component of the widget * @themeKey ais-StarRating__ratingLink - The item link * @themeKey ais-StarRating__ratingLinkSelected - The selected link item * @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item * @themeKey ais-StarRating__ratingIcon - The rating icon * @themeKey ais-StarRating__ratingIconSelected - The selected rating icon * @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon * @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon * @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon * @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon * @themeKey ais-StarRating__ratingLabel - The link label * @themeKey ais-StarRating__ratingLabelSelected - The selected link label * @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label * @themeKey ais-StarRating__ratingCount - The link count * @themeKey ais-StarRating__ratingCountSelected - The selected link count * @themeKey ais-StarRating__ratingCountDisabled - The disabled link count * @themeKey ais-StarRating__noRefinement - present when there is no refinement * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * * import { StarRating, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <StarRating attributeName="rating" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_StarRating2.default); /***/ }), /* 373 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectStats = __webpack_require__(233); var _connectStats2 = _interopRequireDefault(_connectStats); var _Stats = __webpack_require__(396); var _Stats2 = _interopRequireDefault(_Stats); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). * @name Stats * @kind widget * @themeKey ais-Stats__root - the root of the component * @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time. * @example * import React from 'react'; * * import { Stats, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Stats /> * </InstantSearch> * ); * } */ exports.default = (0, _connectStats2.default)(_Stats2.default); /***/ }), /* 374 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _connectToggle = __webpack_require__(234); var _connectToggle2 = _interopRequireDefault(_connectToggle); var _Toggle = __webpack_require__(397); var _Toggle2 = _interopRequireDefault(_Toggle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Toggle provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization. * @name Toggle * @kind widget * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName` when checked. * @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-Toggle__root - the root of the component * @themeKey ais-Toggle__checkbox - the toggle checkbox * @themeKey ais-Toggle__label - the toggle label * @example * import React from 'react'; * * import { Toggle, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Toggle * attributeName="materials" * label="Made with solid pine" * value={'Solid pine'} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectToggle2.default)(_Toggle2.default); /***/ }), /* 375 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var AlgoliaSearchCore = __webpack_require__(404); var createAlgoliasearch = __webpack_require__(406); module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) '); /***/ }), /* 376 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('ClearAll'); var ClearAll = function (_Component) { _inherits(ClearAll, _Component); function ClearAll() { _classCallCheck(this, ClearAll); return _possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments)); } _createClass(ClearAll, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var items = _props.items; var refine = _props.refine; var isDisabled = items.length === 0; if (isDisabled) { return _react2.default.createElement( 'button', _extends({}, cx('root'), { disabled: true }), translate('reset') ); } return _react2.default.createElement( 'button', _extends({}, cx('root'), { onClick: refine.bind(null, items) }), translate('reset') ); } }]); return ClearAll; }(_react.Component); ClearAll.propTypes = { translate: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.object).isRequired, refine: _propTypes2.default.func.isRequired }; exports.default = (0, _translatable2.default)({ reset: 'Clear all filters' })(ClearAll); /***/ }), /* 377 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { return null; }; /***/ }), /* 378 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('CurrentRefinements'); var CurrentRefinements = function (_Component) { _inherits(CurrentRefinements, _Component); function CurrentRefinements() { _classCallCheck(this, CurrentRefinements); return _possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments)); } _createClass(CurrentRefinements, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var items = _props.items; var refine = _props.refine; var canRefine = _props.canRefine; return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), _react2.default.createElement( 'div', cx('items'), items.map(function (item) { return _react2.default.createElement( 'div', _extends({ key: item.label }, cx('item', item.items && 'itemParent')), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), item.items ? item.items.map(function (nestedItem) { return _react2.default.createElement( 'div', _extends({ key: nestedItem.label }, cx('item')), _react2.default.createElement( 'span', cx('itemLabel'), nestedItem.label ), _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, nestedItem.value) }), translate('clearFilter', nestedItem) ) ); }) : _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, item.value) }), translate('clearFilter', item) ) ); }) ) ); } }]); return CurrentRefinements; }(_react.Component); CurrentRefinements.propTypes = { translate: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string })).isRequired, refine: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, transformItems: _propTypes2.default.func }; CurrentRefinements.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ clearFilter: '✕' })(CurrentRefinements); /***/ }), /* 379 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('HierarchicalMenu'); var itemsPropType = _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.string, count: _propTypes2.default.number.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var HierarchicalMenu = function (_Component) { _inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props; var createURL = _this$props.createURL; var refine = _this$props.refine; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink'), { onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), ' ', _react2.default.createElement( 'span', cx('itemCount'), item.count ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(HierarchicalMenu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine']))); } }]); return HierarchicalMenu; }(_react.Component); HierarchicalMenu.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, items: itemsPropType, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; HierarchicalMenu.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /***/ }), /* 380 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; exports.default = Highlight; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(345); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlight(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_highlightResult' }, props)); } Highlight.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 381 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('Hits'); var Hits = function (_Component) { _inherits(Hits, _Component); function Hits() { _classCallCheck(this, Hits); return _possibleConstructorReturn(this, (Hits.__proto__ || Object.getPrototypeOf(Hits)).apply(this, arguments)); } _createClass(Hits, [{ key: 'render', value: function render() { var _props = this.props; var ItemComponent = _props.hitComponent; var hits = _props.hits; return _react2.default.createElement( 'div', cx('root'), hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }) ); } }]); return Hits; }(_react.Component); Hits.propTypes = { hits: _propTypes2.default.array, hitComponent: _propTypes2.default.func.isRequired }; /* eslint-disable react/display-name */ Hits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; /* eslint-enable react/display-name */ exports.default = Hits; /***/ }), /* 382 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(347); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('HitsPerPage'); var HitsPerPage = function (_Component) { _inherits(HitsPerPage, _Component); function HitsPerPage() { _classCallCheck(this, HitsPerPage); return _possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments)); } _createClass(HitsPerPage, [{ key: 'render', value: function render() { var _props = this.props; var currentRefinement = _props.currentRefinement; var refine = _props.refine; var items = _props.items; return _react2.default.createElement(_Select2.default, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx }); } }]); return HitsPerPage; }(_react.Component); HitsPerPage.propTypes = { refine: _propTypes2.default.func.isRequired, currentRefinement: _propTypes2.default.number.isRequired, transformItems: _propTypes2.default.func, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ /** * Number of hits to display. */ value: _propTypes2.default.number.isRequired, /** * Label to display on the option. */ label: _propTypes2.default.string })) }; exports.default = HitsPerPage; /***/ }), /* 383 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); 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 cx = (0, _classNames2.default)('InfiniteHits'); var InfiniteHits = function (_Component) { _inherits(InfiniteHits, _Component); function InfiniteHits() { _classCallCheck(this, InfiniteHits); return _possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments)); } _createClass(InfiniteHits, [{ key: 'render', value: function render() { var _props = this.props; var ItemComponent = _props.hitComponent; var hits = _props.hits; var hasMore = _props.hasMore; var refine = _props.refine; var translate = _props.translate; var renderedHits = hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }); var loadMoreButton = hasMore ? _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { onClick: function onClick() { return refine(); } }), translate('loadMore') ) : _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { disabled: true }), translate('loadMore') ); return _react2.default.createElement( 'div', cx('root'), renderedHits, loadMoreButton ); } }]); return InfiniteHits; }(_react.Component); InfiniteHits.propTypes = { hits: _propTypes2.default.array, hitComponent: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]).isRequired, hasMore: _propTypes2.default.bool.isRequired, refine: _propTypes2.default.func.isRequired, translate: _propTypes2.default.func.isRequired }; /* eslint-disable react/display-name */ InfiniteHits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; /* eslint-enable react/display-name */ exports.default = (0, _translatable2.default)({ loadMore: 'Load more' })(InfiniteHits); /***/ }), /* 384 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(57); var _has3 = _interopRequireDefault(_has2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); 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 LinkList = function (_Component) { _inherits(LinkList, _Component); function LinkList() { _classCallCheck(this, LinkList); return _possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments)); } _createClass(LinkList, [{ key: 'render', value: function render() { var _props = this.props; var cx = _props.cx; var createURL = _props.createURL; var items = _props.items; var onSelect = _props.onSelect; var canRefine = _props.canRefine; return _react2.default.createElement( 'ul', cx('root', !canRefine && 'noRefinement'), items.map(function (item) { return _react2.default.createElement( 'li', _extends({ key: (0, _has3.default)(item, 'key') ? item.key : item.value }, cx('item', item.selected && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), { disabled: item.disabled }), item.disabled ? _react2.default.createElement( 'span', cx('itemLink', 'itemLinkDisabled'), (0, _has3.default)(item, 'label') ? item.label : item.value ) : _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.selected && 'itemLinkSelected'), { 'aria-label': item.ariaLabel, href: createURL(item.value), onClick: onSelect.bind(null, item.value) }), (0, _has3.default)(item, 'label') ? item.label : item.value ) ); }) ); } }]); return LinkList; }(_react.Component); LinkList.propTypes = { cx: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number, _propTypes2.default.object]).isRequired, key: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), label: _propTypes2.default.node, modifier: _propTypes2.default.string, ariaLabel: _propTypes2.default.string, disabled: _propTypes2.default.bool })), onSelect: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired }; exports.default = LinkList; /***/ }), /* 385 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(236); var _Link2 = _interopRequireDefault(_Link); var _Highlight = __webpack_require__(235); var _Highlight2 = _interopRequireDefault(_Highlight); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('Menu'); var Menu = function (_Component) { _inherits(Menu, _Component); function Menu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Menu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item, resetQuery) { var createURL = _this.props.createURL; var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.isRefined && 'itemLinkSelected'), { onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }, _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Menu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']))); } }]); return Menu; }(_react.Component); Menu.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, searchForItems: _propTypes2.default.func.isRequired, withSearchBox: _propTypes2.default.bool, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.string.isRequired, count: _propTypes2.default.number.isRequired, isRefined: _propTypes2.default.bool.isRequired })), isFromSearch: _propTypes2.default.bool.isRequired, canRefine: _propTypes2.default.bool.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; Menu.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(Menu); /***/ }), /* 386 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); 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 cx = (0, _classNames2.default)('MultiRange'); var MultiRange = function (_Component) { _inherits(MultiRange, _Component); function MultiRange() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MultiRange); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props; var refine = _this$props.refine; var translate = _this$props.translate; var label = item.value === '' ? translate('all') : item.label; return _react2.default.createElement( 'label', cx(item.value === '' && 'itemAll'), _react2.default.createElement('input', _extends({}, cx('itemRadio', item.isRefined && 'itemRadioSelected'), { type: 'radio', checked: item.isRefined, disabled: item.noRefinement, onChange: refine.bind(null, item.value) })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MultiRange, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props; var items = _props.items; var canRefine = _props.canRefine; return _react2.default.createElement(_List2.default, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx, items: items.map(function (item) { return _extends({}, item, { key: item.value }); }) }); } }]); return MultiRange; }(_react.Component); MultiRange.propTypes = { items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.node.isRequired, value: _propTypes2.default.string.isRequired, isRefined: _propTypes2.default.bool.isRequired, noRefinement: _propTypes2.default.bool.isRequired })).isRequired, refine: _propTypes2.default.func.isRequired, transformItems: _propTypes2.default.func, canRefine: _propTypes2.default.bool.isRequired, translate: _propTypes2.default.func.isRequired }; MultiRange.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ all: 'All' })(MultiRange); /***/ }), /* 387 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _range2 = __webpack_require__(424); var _range3 = _interopRequireDefault(_range2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(58); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _LinkList = __webpack_require__(384); var _LinkList2 = _interopRequireDefault(_LinkList); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 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 cx = (0, _classNames2.default)('Pagination'); function getPagesDisplayedCount(padding, total) { return Math.min(2 * padding + 1, total); } function calculatePaddingLeft(current, padding, total, totalDisplayedPages) { if (current <= padding) { return current; } if (current >= total - padding) { return totalDisplayedPages - (total - current); } return padding; } function getPages(page, total, padding) { var totalDisplayedPages = getPagesDisplayedCount(padding, total); if (totalDisplayedPages === total) return (0, _range3.default)(1, total + 1); var paddingLeft = calculatePaddingLeft(page, padding, total, totalDisplayedPages); var paddingRight = totalDisplayedPages - paddingLeft; var first = page - paddingLeft; var last = page + paddingRight; return (0, _range3.default)(first + 1, last + 1); } var Pagination = function (_Component) { _inherits(Pagination, _Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments)); } _createClass(Pagination, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'getItem', value: function getItem(modifier, translationKey, value) { var _props = this.props; var nbPages = _props.nbPages; var maxPages = _props.maxPages; var translate = _props.translate; return { key: modifier + '.' + value, modifier: modifier, disabled: value < 1 || value >= Math.min(maxPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate('aria' + (0, _utils.capitalize)(translationKey), value) }; } }, { key: 'render', value: function render() { var _props2 = this.props; var nbPages = _props2.nbPages; var maxPages = _props2.maxPages; var currentRefinement = _props2.currentRefinement; var pagesPadding = _props2.pagesPadding; var showFirst = _props2.showFirst; var showPrevious = _props2.showPrevious; var showNext = _props2.showNext; var showLast = _props2.showLast; var refine = _props2.refine; var createURL = _props2.createURL; var translate = _props2.translate; var ListComponent = _props2.listComponent; var otherProps = _objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']); var totalPages = Math.min(nbPages, maxPages); var lastPage = totalPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'itemFirst', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'itemPrevious', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) { return { key: value, modifier: 'itemPage', label: translate('page', value), value: value, selected: value === currentRefinement, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'itemNext', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'itemLast', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return _react2.default.createElement(ListComponent, _extends({}, otherProps, { cx: cx, items: items, onSelect: refine, createURL: createURL })); } }]); return Pagination; }(_react.Component); Pagination.propTypes = { nbPages: _propTypes2.default.number.isRequired, currentRefinement: _propTypes2.default.number.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, canRefine: _propTypes2.default.bool.isRequired, translate: _propTypes2.default.func.isRequired, listComponent: _propTypes2.default.func, showFirst: _propTypes2.default.bool, showPrevious: _propTypes2.default.bool, showNext: _propTypes2.default.bool, showLast: _propTypes2.default.bool, pagesPadding: _propTypes2.default.number, maxPages: _propTypes2.default.number }; Pagination.defaultProps = { listComponent: _LinkList2.default, showFirst: true, showPrevious: true, showNext: true, showLast: false, pagesPadding: 3, maxPages: Infinity }; Pagination.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ previous: '‹', next: '›', first: '«', last: '»', page: function page(currentRefinement) { return currentRefinement.toString(); }, ariaPrevious: 'Previous page', ariaNext: 'Next page', ariaFirst: 'First page', ariaLast: 'Last page', ariaPage: function ariaPage(currentRefinement) { return 'Page ' + currentRefinement.toString(); } })(Pagination); /***/ }), /* 388 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('Panel'); var Panel = function (_Component) { _inherits(Panel, _Component); _createClass(Panel, [{ key: 'getChildContext', value: function getChildContext() { return { canRefine: this.canRefine }; } }]); function Panel(props) { _classCallCheck(this, Panel); var _this = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props)); _this.state = { canRefine: true }; _this.canRefine = function (canRefine) { _this.setState({ canRefine: canRefine }); }; return _this; } _createClass(Panel, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', cx('root', !this.state.canRefine && 'noRefinement'), _react2.default.createElement( 'h5', cx('title'), this.props.title ), this.props.children ); } }]); return Panel; }(_react.Component); Panel.propTypes = { title: _propTypes2.default.string.isRequired, children: _propTypes2.default.node }; Panel.childContextTypes = { canRefine: _propTypes2.default.func }; exports.default = Panel; /***/ }), /* 389 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362' }, _react2.default.createElement( 'linearGradient', { id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' }, _react2.default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }), _react2.default.createElement('stop', { offset: '1', stopColor: '#3369E7' }) ), _react2.default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }), _react2.default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }), _react2.default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' }) ); }; /* eslint-enable max-len */ var PoweredBy = function (_Component) { _inherits(PoweredBy, _Component); function PoweredBy() { _classCallCheck(this, PoweredBy); return _possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments)); } _createClass(PoweredBy, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var url = _props.url; return _react2.default.createElement( 'div', cx('root'), _react2.default.createElement( 'span', cx('searchBy'), translate('searchBy'), ' ' ), _react2.default.createElement( 'a', _extends({ href: url, target: '_blank' }, cx('algoliaLink')), _react2.default.createElement(AlgoliaLogo, null) ) ); } }]); return PoweredBy; }(_react.Component); PoweredBy.propTypes = { url: _propTypes2.default.string.isRequired, translate: _propTypes2.default.func.isRequired }; exports.default = (0, _translatable2.default)({ searchBy: 'Search by' })(PoweredBy); /***/ }), /* 390 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isNaN2 = __webpack_require__(218); var _isNaN3 = _interopRequireDefault(_isNaN2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('RangeInput'); var RangeInput = function (_Component) { _inherits(RangeInput, _Component); function RangeInput(props) { _classCallCheck(this, RangeInput); var _this = _possibleConstructorReturn(this, (RangeInput.__proto__ || Object.getPrototypeOf(RangeInput)).call(this, props)); _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); if (!(0, _isNaN3.default)(parseFloat(_this.state.from, 10)) && !(0, _isNaN3.default)(parseFloat(_this.state.to, 10))) { _this.props.refine({ min: _this.state.from, max: _this.state.to }); } }; _this.state = _this.props.canRefine ? { from: props.currentRefinement.min, to: props.currentRefinement.max } : { from: '', to: '' }; return _this; } _createClass(RangeInput, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.canRefine) { this.setState({ from: nextProps.currentRefinement.min, to: nextProps.currentRefinement.max }); } if (this.context.canRefine) this.context.canRefine(nextProps.canRefine); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var canRefine = _props.canRefine; return _react2.default.createElement( 'form', _extends({}, cx('root', !canRefine && 'noRefinement'), { onSubmit: this.onSubmit }), _react2.default.createElement( 'fieldset', _extends({ disabled: !canRefine }, cx('fieldset')), _react2.default.createElement( 'label', cx('labelMin'), _react2.default.createElement('input', _extends({}, cx('inputMin'), { type: 'number', value: this.state.from, onChange: function onChange(e) { return _this2.setState({ from: e.target.value }); } })) ), _react2.default.createElement( 'span', cx('separator'), translate('separator') ), _react2.default.createElement( 'label', cx('labelMax'), _react2.default.createElement('input', _extends({}, cx('inputMax'), { type: 'number', value: this.state.to, onChange: function onChange(e) { return _this2.setState({ to: e.target.value }); } })) ), _react2.default.createElement( 'button', _extends({}, cx('submit'), { type: 'submit' }), translate('submit') ) ) ); } }]); return RangeInput; }(_react.Component); RangeInput.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, min: _propTypes2.default.number, max: _propTypes2.default.number, currentRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number, max: _propTypes2.default.number }), canRefine: _propTypes2.default.bool.isRequired }; RangeInput.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ submit: 'ok', separator: 'to' })(RangeInput); /***/ }), /* 391 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(111); var _pick3 = _interopRequireDefault(_pick2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(212); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(14); var _classNames2 = _interopRequireDefault(_classNames); var _Highlight = __webpack_require__(235); var _Highlight2 = _interopRequireDefault(_Highlight); 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 cx = (0, _classNames2.default)('RefinementList'); var RefinementList = function (_Component) { _inherits(RefinementList, _Component); function RefinementList(props) { _classCallCheck(this, RefinementList); var _this = _possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props)); _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }; _this.renderItem = function (item, resetQuery) { var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( 'label', null, _react2.default.createElement('input', _extends({}, cx('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), { type: 'checkbox', checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item, resetQuery); } })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }; _this.state = { query: '' }; return _this; } _createClass(RefinementList, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement( 'div', null, _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']), { query: this.state.query })) ); } }]); return RefinementList; }(_react.Component); RefinementList.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, searchForItems: _propTypes2.default.func.isRequired, withSearchBox: _propTypes2.default.bool, createURL: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string.isRequired, value: _propTypes2.default.arrayOf(_propTypes2.default.string).isRequired, count: _propTypes2.default.number.isRequired, isRefined: _propTypes2.default.bool.isRequired })), isFromSearch: _propTypes2.default.bool.isRequired, canRefine: _propTypes2.default.bool.isRequired, showMore: _propTypes2.default.bool, limitMin: _propTypes2.default.number, limitMax: _propTypes2.default.number, transformItems: _propTypes2.default.func }; RefinementList.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(RefinementList); /***/ }), /* 392 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _reactDom = __webpack_require__(429); 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 ScrollTo = function (_Component) { _inherits(ScrollTo, _Component); function ScrollTo() { _classCallCheck(this, ScrollTo); return _possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments)); } _createClass(ScrollTo, [{ key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var value = this.props.value; if (value !== prevProps.value) { var el = (0, _reactDom.findDOMNode)(this); el.scrollIntoView(); } } }, { key: 'render', value: function render() { return _react.Children.only(this.props.children); } }]); return ScrollTo; }(_react.Component); ScrollTo.propTypes = { value: _propTypes2.default.any, children: _propTypes2.default.node }; exports.default = ScrollTo; /***/ }), /* 393 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; exports.default = Snippet; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(345); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Snippet(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_snippetResult' }, props)); } Snippet.propTypes = { hit: _propTypes2.default.object.isRequired, attributeName: _propTypes2.default.string.isRequired, highlight: _propTypes2.default.func.isRequired, tagName: _propTypes2.default.string }; /***/ }), /* 394 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(347); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('SortBy'); var SortBy = function (_Component) { _inherits(SortBy, _Component); function SortBy() { var _ref; var _temp, _this, _ret; _classCallCheck(this, SortBy); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = SortBy.__proto__ || Object.getPrototypeOf(SortBy)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(SortBy, [{ key: 'render', value: function render() { var _props = this.props; var refine = _props.refine; var items = _props.items; var currentRefinement = _props.currentRefinement; return _react2.default.createElement(_Select2.default, { cx: cx, selectedItem: currentRefinement, onSelect: refine, items: items }); } }]); return SortBy; }(_react.Component); SortBy.propTypes = { refine: _propTypes2.default.func.isRequired, items: _propTypes2.default.arrayOf(_propTypes2.default.shape({ label: _propTypes2.default.string, value: _propTypes2.default.string.isRequired })).isRequired, currentRefinement: _propTypes2.default.string.isRequired, transformItems: _propTypes2.default.func }; exports.default = SortBy; /***/ }), /* 395 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('StarRating'); var StarRating = function (_Component) { _inherits(StarRating, _Component); function StarRating() { _classCallCheck(this, StarRating); return _possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments)); } _createClass(StarRating, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'onClick', value: function onClick(min, max, e) { e.preventDefault(); e.stopPropagation(); if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) { this.props.refine({ min: this.props.min, max: this.props.max }); } else { this.props.refine({ min: min, max: max }); } } }, { key: 'buildItem', value: function buildItem(_ref) { var max = _ref.max; var lowerBound = _ref.lowerBound; var count = _ref.count; var translate = _ref.translate; var createURL = _ref.createURL; var isLastSelectableItem = _ref.isLastSelectableItem; var disabled = !count; var isCurrentMinLower = this.props.currentRefinement.min < lowerBound; var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max; var icons = []; for (var icon = 0; icon < max; icon++) { var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon'; icons.push(_react2.default.createElement('span', _extends({ key: icon }, cx(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled')))); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var StarsWrapper = isLastAndSelect ? 'div' : 'a'; var onClickHandler = isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return _react2.default.createElement( StarsWrapper, _extends({}, cx('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), { disabled: disabled, key: lowerBound }, onClickHandler), icons, _react2.default.createElement( 'span', cx('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'), translate('ratingLabel') ), _react2.default.createElement( 'span', null, ' ' ), _react2.default.createElement( 'span', cx('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'), count ) ); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props; var translate = _props.translate; var refine = _props.refine; var min = _props.min; var max = _props.max; var count = _props.count; var createURL = _props.createURL; var canRefine = _props.canRefine; var items = []; var _loop = function _loop(i) { var hasCount = !(0, _isEmpty3.default)(count.filter(function (item) { return Number(item.value) === i; })); var lastSelectableItem = count.reduce(function (acc, item) { return item.value < acc.value || !acc.value && hasCount ? item : acc; }, {}); var itemCount = count.reduce(function (acc, item) { return item.value >= i && hasCount ? acc + item.count : acc; }, 0); items.push(_this2.buildItem({ lowerBound: i, max: max, refine: refine, count: itemCount, translate: translate, createURL: createURL, isLastSelectableItem: i === Number(lastSelectableItem.value) })); }; for (var i = max; i >= min; i--) { _loop(i); } return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), items ); } }]); return StarRating; }(_react.Component); StarRating.propTypes = { translate: _propTypes2.default.func.isRequired, refine: _propTypes2.default.func.isRequired, createURL: _propTypes2.default.func.isRequired, min: _propTypes2.default.number, max: _propTypes2.default.number, currentRefinement: _propTypes2.default.shape({ min: _propTypes2.default.number, max: _propTypes2.default.number }), count: _propTypes2.default.arrayOf(_propTypes2.default.shape({ value: _propTypes2.default.string, count: _propTypes2.default.number })), canRefine: _propTypes2.default.bool.isRequired }; StarRating.contextTypes = { canRefine: _propTypes2.default.func }; exports.default = (0, _translatable2.default)({ ratingLabel: ' & Up' })(StarRating); /***/ }), /* 396 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(33); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('Stats'); var Stats = function (_Component) { _inherits(Stats, _Component); function Stats() { _classCallCheck(this, Stats); return _possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments)); } _createClass(Stats, [{ key: 'render', value: function render() { var _props = this.props; var translate = _props.translate; var nbHits = _props.nbHits; var processingTimeMS = _props.processingTimeMS; return _react2.default.createElement( 'span', cx('root'), translate('stats', nbHits, processingTimeMS) ); } }]); return Stats; }(_react.Component); Stats.propTypes = { translate: _propTypes2.default.func.isRequired, nbHits: _propTypes2.default.number.isRequired, processingTimeMS: _propTypes2.default.number.isRequired }; exports.default = (0, _translatable2.default)({ stats: function stats(n, ms) { return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms'; } })(Stats); /***/ }), /* 397 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(14); 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 cx = (0, _classNames2.default)('Toggle'); var Toggle = function (_Component) { _inherits(Toggle, _Component); function Toggle() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Toggle); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.checked); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Toggle, [{ key: 'render', value: function render() { var _props = this.props; var currentRefinement = _props.currentRefinement; var label = _props.label; return _react2.default.createElement( 'label', cx('root'), _react2.default.createElement('input', _extends({}, cx('checkbox'), { type: 'checkbox', checked: currentRefinement, onChange: this.onChange })), _react2.default.createElement( 'span', cx('label'), label ) ); } }]); return Toggle; }(_react.Component); Toggle.propTypes = { currentRefinement: _propTypes2.default.bool.isRequired, refine: _propTypes2.default.func.isRequired, label: _propTypes2.default.string.isRequired }; exports.default = Toggle; /***/ }), /* 398 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); 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; } /* eslint valid-jsdoc: 0 */ /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @example * import {InstantSearch, Index, SearchBox, Hits, Configure} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch appId="" apiKey="" indexName="index1"> <SearchBox/> <Configure hitsPerPage={1} /> <Index indexName="index1"> <Hits /> </Index> <Index indexName="index2"> <Hits /> </Index> </InstantSearch> * ); * } */ var Index = function (_Component) { _inherits(Index, _Component); function Index(props, context) { _classCallCheck(this, Index); var _this = _possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).call(this, props)); var widgetsManager = context.ais.widgetsManager; /* we want <Index> to be seen as a regular widget. It means that with only <Index> present a new query will be sent to Algolia. That way you don't need a virtual hits widget to use the connectAutoComplete. */ _this.unregisterWidget = widgetsManager.registerWidget({ getSearchParameters: function getSearchParameters(searchParameters) { return _this.getSearchParameters.call(_this, searchParameters, _this.props); }, multiIndexContext: { targetedIndex: _this.props.indexName } }); return _this; } _createClass(Index, [{ key: 'componentWillUnmount', value: function componentWillUnmount() { this.unregisterWidget(); } }, { key: 'getChildContext', value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexName } }; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters, props) { return searchParameters.setIndex(props.indexName); } }, { key: 'render', value: function render() { var childrenCount = _react.Children.count(this.props.children); var _props$root = this.props.root; var Root = _props$root.Root; var props = _props$root.props; if (childrenCount === 0) return null;else return _react2.default.createElement( Root, props, this.props.children ); } }]); return Index; }(_react.Component); Index.propTypes = { // @TODO: These props are currently constant. indexName: _propTypes2.default.string.isRequired, children: _propTypes2.default.node, root: _propTypes2.default.shape({ Root: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]), props: _propTypes2.default.object }).isRequired }; Index.childContextTypes = { multiIndexContext: _propTypes2.default.object.isRequired }; Index.contextTypes = { // @TODO: more precise widgets manager propType ais: _propTypes2.default.object.isRequired }; exports.default = Index; /***/ }), /* 399 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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; }; }(); var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _createInstantSearchManager = __webpack_require__(400); var _createInstantSearchManager2 = _interopRequireDefault(_createInstantSearchManager); 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; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } else if (props.searchState && !nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @example * import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch * appId="appId" * apiKey="apiKey" * indexName="indexName" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); * } */ var InstantSearch = function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { _classCallCheck(this, InstantSearch); var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = (0, _createInstantSearchManager2.default)({ indexName: props.indexName, searchParameters: props.searchParameters, algoliaClient: props.algoliaClient, initialState: initialState }); return _this; } _createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this) } }; } return { ais: _extends({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = _react.Children.count(this.props.children); var _props$root = this.props.root; var Root = _props$root.Root; var props = _props$root.props; if (childrenCount === 0) return null;else return _react2.default.createElement( Root, props, this.props.children ); } }]); return InstantSearch; }(_react.Component); InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: _propTypes2.default.string.isRequired, algoliaClient: _propTypes2.default.object.isRequired, searchParameters: _propTypes2.default.object, createURL: _propTypes2.default.func, searchState: _propTypes2.default.object, onSearchStateChange: _propTypes2.default.func, children: _propTypes2.default.node, root: _propTypes2.default.shape({ Root: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]), props: _propTypes2.default.object }).isRequired }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: _propTypes2.default.object.isRequired }; exports.default = InstantSearch; /***/ }), /* 400 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(16); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(38); var _omit3 = _interopRequireDefault(_omit2); 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; }; exports.default = createInstantSearchManager; var _algoliasearchHelper = __webpack_require__(214); var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper); var _createWidgetsManager = __webpack_require__(402); var _createWidgetsManager2 = _interopRequireDefault(_createWidgetsManager); var _createStore = __webpack_require__(401); var _createStore2 = _interopRequireDefault(_createStore); var _highlightTags = __webpack_require__(213); var _highlightTags2 = _interopRequireDefault(_highlightTags); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _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; } /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName; var _ref$initialState = _ref.initialState; var initialState = _ref$initialState === undefined ? {} : _ref$initialState; var algoliaClient = _ref.algoliaClient; var _ref$searchParameters = _ref.searchParameters; var searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters; var baseSP = new _algoliasearchHelper.SearchParameters(_extends({}, searchParameters, { index: indexName }, _highlightTags2.default)); var helper = (0, _algoliasearchHelper2.default)(algoliaClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); var derivedHelpers = {}; var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used. var initialSearchParameters = helper.state; var widgetsManager = (0, _createWidgetsManager2.default)(onWidgetsUpdate); var store = (0, _createStore2.default)({ widgets: initialState, metadata: [], results: null, error: null, searching: false }); var skip = false; function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { indexMapping = {}; var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !widget.multiIndexContext; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); indexMapping[sharedParameters.index] = indexName; var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.multiIndexContext && widget.multiIndexContext.targetedIndex !== indexName; }).reduce(function (indices, widget) { var targetedIndex = widget.multiIndexContext.targetedIndex; var index = indices.find(function (i) { return i.targetedIndex === targetedIndex; }); if (index) { index.widgets.push(widget); } else { indices.push({ targetedIndex: targetedIndex, widgets: [widget] }); } return indices; }, []); var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.multiIndexContext && widget.multiIndexContext.targetedIndex === indexName; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state); var sharedParameters = _getSearchParameters.sharedParameters; var mainIndexParameters = _getSearchParameters.mainIndexParameters; var derivatedWidgets = _getSearchParameters.derivatedWidgets; Object.keys(derivedHelpers).forEach(function (key) { return derivedHelpers[key].detach(); }); derivedHelpers = {}; helper.setState(sharedParameters); derivatedWidgets.forEach(function (derivatedSearchParameters) { var index = derivatedSearchParameters.targetedIndex; var derivedHelper = helper.derive(function () { var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[parameters.index] = index; return parameters; }); derivedHelper.on('result', handleSearchSuccess); derivedHelper.on('error', handleSearchError); derivedHelpers[index] = derivedHelper; }); helper.setState(mainIndexParameters); helper.search(); } } function handleSearchSuccess(content) { var state = store.getState(); var results = state.results ? state.results : []; if (!(0, _isEmpty3.default)(derivedHelpers)) { results[indexMapping[content.index]] = content; } else { results = content; } var nextState = (0, _omit3.default)(_extends({}, store.getState(), { results: results, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var nextState = (0, _omit3.default)(_extends({}, store.getState(), { error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(nextSearchState) { store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(nextSearchState.facetName, nextSearchState.query).then(function (content) { var _extends2; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty(_extends2, nextSearchState.facetName, content.facetHits), _defineProperty(_extends2, 'query', nextSearchState.query), _extends2)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex, skipSearch: skipSearch }; } /***/ }), /* 401 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createStore; function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } /***/ }), /* 402 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createWidgetsManager; var _utils = __webpack_require__(58); function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; (0, _utils.defer)(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } /***/ }), /* 403 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withKeysPropType = exports.stateManagerPropType = exports.configManagerPropType = undefined; var _propTypes = __webpack_require__(1); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var configManagerPropType = exports.configManagerPropType = _propTypes2.default.shape({ register: _propTypes2.default.func.isRequired, swap: _propTypes2.default.func.isRequired, unregister: _propTypes2.default.func.isRequired }); var stateManagerPropType = exports.stateManagerPropType = _propTypes2.default.shape({ createURL: _propTypes2.default.func.isRequired, setState: _propTypes2.default.func.isRequired, getState: _propTypes2.default.func.isRequired, unlisten: _propTypes2.default.func.isRequired }); var withKeysPropType = exports.withKeysPropType = function withKeysPropType(keys) { return function (props, propName, componentName) { var prop = props[propName]; if (prop) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var key = _step.value; if (keys.indexOf(key) === -1) { return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.')); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } return undefined; }; }; /***/ }), /* 404 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {module.exports = AlgoliaSearchCore; var errors = __webpack_require__(215); var exitPromise = __webpack_require__(412); var IndexCore = __webpack_require__(405); var store = __webpack_require__(416); // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API. * Set to 'https:' to force using https. * Default to document.location.protocol in browsers * @param {Object|Array} [opts.hosts={ * read: [this.applicationID + '-dsn.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]), * write: [this.applicationID + '.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]) - The hosts to use for Algolia Search API. * If you provide them, you will less benefit from our HA implementation */ function AlgoliaSearchCore(applicationID, apiKey, opts) { var debug = __webpack_require__(216)('algoliasearch'); var clone = __webpack_require__(119); var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)'; if (opts._allowEmptyCredentials !== true && !applicationID) { throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage); } if (opts._allowEmptyCredentials !== true && !apiKey) { throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage); } this.applicationID = applicationID; this.apiKey = apiKey; this.hosts = { read: [], write: [] }; opts = opts || {}; var protocol = opts.protocol || 'https:'; this._timeouts = opts.timeouts || { connect: 1 * 1000, // 500ms connect is GPRS latency read: 2 * 1000, write: 30 * 1000 }; // backward compat, if opts.timeout is passed, we use it to configure all timeouts like before if (opts.timeout) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout; } // while we advocate for colon-at-the-end values: 'http:' for `opts.protocol` // we also accept `http` and `https`. It's a common error. if (!/:$/.test(protocol)) { protocol = protocol + ':'; } if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)'); } this._checkAppIdData(); if (!opts.hosts) { var defaultHosts = map(this._shuffleResult, function(hostNumber) { return applicationID + '-' + hostNumber + '.algolianet.com'; }); // no hosts given, compute defaults this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts); this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts); } else if (isArray(opts.hosts)) { // when passing custom hosts, we need to have a different host index if the number // of write/read hosts are different. this.hosts.read = clone(opts.hosts); this.hosts.write = clone(opts.hosts); } else { this.hosts.read = clone(opts.hosts.read); this.hosts.write = clone(opts.hosts.write); } // add protocol and lowercase hosts this.hosts.read = map(this.hosts.read, prepareHost(protocol)); this.hosts.write = map(this.hosts.write, prepareHost(protocol)); this.extraHeaders = []; // In some situations you might want to warm the cache this.cache = opts._cache || {}; this._ua = opts._ua; this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache; this._useFallback = opts.useFallback === undefined ? true : opts.useFallback; this._setTimeout = opts._setTimeout; debug('init done, %j', this); } /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearchCore.prototype.initIndex = function(indexName) { return new IndexCore(this, indexName); }; /** * Add an extra field to the HTTP request * * @param name the header field name * @param value the header field value */ AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) { this.extraHeaders.push({ name: name.toLowerCase(), value: value }); }; /** * Augment sent x-algolia-agent with more data, each agent part * is automatically separated from the others by a semicolon; * * @param algoliaAgent the agent to add */ AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) { if (this._ua.indexOf(';' + algoliaAgent) === -1) { this._ua += ';' + algoliaAgent; } }; /* * Wrapper that try all hosts to maximize the quality of service */ AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) { this._checkAppIdData(); var requestDebug = __webpack_require__(216)('algoliasearch:' + initialOpts.url); var body; var additionalUA = initialOpts.additionalUA || ''; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders(additionalUA, false); } else { headers = this._computeRequestHeaders(additionalUA); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); var cacheID; if (client._useCache) { cacheID = initialOpts.url; } // as we sometime use POST requests to pass parameters (like query='aa'), // the cacheID must also include the body to be different between calls if (client._useCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (client._useCache && cache && cache[cacheID] !== undefined) { requestDebug('serving response from cache'); return client._promise.resolve(JSON.parse(cache[cacheID])); } // if we reached max tries if (tries >= client.hosts[initialOpts.hostType].length) { if (!hasFallback || usingFallback) { requestDebug('could not get any response'); // then stop return client._promise.reject(new errors.AlgoliaSearchError( 'Cannot connect to the AlgoliaSearch API.' + ' Send an email to support@algolia.com to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders(additionalUA); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); client._setHostIndexByType(0, initialOpts.hostType); usingFallback = true; // the current request is now using fallback return doRequest(client._request.fallback, reqOpts); } var currentHost = client._getHostByType(initialOpts.hostType); var url = currentHost + reqOpts.url; var options = { body: reqOpts.body, jsonBody: reqOpts.jsonBody, method: reqOpts.method, headers: headers, timeouts: reqOpts.timeouts, debug: requestDebug }; requestDebug('method: %s, url: %s, headers: %j, timeouts: %d', options.method, url, options.headers, options.timeouts); if (requester === client._request.fallback) { requestDebug('using fallback'); } // `requester` is any of this._request or this._request.fallback // thus it needs to be called using the client as context return requester.call(client, url, options).then(success, tryFallback); function success(httpResponse) { // compute the status of the response, // // When in browser mode, using XDR or JSONP, we have no statusCode available // So we rely on our API response `status` property. // But `waitTask` can set a `status` property which is not the statusCode (it's the task status) // So we check if there's a `message` along `status` and it means it's an error // // That's the only case where we have a response.status that's not the http statusCode var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status || // this is important to check the request statusCode AFTER the body eventual // statusCode because some implementations (jQuery XDomainRequest transport) may // send statusCode 200 while we had an error httpResponse.statusCode || // When in browser mode, using XDR or JSONP // we default to success when no error (no response.status && response.message) // If there was a JSON.parse() error then body is null and it fails httpResponse && httpResponse.body && 200; requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j', httpResponse.statusCode, status, httpResponse.headers); var httpResponseOk = Math.floor(status / 100) === 2; var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime, statusCode: status }); if (httpResponseOk) { if (client._useCache && cache) { cache[cacheID] = httpResponse.responseText; } return httpResponse.body; } var shouldRetry = Math.floor(status / 100) !== 4; if (shouldRetry) { tries += 1; return retryRequest(); } requestDebug('unrecoverable error'); // no success and no retry => fail var unrecoverableError = new errors.AlgoliaSearchError( httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status} ); return client._promise.reject(unrecoverableError); } function tryFallback(err) { // error cases: // While not in fallback mode: // - CORS not supported // - network error // While in fallback mode: // - timeout // - network error // - badly formatted JSONP (script loaded, did not call our callback) // In both cases: // - uncaught exception occurs (TypeError) requestDebug('error: %s, stack: %s', err.message, err.stack); var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime }); if (!(err instanceof errors.AlgoliaSearchError)) { err = new errors.Unknown(err && err.message, err); } tries += 1; // stop the request implementation when: if ( // we did not generate this error, // it comes from a throw in some other piece of code err instanceof errors.Unknown || // server sent unparsable JSON err instanceof errors.UnparsableJSON || // max tries and already using fallback or no fallback tries >= client.hosts[initialOpts.hostType].length && (usingFallback || !hasFallback)) { // stop request implementation for this command err.debugData = debugData; return client._promise.reject(err); } // When a timeout occured, retry by raising timeout if (err instanceof errors.RequestTimeout) { return retryRequestWithHigherTimeout(); } return retryRequest(); } function retryRequest() { requestDebug('retrying request'); client._incrementHostIndex(initialOpts.hostType); return doRequest(requester, reqOpts); } function retryRequestWithHigherTimeout() { requestDebug('retrying request with higher timeout'); client._incrementHostIndex(initialOpts.hostType); client._incrementTimeoutMultipler(); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); return doRequest(requester, reqOpts); } } var promise = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType) } ); // either we have a callback // either we are using promises if (initialOpts.callback) { promise.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, content); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { return promise; } }; /* * Transform search param object in query string * @param {object} args arguments to add to the current query string * @param {string} params current query string * @return {string} the final query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) { var forEach = __webpack_require__(110); var ua = additionalUA ? this._ua + ';' + additionalUA : this._ua; var requestHeaders = { 'x-algolia-agent': ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (withAPIKey !== false) { requestHeaders['x-algolia-api-key'] = this.apiKey; } if (this.userToken) { requestHeaders['x-algolia-usertoken'] = this.userToken; } if (this.securityTags) { requestHeaders['x-algolia-tagfilters'] = this.securityTags; } if (this.extraHeaders) { forEach(this.extraHeaders, function addToRequestHeaders(header) { requestHeaders[header.name] = header.value; }); } return requestHeaders; }; /** * Search through multiple indices at the same time * @param {Object[]} queries An array of queries you want to run. * @param {string} queries[].indexName The index name you want to target * @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params` * @param {Object} queries[].params Any search param like hitsPerPage, .. * @param {Function} callback Callback to be called * @return {Promise|undefined} Returns a promise if no callback given */ AlgoliaSearchCore.prototype.search = function(queries, opts, callback) { var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: client.search(arrayOfQueries[, callback])'; if (!isArray(queries)) { throw new Error(usage); } if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } var client = this; var postObj = { requests: map(queries, function prepareRequest(query) { var params = ''; // allow query.query // so we are mimicing the index.search(query, params) method // {indexName:, query:, params:} if (query.query !== undefined) { params += 'query=' + encodeURIComponent(query.query); } return { indexName: query.indexName, params: client._getSearchParams(query.params, params) }; }) }; var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) { return requestId + '=' + encodeURIComponent( '/1/indexes/' + encodeURIComponent(request.indexName) + '?' + request.params ); }).join('&'); var url = '/1/indexes/*/queries'; if (opts.strategy !== undefined) { url += '?strategy=' + opts.strategy; } return this._jsonRequest({ cache: this.cache, method: 'POST', url: url, body: postObj, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/*', body: { params: JSONPParams } }, callback: callback }); }; /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ AlgoliaSearchCore.prototype.setSecurityTags = function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.securityTags = tags; }; /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ AlgoliaSearchCore.prototype.setUserToken = function(userToken) { this.userToken = userToken; }; /** * Clear all queries in client's cache * @return undefined */ AlgoliaSearchCore.prototype.clearCache = function() { this.cache = {}; }; /** * Set the number of milliseconds a request can take before automatically being terminated. * @deprecated * @param {Number} milliseconds */ AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) { if (milliseconds) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds; } }; /** * Set the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) { this._timeouts = timeouts; }; /** * Get the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.getTimeouts = function() { return this._timeouts; }; AlgoliaSearchCore.prototype._getAppIdData = function() { var data = store.get(this.applicationID); if (data !== null) this._cacheAppIdData(data); return data; }; AlgoliaSearchCore.prototype._setAppIdData = function(data) { data.lastChange = (new Date()).getTime(); this._cacheAppIdData(data); return store.set(this.applicationID, data); }; AlgoliaSearchCore.prototype._checkAppIdData = function() { var data = this._getAppIdData(); var now = (new Date()).getTime(); if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) { return this._resetInitialAppIdData(data); } return data; }; AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) { var newData = data || {}; newData.hostIndexes = {read: 0, write: 0}; newData.timeoutMultiplier = 1; newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]); return this._setAppIdData(newData); }; AlgoliaSearchCore.prototype._cacheAppIdData = function(data) { this._hostIndexes = data.hostIndexes; this._timeoutMultiplier = data.timeoutMultiplier; this._shuffleResult = data.shuffleResult; }; AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) { var foreach = __webpack_require__(110); var currentData = this._getAppIdData(); foreach(newData, function(value, key) { currentData[key] = value; }); return this._setAppIdData(currentData); }; AlgoliaSearchCore.prototype._getHostByType = function(hostType) { return this.hosts[hostType][this._getHostIndexByType(hostType)]; }; AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() { return this._timeoutMultiplier; }; AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) { return this._hostIndexes[hostType]; }; AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) { var clone = __webpack_require__(119); var newHostIndexes = clone(this._hostIndexes); newHostIndexes[hostType] = hostIndex; this._partialAppIdDataUpdate({hostIndexes: newHostIndexes}); return hostIndex; }; AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) { return this._setHostIndexByType( (this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType ); }; AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() { var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4); return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier}); }; AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) { return { connect: this._timeouts.connect * this._timeoutMultiplier, complete: this._timeouts[hostType] * this._timeoutMultiplier }; }; function prepareHost(protocol) { return function prepare(host) { return protocol + '//' + host.toLowerCase(); }; } // Prototype.js < 1.7, a widely used library, defines a weird // Array.prototype.toJSON function that will fail to stringify our content // appropriately // refs: // - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q // - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c // - http://stackoverflow.com/a/3148441/147079 function safeJSONStringify(obj) { /* eslint no-extend-native:0 */ if (Array.prototype.toJSON === undefined) { return JSON.stringify(obj); } var toJSON = Array.prototype.toJSON; delete Array.prototype.toJSON; var out = JSON.stringify(obj); Array.prototype.toJSON = toJSON; return out; } function shuffle(array) { var currentIndex = array.length; var temporaryValue; var randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function removeCredentials(headers) { var newHeaders = {}; for (var headerName in headers) { if (Object.prototype.hasOwnProperty.call(headers, headerName)) { var value; if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') { value = '**hidden for security purposes**'; } else { value = headers[headerName]; } newHeaders[headerName] = value; } } return newHeaders; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109))) /***/ }), /* 405 */ /***/ (function(module, exports, __webpack_require__) { var buildSearchMethod = __webpack_require__(348); var deprecate = __webpack_require__(410); var deprecatedMessage = __webpack_require__(411); module.exports = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the full text query * @param {object} [args] (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param {function} [callback] the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the similar query * @param {object} [args] (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery'); /* * Browse index content. The response content will have a `cursor` property that you can use * to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browse('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }, callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browse = function(query, queryParameters, callback) { var merge = __webpack_require__(413); var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse', body: {params: params}, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse', body: {cursor: cursor}, hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone = __webpack_require__(119); var omit = __webpack_require__(414); var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])'; if (params.facetName === undefined || params.facetQuery === undefined) { throw new Error(usage); } var facetName = params.facetName; var filteredParams = omit(clone(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback, additionalUA) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback, additionalUA: additionalUA }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occured */ IndexCore.prototype.getObject = function(objectID, attrs, callback) { var indexObj = this; if (arguments.length === 1 || typeof attrs === 'function') { callback = attrs; attrs = undefined; } var params = ''; if (attrs !== undefined) { params = '?attributes='; for (var i = 0; i < attrs.length; ++i) { if (i !== 0) { params += ','; } params += attrs[i]; } } return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, hostType: 'read', callback: callback }); }; /* * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve */ IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) { var isArray = __webpack_require__(249); var map = __webpack_require__(248); var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; if (arguments.length === 1 || typeof attributesToRetrieve === 'function') { callback = attributesToRetrieve; attributesToRetrieve = undefined; } var body = { requests: map(objectIDs, function prepareRequest(objectID) { var request = { indexName: indexObj.indexName, objectID: objectID }; if (attributesToRetrieve) { request.attributesToRetrieve = attributesToRetrieve.join(','); } return request; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/*/objects', hostType: 'read', body: body, callback: callback }); }; IndexCore.prototype.as = null; IndexCore.prototype.indexName = null; IndexCore.prototype.typeAheadArgs = null; IndexCore.prototype.typeAheadValueOption = null; /***/ }), /* 406 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(421); var Promise = global.Promise || __webpack_require__(420).Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = __webpack_require__(349); var errors = __webpack_require__(215); var inlineHeaders = __webpack_require__(408); var jsonpRequest = __webpack_require__(409); var places = __webpack_require__(415); uaSuffix = uaSuffix || ''; if (false) { require('debug').enable('algoliasearch*'); } function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = __webpack_require__(119); var getDocumentProtocol = __webpack_require__(407); opts = cloneDeep(opts || {}); if (opts.protocol === undefined) { opts.protocol = getDocumentProtocol(); } opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = __webpack_require__(417); algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version; algoliasearch.initPlaces = places(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia global.__algolia = { debug: __webpack_require__(216), algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in global, hasXDomainRequest: 'XDomainRequest' in global }; if (support.hasXMLHttpRequest) { support.cors = 'withCredentials' in new XMLHttpRequest(); } function AlgoliaSearchBrowser() { // call AlgoliaSearch constructor AlgoliaSearch.apply(this, arguments); } inherits(AlgoliaSearchBrowser, AlgoliaSearch); AlgoliaSearchBrowser.prototype._request = function request(url, opts) { return new Promise(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors.Network('CORS not supported')); return; } url = inlineHeaders(url, opts.headers); var body = opts.body; var req = support.cors ? new XMLHttpRequest() : new XDomainRequest(); var reqTimeout; var timedOut; var connected = false; reqTimeout = setTimeout(onTimeout, opts.timeouts.connect); // we set an empty onprogress listener // so that XDomainRequest on IE9 is not aborted // refs: // - https://github.com/algolia/algoliasearch-client-js/issues/76 // - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment req.onprogress = onProgress; if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange; req.onload = onLoad; req.onerror = onError; // do not rely on default XHR async flag, as some analytics code like hotjar // breaks it and set it to false by default if (req instanceof XMLHttpRequest) { req.open(opts.method, url, true); } else { req.open(opts.method, url); } // headers are meant to be sent after open if (support.cors) { if (body) { if (opts.method === 'POST') { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests req.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); } else { req.setRequestHeader('content-type', 'application/json'); } } req.setRequestHeader('accept', 'application/json'); } req.send(body); // event object not received in IE8, at least // but we do not use it, still important to note function onLoad(/* event */) { // When browser does not supports req.timeout, we can // have both a load and timeout event, since handled by a dumb setTimeout if (timedOut) { return; } clearTimeout(reqTimeout); var out; try { out = { body: JSON.parse(req.responseText), responseText: req.responseText, statusCode: req.status, // XDomainRequest does not have any response headers headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {} }; } catch (e) { out = new errors.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors.UnparsableJSON) { reject(out); } else { resolve(out); } } function onError(event) { if (timedOut) { return; } clearTimeout(reqTimeout); // error event is trigerred both with XDR/XHR on: // - DNS error // - unallowed cross domain request reject( new errors.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors.RequestTimeout()); } function onConnect() { connected = true; clearTimeout(reqTimeout); reqTimeout = setTimeout(onTimeout, opts.timeouts.complete); } function onProgress() { if (!connected) onConnect(); } function onReadyStateChange() { if (!connected && req.readyState > 1) onConnect(); } }); }; AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) { url = inlineHeaders(url, opts.headers); return new Promise(function wrapJsonpRequest(resolve, reject) { jsonpRequest(url, opts, function jsonpRequestDone(err, content) { if (err) { reject(err); return; } resolve(content); }); }); }; AlgoliaSearchBrowser.prototype._promise = { reject: function rejectPromise(val) { return Promise.reject(val); }, resolve: function resolvePromise(val) { return Promise.resolve(val); }, delay: function delayPromise(ms) { return new Promise(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); } }; return algoliasearch; }; /***/ }), /* 407 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = getDocumentProtocol; function getDocumentProtocol() { var protocol = window.document.location.protocol; // when in `file:` mode (local html file), default to `http:` if (protocol !== 'http:' && protocol !== 'https:') { protocol = 'http:'; } return protocol; } /***/ }), /* 408 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = inlineHeaders; var encode = __webpack_require__(428); function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode(headers); } /***/ }), /* 409 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = jsonpRequest; var errors = __webpack_require__(215); var JSONPCounter = 0; function jsonpRequest(url, opts, cb) { if (opts.method !== 'GET') { cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.')); return; } opts.debug('JSONP: start'); var cbCalled = false; var timedOut = false; JSONPCounter += 1; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); var cbName = 'algoliaJSONP_' + JSONPCounter; var done = false; window[cbName] = function(data) { removeGlobals(); if (timedOut) { opts.debug('JSONP: Late answer, ignoring'); return; } cbCalled = true; clean(); cb(null, { body: data/* , // We do not send the statusCode, there's no statusCode in JSONP, it will be // computed using data.status && data.message like with XDR statusCode*/ }); }; // add callback by hand url += '&callback=' + cbName; // add body params manually if (opts.jsonBody && opts.jsonBody.params) { url += '&' + opts.jsonBody.params; } var ontimeout = setTimeout(timeout, opts.timeouts.complete); // script onreadystatechange needed only for // <= IE8 // https://github.com/angular/angular.js/issues/4523 script.onreadystatechange = readystatechange; script.onload = success; script.onerror = error; script.async = true; script.defer = true; script.src = url; head.appendChild(script); function success() { opts.debug('JSONP: success'); if (done || timedOut) { return; } done = true; // script loaded but did not call the fn => script loading error if (!cbCalled) { opts.debug('JSONP: Fail. Script loaded but did not call the callback'); clean(); cb(new errors.JSONPScriptFail()); } } function readystatechange() { if (this.readyState === 'loaded' || this.readyState === 'complete') { success(); } } function clean() { clearTimeout(ontimeout); script.onload = null; script.onreadystatechange = null; script.onerror = null; head.removeChild(script); } function removeGlobals() { try { delete window[cbName]; delete window[cbName + '_loaded']; } catch (e) { window[cbName] = window[cbName + '_loaded'] = undefined; } } function timeout() { opts.debug('JSONP: Script timeout'); timedOut = true; clean(); cb(new errors.RequestTimeout()); } function error() { opts.debug('JSONP: Script error'); if (done || timedOut) { return; } clean(); cb(new errors.JSONPScriptError()); } } /***/ }), /* 410 */ /***/ (function(module, exports) { module.exports = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.log(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; /***/ }), /* 411 */ /***/ (function(module, exports) { module.exports = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace('.', '') .replace('()', ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink; }; /***/ }), /* 412 */ /***/ (function(module, exports) { // Parse cloud does not supports setTimeout // We do not store a setTimeout reference in the client everytime // We only fallback to a fake setTimeout when not available // setTimeout cannot be override globally sadly module.exports = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; /***/ }), /* 413 */ /***/ (function(module, exports, __webpack_require__) { var foreach = __webpack_require__(110); module.exports = function merge(destination/* , sources */) { var sources = Array.prototype.slice.call(arguments); foreach(sources, function(source) { for (var keyName in source) { if (source.hasOwnProperty(keyName)) { if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') { destination[keyName] = merge({}, destination[keyName], source[keyName]); } else if (source[keyName] !== undefined) { destination[keyName] = source[keyName]; } } } }); return destination; }; /***/ }), /* 414 */ /***/ (function(module, exports, __webpack_require__) { module.exports = function omit(obj, test) { var keys = __webpack_require__(426); var foreach = __webpack_require__(110); var filtered = {}; foreach(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; /***/ }), /* 415 */ /***/ (function(module, exports, __webpack_require__) { module.exports = createPlacesClient; var buildSearchMethod = __webpack_require__(348); function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = __webpack_require__(119); opts = opts && cloneDeep(opts) || {}; opts.hosts = opts.hosts || [ 'places-dsn.algolia.net', 'places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com' ]; // allow initPlaces() no arguments => community rate limited if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) { appID = ''; apiKey = ''; opts._allowEmptyCredentials = true; } var client = algoliasearch(appID, apiKey, opts); var index = client.initIndex('places'); index.search = buildSearchMethod('query', '/1/places/query'); return index; }; } /***/ }), /* 416 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var debug = __webpack_require__(216)('algoliasearch:src/hostIndexState.js'); var localStorageNamespace = 'algoliasearch-client-js'; var store; var moduleStore = { state: {}, set: function(key, data) { this.state[key] = data; return this.state[key]; }, get: function(key) { return this.state[key] || null; } }; var localStorageStore = { set: function(key, data) { moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure try { var namespace = JSON.parse(global.localStorage[localStorageNamespace]); namespace[key] = data; global.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(global.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; module.exports = { get: getOrSet, set: getOrSet, supportsLocalStorage: supportsLocalStorage }; function getOrSet(key, data) { if (arguments.length === 1) { return store.get(key); } return store.set(key, data); } function supportsLocalStorage() { try { if ('localStorage' in global && global.localStorage !== null) { if (!global.localStorage[localStorageNamespace]) { // actual creation of the namespace global.localStorage.setItem(localStorageNamespace, JSON.stringify({})); } return true; } return false; } catch (_) { return false; } } // In case of any error on localStorage, we clean our own namespace, this should handle // quota errors when a lot of keys + data are used function cleanup() { try { global.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 417 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = '3.21.1'; /***/ }), /* 418 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__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__)); } else { window.classNames = classNames; } }()); /***/ }), /* 419 */ /***/ (function(module, exports, __webpack_require__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug.debug = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(425); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }), /* 420 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 4.0.5 */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ES6Promise = factory()); }(this, (function () { 'use strict'; function objectOrFunction(x) { return typeof x === 'function' || typeof x === 'object' && x !== null; } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } 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; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = require; var vertx = __webpack_require__(430); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); _resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then) { asap(function (promise) { var sealed = false; var error = tryThen(then, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { _resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; _reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; _reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { _reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return _resolve(promise, value); }, function (reason) { return _reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$) { if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { handleOwnThenable(promise, maybeThenable); } else { if (then$$ === GET_THEN_ERROR) { _reject(promise, GET_THEN_ERROR.error); } else if (then$$ === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$)) { handleForeignThenable(promise, maybeThenable, then$$); } else { fulfill(promise, maybeThenable); } } } function _resolve(promise, value) { if (promise === value) { _reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function _reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { _reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { _resolve(promise, value); } else if (failed) { _reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { _reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { _resolve(promise, value); }, function rejectPromise(reason) { _reject(promise, reason); }); } catch (e) { _reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { _reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); }; Enumerator.prototype._enumerate = function () { var length = this.length; var _input = this._input; for (var i = 0; this._state === PENDING && i < length; i++) { this._eachEntry(_input[i], i); } }; Enumerator.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$ = c.resolve; if (resolve$$ === resolve) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$) { return resolve$$(entry); }), i); } } else { this._willSettleAt(resolve$$(entry), i); } }; Enumerator.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { _reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); _reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } Promise.all = all; Promise.race = race; Promise.resolve = resolve; Promise.reject = reject; Promise._setScheduler = setScheduler; Promise._setAsap = setAsap; Promise._asap = asap; Promise.prototype = { constructor: Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: then, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function _catch(onRejection) { return this.then(null, onRejection); } }; function polyfill() { var local = undefined; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise; } // Strange compat.. Promise.polyfill = polyfill; Promise.Promise = Promise; return Promise; }))); //# sourceMappingURL=es6-promise.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(109), __webpack_require__(54))) /***/ }), /* 421 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }), /* 422 */ /***/ (function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeMax = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } module.exports = baseRange; /***/ }), /* 423 */ /***/ (function(module, exports, __webpack_require__) { var baseRange = __webpack_require__(422), isIterateeCall = __webpack_require__(217), toFinite = __webpack_require__(219); /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } module.exports = createRange; /***/ }), /* 424 */ /***/ (function(module, exports, __webpack_require__) { var createRange = __webpack_require__(423); /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); module.exports = range; /***/ }), /* 425 */ /***/ (function(module, exports) { /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } /***/ }), /* 426 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = __webpack_require__(427); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /* 427 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /* 428 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; /***/ }), /* 429 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_429__; /***/ }), /* 430 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 431 */, /* 432 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Panel = exports.Toggle = exports.Stats = exports.SortBy = exports.SearchBox = exports.ScrollTo = exports.ClearAll = exports.RefinementList = exports.StarRating = exports.RangeSlider = exports.RangeInput = exports.PoweredBy = exports.Pagination = exports.MultiRange = exports.Menu = exports.InfiniteHits = exports.HitsPerPage = exports.Hits = exports.Snippet = exports.Highlight = exports.HierarchicalMenu = exports.CurrentRefinements = exports.Configure = exports.Index = exports.InstantSearch = undefined; var _Configure = __webpack_require__(354); Object.defineProperty(exports, 'Configure', { enumerable: true, get: function get() { return _interopRequireDefault(_Configure).default; } }); var _CurrentRefinements = __webpack_require__(355); Object.defineProperty(exports, 'CurrentRefinements', { enumerable: true, get: function get() { return _interopRequireDefault(_CurrentRefinements).default; } }); var _HierarchicalMenu = __webpack_require__(356); Object.defineProperty(exports, 'HierarchicalMenu', { enumerable: true, get: function get() { return _interopRequireDefault(_HierarchicalMenu).default; } }); var _Highlight = __webpack_require__(235); Object.defineProperty(exports, 'Highlight', { enumerable: true, get: function get() { return _interopRequireDefault(_Highlight).default; } }); var _Snippet = __webpack_require__(370); Object.defineProperty(exports, 'Snippet', { enumerable: true, get: function get() { return _interopRequireDefault(_Snippet).default; } }); var _Hits = __webpack_require__(357); Object.defineProperty(exports, 'Hits', { enumerable: true, get: function get() { return _interopRequireDefault(_Hits).default; } }); var _HitsPerPage = __webpack_require__(358); Object.defineProperty(exports, 'HitsPerPage', { enumerable: true, get: function get() { return _interopRequireDefault(_HitsPerPage).default; } }); var _InfiniteHits = __webpack_require__(359); Object.defineProperty(exports, 'InfiniteHits', { enumerable: true, get: function get() { return _interopRequireDefault(_InfiniteHits).default; } }); var _Menu = __webpack_require__(360); Object.defineProperty(exports, 'Menu', { enumerable: true, get: function get() { return _interopRequireDefault(_Menu).default; } }); var _MultiRange = __webpack_require__(361); Object.defineProperty(exports, 'MultiRange', { enumerable: true, get: function get() { return _interopRequireDefault(_MultiRange).default; } }); var _Pagination = __webpack_require__(362); Object.defineProperty(exports, 'Pagination', { enumerable: true, get: function get() { return _interopRequireDefault(_Pagination).default; } }); var _PoweredBy = __webpack_require__(364); Object.defineProperty(exports, 'PoweredBy', { enumerable: true, get: function get() { return _interopRequireDefault(_PoweredBy).default; } }); var _RangeInput = __webpack_require__(365); Object.defineProperty(exports, 'RangeInput', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeInput).default; } }); var _RangeSlider = __webpack_require__(366); Object.defineProperty(exports, 'RangeSlider', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeSlider).default; } }); var _StarRating = __webpack_require__(372); Object.defineProperty(exports, 'StarRating', { enumerable: true, get: function get() { return _interopRequireDefault(_StarRating).default; } }); var _RefinementList = __webpack_require__(367); Object.defineProperty(exports, 'RefinementList', { enumerable: true, get: function get() { return _interopRequireDefault(_RefinementList).default; } }); var _ClearAll = __webpack_require__(353); Object.defineProperty(exports, 'ClearAll', { enumerable: true, get: function get() { return _interopRequireDefault(_ClearAll).default; } }); var _ScrollTo = __webpack_require__(368); Object.defineProperty(exports, 'ScrollTo', { enumerable: true, get: function get() { return _interopRequireDefault(_ScrollTo).default; } }); var _SearchBox = __webpack_require__(369); Object.defineProperty(exports, 'SearchBox', { enumerable: true, get: function get() { return _interopRequireDefault(_SearchBox).default; } }); var _SortBy = __webpack_require__(371); Object.defineProperty(exports, 'SortBy', { enumerable: true, get: function get() { return _interopRequireDefault(_SortBy).default; } }); var _Stats = __webpack_require__(373); Object.defineProperty(exports, 'Stats', { enumerable: true, get: function get() { return _interopRequireDefault(_Stats).default; } }); var _Toggle = __webpack_require__(374); Object.defineProperty(exports, 'Toggle', { enumerable: true, get: function get() { return _interopRequireDefault(_Toggle).default; } }); var _Panel = __webpack_require__(363); Object.defineProperty(exports, 'Panel', { enumerable: true, get: function get() { return _interopRequireDefault(_Panel).default; } }); var _createInstantSearch = __webpack_require__(352); var _createInstantSearch2 = _interopRequireDefault(_createInstantSearch); var _createIndex = __webpack_require__(351); var _createIndex2 = _interopRequireDefault(_createIndex); var _lite = __webpack_require__(375); var _lite2 = _interopRequireDefault(_lite); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InstantSearch = (0, _createInstantSearch2.default)(_lite2.default, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); exports.InstantSearch = InstantSearch; var Index = (0, _createIndex2.default)({ Root: 'div', props: { className: 'ais-MultiIndex__root' } }); exports.Index = Index; /***/ }) /******/ ]); }); //# sourceMappingURL=Dom.js.map
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":6,"../lib/Core":8,"../lib/Document":10,"../lib/Grid":12,"../lib/Highchart":13,"../lib/OldView":30,"../lib/OldView.Bind":29,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":41}],2:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":34,"./Shared":40}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c,d){var e=this._compareFunc(this._data,a);return d=d||[],0===e&&(this._left&&this._left.lookup(a,b,c,d),d.push(this._data),this._right&&this._right.lookup(a,b,c,d)),-1===e&&this._right&&this._right.lookup(a,b,c,d),1===e&&this._left&&this._left.lookup(a,b,c,d),d},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return d=d||[],void 0===d._visitedCount&&(d._visitedCount=0),d._visitedCount++,d._visitedNodes=d._visitedNodes||[],d._visitedNodes.push(h),g=this.sortAsc(i,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":34,"./Shared":40}],4:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this.sharedPathSolver=o,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=a("./Condition"),o=new h,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" 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: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},p.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length?(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length?(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this,f||[]),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f})):d&&d.call(this,f||[])):d&&d.call(this,f||[]),h.stop(),f||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i,failed:j}),this.deferEmit("change",{type:"insert",data:i,failed:j}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),b.$groupBy&&(x.data("flag.group",!0),x.time("group"),e=this.group(b.$groupBy,e),x.time("group")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled), void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype.group=function(a,b){var c,d,e,f=o.parse(a,!0),g=new h,i={};if(f.length)for(d=0;d<f.length;d++)for(g.path(f[d].path),e=0;e<b.length;e++)c=g.get(b[e]),i[c]=i[c]||[],i[c].push(b[e]);return i},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b,c),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b,c),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},p.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},p.prototype.when=function(a){var b=this.objectId();return this._when=this._when||{},this._when[b]=this._when[b]||new n(this,b,a),this._when[b]},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Condition":7,"./Index2d":14,"./IndexBinaryTree":15,"./IndexHashMap":16,"./KeyValueStore":17,"./Metrics":18,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":40}],7:[function(a,b,c){"use strict";var d,e;d=a("./Shared"),e=function(){this.init.apply(this,arguments)},e.prototype.init=function(a,b,c){this._dataSource=a,this._id=b,this._query=[c],this._started=!1,this._state=[!1],this._satisfied=!1,this.earlyExit(!0)},d.addModule("Condition",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"id"),d.synthesize(e.prototype,"then"),d.synthesize(e.prototype,"else"),d.synthesize(e.prototype,"earlyExit"),d.synthesize(e.prototype,"debug"),e.prototype.and=function(a){return this._query.push(a),this._state.push(!1),this},e.prototype.start=function(a){if(!this._started){var b=this;0!==arguments.length&&(this._satisfied=a),this._updateStates(),b._onChange=function(){b._updateStates()},this._dataSource.on("change",b._onChange),this._started=!0}return this},e.prototype._updateStates=function(){var a,b=!0;for(a=0;a<this._query.length&&(this._state[a]=this._dataSource.count(this._query[a])>0,this._debug&&console.log(this.logIdentifier()+" Evaluating",this._query[a],"=",this._query[a]),this._state[a]||(b=!1,!this._earlyExit));a++);this._satisfied!==b&&(b?this._then&&this._then():this._else&&this._else(),this._satisfied=b)},e.prototype.stop=function(){return this._started&&(this._dataSource.off("change",this._onChange),delete this._onChange,this._started=!1),this},e.prototype.drop=function(){return this.stop(),delete this._dataSource.when[this._id],this},d.finishModule("Condition"),b.exports=e},{"./Shared":40}],8:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.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"},b.exports=i},{"./Db.js":9,"./Metrics.js":18,"./Overload":32,"./Shared":40}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":18,"./Overload":32,"./Shared":40}],10:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){var b=this;if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new g(a).db(this),b.emit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":5,"./Shared":40}],11:[function(a,b,c){"use strict";var d,e,f,g,h=Math.PI/180,i=180/Math.PI,j=6371;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var k=function(){};k.prototype.radians=function(a){return a*h},k.prototype.degrees=function(a){return a*i},k.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},k.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},k.prototype.calculateLatLngByDistanceBearing=function(a,b,c){var d=a[1],e=a[0],f=Math.asin(Math.sin(this.radians(e))*Math.cos(b/j)+Math.cos(this.radians(e))*Math.sin(b/j)*Math.cos(this.radians(c))),g=this.radians(d)+Math.atan2(Math.sin(this.radians(c))*Math.sin(b/j)*Math.cos(this.radians(e)),Math.cos(b/j)-Math.sin(this.radians(e))*Math.sin(f)),h=(g+3*Math.PI)%(2*Math.PI)-Math.PI;return{lat:this.degrees(f),lng:this.degrees(h)}},k.prototype.calculateExtentByRadius=function(a,b){var c,d,e,f,g=[],h=[];return e=this.calculateLatLngByDistanceBearing(a,b,0),d=this.calculateLatLngByDistanceBearing(a,b,90),f=this.calculateLatLngByDistanceBearing(a,b,180),c=this.calculateLatLngByDistanceBearing(a,b,270),g[0]=e.lat,g[1]=f.lat,h[0]=c.lng,h[1]=d.lng,{lat:g,lng:h}},k.prototype.calculateHashArrayByRadius=function(a,b,c){var d,e,f,g=this.calculateExtentByRadius(a,b),h=[g.lat[0],g.lng[0]],i=[g.lat[0],g.lng[1]],j=[g.lat[1],g.lng[0]],k=this.encode(h[0],h[1],c),l=this.encode(i[0],i[1],c),m=this.encode(j[0],j[1],c),n=0,o=0,p=[];for(d=k,p.push(d);d!==l;)d=this.calculateAdjacent(d,"right"),n++,p.push(d);for(d=k;d!==m;)d=this.calculateAdjacent(d,"bottom"),o++;for(e=0;n>=e;e++)for(d=p[e],f=0;o>f;f++)d=this.calculateAdjacent(d,"bottom"),p.push(d);return p},k.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},k.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{lat:l,lng:m}},k.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},"undefined"!=typeof b&&(b.exports=k)},{}],12:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._baseQuery={},this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),"function"==typeof this._from.query&&(this._baseQuery=this._from.query()),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()), this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.query=function(a,b){return this._baseQuery=a,this._baseQueryOptions=b,this},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d=a.decouple(a._baseQuery);b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j,k=e.attr("data-grid-filter"),l=e.attr("data-grid-vartype"),m={},n=e.html(),o=a._db.view("tmpGridFilter_"+a._id+"_"+k);m[k]=1,j={$distinct:m},o.query(j).orderBy(m).from(a._from._from),i=function(){o.refresh()},a._from._from.on("change",i),a.on("drop",function(){a._from&&a._from._from&&a._from._from.off("change",i),o.drop()}),h=['<div class="dropdown" id="'+a._id+"_"+k+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+k+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',n+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+k+'_dropdownMenu"></ul>'),f.append(g),e.html(f),o.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked>&nbsp;All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+k+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox">&nbsp;{^{:'+k+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+k+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=o.query(),d=b.val();d?c[k]=new RegExp(d,"gi"):delete c[k],o.query(c)}),b.on("click","#"+a._id+"_"+k+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=o.query();delete b[k],o.query(b)}),b.on("click","#"+a._id+"_"+k+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),j=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(j.prop("checked",j.prop("checked")),e=j.is(":checked")):(j.prop("checked",!j.prop("checked")),e=j.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[k],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),l){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[k]=d[k]||{$in:[]},f=d[k].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[k]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":38,"./Shared":40,"./View":41}],13:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":32,"./Shared":40}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b,c){var d,e,f,g,i=this._btree.keys();for(g=0;g<i.length;g++)if(d=i[g].path,e=h.get(a,d),"object"==typeof e)return e.$near&&(f=[],f=f.concat(this.near(d,e.$near,b,c))),e.$geoWithin&&(f=[],f=f.concat(this.geoWithin(d,e.$geoWithin,b,c))),f;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c,d){var e,f,g,k,l,m,n,o,p,q,r,s,t=this,u=[],v=this._collection.primaryKey();if("km"===b.$distanceUnits){for(o=b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}}else if("miles"===b.$distanceUnits)for(o=1.60934*b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}for(0===n&&(n=1),d&&d.time("index2d.calculateHashArea"),e=i.calculateHashArrayByRadius(b.$point,o,n),d&&d.time("index2d.calculateHashArea"),d&&(d.data("index2d.near.precision",n),d.data("index2d.near.hashArea",e),d.data("index2d.near.maxDistanceKm",o),d.data("index2d.near.centerPointCoords",[b.$point[0],b.$point[1]])),m=[],f=0,k={},g=[],d&&d.time("index2d.near.getDocsInsideHashArea"),s=0;s<e.length;s++)l=this._btree.startsWith(a,e[s]),k[e[s]]=l,f+=l._visitedCount,g=g.concat(l._visitedNodes),m=m.concat(l);if(d&&(d.time("index2d.near.getDocsInsideHashArea"),d.data("index2d.near.startsWith",k),d.data("index2d.near.visitedTreeNodes",g)),d&&d.time("index2d.near.lookupDocsById"),m=this._collection._primaryIndex.lookup(m),d&&d.time("index2d.near.lookupDocsById"),b.$distanceField&&(m=this.decouple(m)),m.length){for(p={},d&&d.time("index2d.near.calculateDistanceFromCenter"),s=0;s<m.length;s++)r=h.get(m[s],a),q=p[m[s][v]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],r[0],r[1]),o>=q&&(b.$distanceField&&h.set(m[s],b.$distanceField,"km"===b.$distanceUnits?q:Math.round(.621371*q)),b.$geoHashField&&h.set(m[s],b.$geoHashField,i.encode(r[0],r[1],n)),u.push(m[s]));d&&d.time("index2d.near.calculateDistanceFromCenter"),d&&d.time("index2d.near.sortResultsByDistance"),u.sort(function(a,b){return t.sortAsc(p[a[v]],p[b[v]])}),d&&d.time("index2d.near.sortResultsByDistance")}return u},k.prototype.geoWithin=function(a,b,c){return console.log("geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array."),[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./GeoHash":11,"./Path":34,"./Shared":40}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b,c){return this._btree.lookup(a,b,c)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":34,"./Shared":40}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":34,"./Shared":40}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(void 0!==a[e]&&null!==a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":40}],18:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":31,"./Shared":40}],19:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainEnabled:function(a){return void 0!==a?(this._chainDisabled=!a,this):!this._chainDisabled},chainWillSend:function(){return Boolean(this._chain&&!this._chainDisabled)},chainSend:function(a,b,c){if(this._chain&&!this._chainDisabled){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":32,"./Serialiser":39}],22:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=!1,e=function(){d||(c.off(a,e),b.apply(c,arguments),d=!0)};return this.on(a,e)},"string, *, function":function(a,b,c){ var d=this,e=!1,f=function(){e||(d.off(a,b,f),c.apply(d,arguments),e=!0)};return this.on(a,b,f)}}),off:new d({string:function(a){var b=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){b.off(a)})):this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d,e=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){e.off(a,b)})):"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){var d=this;if(this._emitting)this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){d.off(a,b,c)});else if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var e=this._listeners[a][b],f=e.indexOf(c);f>-1&&e.splice(f,1)}},"string, *":function(a,b){var c=this;this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){c.off(a,b)})):this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},this._emitting=!0,a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this._emitting=!1,this._processRemovalQueue(),this},_processRemovalQueue:function(){var a;if(this._eventRemovalQueue&&this._eventRemovalQueue.length){for(a=0;a<this._eventRemovalQueue.length;a++)this._eventRemovalQueue[a]();this._eventRemovalQueue=[]}},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":32}],24:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],27:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f.triggerStack={},f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b["export"],e=b["import"],d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g["export"],c=g["import"],b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":32}],28:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],29:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":40}],30:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],delete this._listeners,!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?(void 0!==c&&c!==!0||this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,void 0!==b&&b!==!0||this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,void 0!==b&&b!==!0||this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./Shared":40}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":34,"./Shared":40}],32:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],33:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh(); }},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.emit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":5,"./Document":10,"./Shared":40}],34:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":40}],35:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){b?c(b):o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,f,g){a&&a(b,e,g,{tableData:d,metaData:f,tableDataName:c._db._name+"-"+c._name,metaDataName:c._db._name+"-"+c._name+"-metaData"})})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):b.remove({},function(){d=d||[],b.insert(d,function(){b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)})})})}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,async:43,localforage:81}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":40,pako:83}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":40,"crypto-js":52}],38:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":40}],39:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],40:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.812",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":19,"./Mixin.ChainReactor":20,"./Mixin.Common":21,"./Mixin.Constants":22,"./Mixin.Events":23,"./Mixin.Matching":24,"./Mixin.Sorting":25,"./Mixin.Tags":26,"./Mixin.Triggers":27,"./Mixin.Updating":28,"./Overload":32}],41:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return"setData"!==g&&"insert"!==g&&"update"!==g&&"remove"!==g?!1:(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,c||d||e?(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),f.dataArr.length||f.removeArr.length?(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0):!0):!1)},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(a,b,c,d){var e={$and:[this.query(),a]};this._from.update.call(this._from,e,b,c,d)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.addTrigger=function(){return this._data.addTrigger.apply(this._data,arguments)},o.prototype.removeTrigger=function(){return this._data.removeTrigger.apply(this._data,arguments)},o.prototype.ignoreTriggers=function(){return this._data.ignoreTriggers.apply(this._data,arguments)},o.prototype.addLinkIO=function(){return this._data.addLinkIO.apply(this._data,arguments)},o.prototype.removeLinkIO=function(){return this._data.removeLinkIO.apply(this._data,arguments)},o.prototype.willTrigger=function(){return this._data.willTrigger.apply(this._data,arguments)},o.prototype.processTrigger=function(){return this._data.processTrigger.apply(this._data,arguments)},o.prototype._triggerIndexOf=function(){return this._data._triggerIndexOf.apply(this._data,arguments)},o.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings},o.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh(),void 0!==e&&this.emit("queryChange",e)},o.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":function(){return this.decouple(this._querySettings.query)},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange); }return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.emit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":2,"./Collection":5,"./CollectionGroup":6,"./Overload":32,"./ReactorIO":38,"./Shared":40}],42:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:99}],43:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){for(;!j.paused&&g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){s.unshift(a)}function f(a){var b=p(s,a);b>=0&&s.splice(b,1)}function g(){j--,k(s.slice(0),function(a){a()})}"function"==typeof arguments[1]&&(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=!1,s=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(t,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](s,l))}if(!q){for(var j,k=N(a[d])?a[d]:[a[d]],s=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,q=!0,c(a,e)}else l[d]=b,K.setImmediate(g)}),t=k.slice(0,k.length-1),u=t.length;u--;){if(!(j=a[t[u]]))throw new Error("Has nonexistent dependency in "+t.join(", "));if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](s,l)):e(i)}})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c.apply(null,[null].concat(f))});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={},f=Object.prototype.hasOwnProperty;b=b||e;var g=r(function(e){var g=e.pop(),h=b.apply(null,e);f.call(c,h)?K.setImmediate(function(){g.apply(null,c[h])}):f.call(d,h)?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([r(function(a){c[h]=a;var b=d[h];delete d[h];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return g.memo=c,g.unmemoized=a,g},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:99}],44:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":46}],46:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],47:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2,l=j|k;g[h>>>2]|=l<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":46}],48:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":46}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":46,"./hmac":51,"./sha1":70}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":45,"./core":46}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":46}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":44,"./cipher-core":45,"./core":46,"./enc-base64":47,"./enc-utf16":48,"./evpkdf":49,"./format-hex":50,"./hmac":51,"./lib-typedarrays":53,"./md5":54,"./mode-cfb":55,"./mode-ctr":57,"./mode-ctr-gladman":56,"./mode-ecb":58,"./mode-ofb":59,"./pad-ansix923":60,"./pad-iso10126":61,"./pad-iso97971":62,"./pad-nopadding":63,"./pad-zeropadding":64,"./pbkdf2":65,"./rabbit":67,"./rabbit-legacy":66,"./rc4":68,"./ripemd160":69,"./sha1":70,"./sha224":71,"./sha256":72,"./sha3":73,"./sha384":74,"./sha512":75,"./tripledes":76,"./x64-core":77}],53:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)), (a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":46}],54:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":46}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":45,"./core":46}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":45,"./core":46}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":45,"./core":46}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":45,"./core":46}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":45,"./core":46}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":45,"./core":46}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":45,"./core":46}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":45,"./core":46}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":45,"./core":46}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":45,"./core":46}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":46,"./hmac":51,"./sha1":70}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":46}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":46}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":46,"./sha256":72}],72:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":46}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":46,"./x64-core":77}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":46,"./x64-core":77}],76:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122, 2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":46}],78:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=window.BlobBuilder||window.MSBlobBuilder||window.MozBlobBuilder||window.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function e(a){return new u(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function f(a){return new u(function(b,d){var f=c([""],{type:"image/png"}),g=a.transaction([x],"readwrite");g.objectStore(x).put(f,"key"),g.oncomplete=function(){var c=a.transaction([x],"readwrite"),f=c.objectStore(x).get("key");f.onerror=d,f.onsuccess=function(a){var c=a.target.result,d=URL.createObjectURL(c);e(d).then(function(a){b(!(!a||"image/png"!==a.type))},function(){b(!1)}).then(function(){URL.revokeObjectURL(d)})}}})["catch"](function(){return!1})}function g(a){return"boolean"==typeof w?u.resolve(w):f(a).then(function(a){return w=a})}function h(a){return new u(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function i(a){var b=d(atob(a.data));return c([b],{type:a.type})}function j(a){return a&&a.__local_forage_encoded_blob}function k(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new u(function(a,d){var e=v.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(a){e.result.createObjectStore(c.storeName),a.oldVersion<=1&&e.result.createObjectStore(x)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function l(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),j(a)&&(a=i(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function m(a,b){var c=this,d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;j(d)&&(d=i(d));var e=a(d,c.key,h++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function n(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new u(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,g(f.db)}).then(function(a){return!a&&b instanceof Blob?h(b):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0);var h=g.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}})["catch"](e)});return t(e,c),e}function o(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return t(d,b),d}function p(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return t(c,a),c}function q(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function r(a,b){var c=this,d=new u(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return t(d,b),d}function s(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function t(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var u="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,v=v||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(v){var w,x="local-forage-detect-blob-support",y={_driver:"asyncStorage",_initStorage:k,iterate:m,getItem:l,setItem:n,removeItem:o,clear:p,length:q,key:r,keys:s};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=y:"function"==typeof define&&define.amd?define("asyncStorage",function(){return y}):this.asyncStorage=y}}).call(window)},{promise:101}],79:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=1,g=0;e>g;g++){var h=p.key(g);if(0===h.indexOf(b)){var i=p.getItem(h);if(i&&(i=o.deserialize(i)),i=a(i,h.substring(d),f++),void 0!==i)return i}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){"QuotaExceededError"!==i.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==i.name||f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":82,promise:101}],80:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":82,promise:101}],81:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){var k=new g(function(b){if(n===l.DEFINE)a([f],b);else if(n===l.EXPORT)switch(f){case i.INDEXEDDB:b(a("./drivers/indexeddb"));break;case i.LOCALSTORAGE:b(a("./drivers/localstorage"));break;case i.WEBSQL:b(a("./drivers/websql"))}else b(q[f])});k.then(function(a){i._extend(a),c()})}else h[f]?(i._extend(h[f]),c()):(i._driverSet=g.reject(j),d(j))}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":78,"./drivers/localstorage":79,"./drivers/websql":80,promise:101}],82:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=y.BlobBuilder||y.MSBlobBuilder||y.MozBlobBuilder||y.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=k;a instanceof ArrayBuffer?(d=a,e+=m):(d=a.buffer,"[object Int8Array]"===c?e+=o:"[object Uint8Array]"===c?e+=p:"[object Uint8ClampedArray]"===c?e+=q:"[object Int16Array]"===c?e+=r:"[object Uint16Array]"===c?e+=t:"[object Int32Array]"===c?e+=s:"[object Uint32Array]"===c?e+=u:"[object Float32Array]"===c?e+=v:"[object Float64Array]"===c?e+=w:b(new Error("Failed to get type for BinaryArray"))),b(e+g(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=i+a.type+"~"+g(this.result);b(k+n+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(h){console.error("Couldn't convert value into a JSON string: ",a),b(null,h)}}function e(a){if(a.substring(0,l)!==k)return JSON.parse(a);var b,d=a.substring(x),e=a.substring(l,x);if(e===n&&j.test(d)){var g=d.match(j);b=g[1],d=d.substring(g[0].length)}var h=f(d);switch(e){case m:return h;case n:return c([h],{type:b});case o:return new Int8Array(h);case p:return new Uint8Array(h);case q:return new Uint8ClampedArray(h);case r:return new Int16Array(h);case t:return new Uint16Array(h);case s:return new Int32Array(h);case u:return new Uint32Array(h);case v:return new Float32Array(h);case w:return new Float64Array(h);default:throw new Error("Unkown type: "+e)}}function f(a){var b,c,d,e,f,g=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var k=new ArrayBuffer(g),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=h.indexOf(a[b]),d=h.indexOf(a[b+1]),e=h.indexOf(a[b+2]),f=h.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function g(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=h[c[b]>>2],d+=h[(3&c[b])<<4|c[b+1]>>4],d+=h[(15&c[b+1])<<2|c[b+2]>>6],d+=h[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="~~local_forage_type~",j=/^~~local_forage_type~([^~]+)~/,k="__lfsc__:",l=k.length,m="arbf",n="blob",o="si08",p="ui08",q="uic8",r="si16",s="si32",t="ur16",u="ui32",v="fl32",w="fl64",x=l+m.length,y=this,z={serialize:d,deserialize:e,stringToBuffer:f,bufferToString:g};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=z:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return z}):this.localforageSerializer=z}).call(window)},{}],83:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":84,"./lib/inflate":85,"./lib/utils/common":86,"./lib/zlib/constants":89}],84:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);b.header&&h.deflateSetHeader(this.strm,b.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d===r?(this.onEnd(p),e.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":86,"./utils/strings":87,"./zlib/deflate":91,"./zlib/messages":96,"./zlib/zstream":98}],85:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options; b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l=this.strm,m=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?l.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new h.Buf8(m),l.next_out=0,l.avail_out=m),c=g.inflate(l,j.Z_NO_FLUSH),c===j.Z_BUF_ERROR&&o===!0&&(c=j.Z_OK,o=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0!==l.avail_out&&c!==j.Z_STREAM_END&&(0!==l.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(l.output,l.next_out),f=l.next_out-e,k=i.buf2string(l.output,e),l.next_out=f,l.avail_out=m-f,f&&h.arraySet(l.output,l.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(l.output,l.next_out)))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d===j.Z_SYNC_FLUSH?(this.onEnd(j.Z_OK),l.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":86,"./utils/strings":87,"./zlib/constants":89,"./zlib/gzheader":92,"./zlib/inflate":94,"./zlib/messages":96,"./zlib/zstream":98}],86:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],87:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":86}],88:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],89:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],90:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],91:[function(a,b,c){"use strict";function d(a,b){return a.msg=H[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(D.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){E._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,D.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=F(a.adler,b,e,c):2===a.state.wrap&&(a.adler=G(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ka?a.strstart-(a.w_size-ka):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ja,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ja-(m-f),f=m-ja,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ka)){D.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ia)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ia-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ia)););}while(a.lookahead<ka&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===I)return ta;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ta;if(a.strstart-a.block_start>=a.w_size-ka&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ta:ta}function o(a,b){for(var c,d;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c)),a.match_length>=ia)if(d=E._tr_tally(a,a.strstart-a.match_start,a.match_length-ia),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ia){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function p(a,b){for(var c,d,e;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ia-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===T||a.match_length===ia&&a.strstart-a.match_start>4096)&&(a.match_length=ia-1)),a.prev_length>=ia&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ia,d=E._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ia),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ia-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ta}else if(a.match_available){if(d=E._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ta}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=E._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ja){if(m(a),a.lookahead<=ja&&b===I)return ta;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ia&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ja;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ja-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ia?(c=E._tr_tally(a,1,a.match_length-ia),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===I)return ta;break}if(a.match_length=0,c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=C[a.level].max_lazy,a.good_match=C[a.level].good_length,a.nice_match=C[a.level].nice_length,a.max_chain_length=C[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ia-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new D.Buf16(2*ga),this.dyn_dtree=new D.Buf16(2*(2*ea+1)),this.bl_tree=new D.Buf16(2*(2*fa+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new D.Buf16(ha+1),this.heap=new D.Buf16(2*da+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new D.Buf16(2*da+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Y,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?ma:ra,a.adler=2===b.wrap?0:1,b.last_flush=I,E._tr_init(b),N):d(a,P)}function w(a){var b=v(a);return b===N&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?P:(a.state.gzhead=b,N):P}function y(a,b,c,e,f,g){if(!a)return P;var h=1;if(b===S&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>$||c!==Z||8>e||e>15||0>b||b>9||0>g||g>W)return d(a,P);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ia-1)/ia),i.window=new D.Buf8(2*i.w_size),i.head=new D.Buf16(i.hash_size),i.prev=new D.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new D.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,Z,_,aa,X)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>M||0>b)return a?d(a,P):P;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===sa&&b!==L)return d(a,0===a.avail_out?R:P);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===ma)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=G(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=na):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,xa),h.status=ra);else{var m=Z+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=U||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=la),m+=31-m%31,h.status=ra,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===na)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=qa)}else h.status=qa;if(h.status===qa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=ra)):h.status=ra),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,N}else if(0===a.avail_in&&e(b)<=e(c)&&b!==L)return d(a,R);if(h.status===sa&&0!==a.avail_in)return d(a,R);if(0!==a.avail_in||0!==h.lookahead||b!==I&&h.status!==sa){var o=h.strategy===U?r(h,b):h.strategy===V?q(h,b):C[h.level].func(h,b);if(o!==va&&o!==wa||(h.status=sa),o===ta||o===va)return 0===a.avail_out&&(h.last_flush=-1),N;if(o===ua&&(b===J?E._tr_align(h):b!==M&&(E._tr_stored_block(h,0,0,!1),b===K&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,N}return b!==L?N:h.wrap<=0?O:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?N:O)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa?d(a,P):(a.state=null,b===ra?d(a,Q):N)):P}var C,D=a("../utils/common"),E=a("./trees"),F=a("./adler32"),G=a("./crc32"),H=a("./messages"),I=0,J=1,K=3,L=4,M=5,N=0,O=1,P=-2,Q=-3,R=-5,S=-1,T=1,U=2,V=3,W=4,X=0,Y=2,Z=8,$=9,_=15,aa=8,ba=29,ca=256,da=ca+1+ba,ea=30,fa=19,ga=2*da+1,ha=15,ia=3,ja=258,ka=ja+ia+1,la=32,ma=42,na=69,oa=73,pa=91,qa=103,ra=113,sa=666,ta=1,ua=2,va=3,wa=4,xa=3;C=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":86,"./adler32":88,"./crc32":90,"./messages":96,"./trees":97}],92:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],93:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],94:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a; case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":86,"./adler32":88,"./crc32":90,"./inffast":93,"./inftrees":95}],95:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":86}],96:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],97:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return 256>a?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;W>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;V>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;W>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;Q-1>d;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;16>d;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;T>d;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;W>=b;b++)g[b]=0;for(a=0;143>=a;)ga[2*a+1]=8,a++,g[8]++;for(;255>=a;)ga[2*a+1]=9,a++,g[9]++;for(;279>=a;)ga[2*a+1]=7,a++,g[7]++;for(;287>=a;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;T>a;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;S>b;b++)a.dyn_ltree[2*b]=0;for(b=0;T>b;b++)a.dyn_dtree[2*b]=0;for(b=0;U>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):10>=h?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;c>=d;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(l>h){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):10>=h?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;d>e;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;R>b;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":86}],98:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}],99:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],100:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:42}],101:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":100,asap:42}]},{},[1]);
/** * 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. * * @emails react-core */ 'use strict'; var PropTypes; var React; var ReactFragment; var ReactPropTypeLocations; var ReactTestUtils; var Component; var MyComponent; var requiredMessage = 'Required prop `testProp` was not specified in `testComponent`.'; function typeCheckFail(declaration, value, message) { var props = {testProp: value}; var error = declaration( props, 'testProp', 'testComponent', ReactPropTypeLocations.prop ); expect(error instanceof Error).toBe(true); expect(error.message).toBe(message); } function typeCheckPass(declaration, value) { var props = {testProp: value}; var error = declaration( props, 'testProp', 'testComponent', ReactPropTypeLocations.prop ); expect(error).toBe(null); } describe('ReactPropTypes', function() { beforeEach(function() { PropTypes = require('ReactPropTypes'); React = require('React'); ReactFragment = require('ReactFragment'); ReactPropTypeLocations = require('ReactPropTypeLocations'); ReactTestUtils = require('ReactTestUtils'); }); describe('Primitive Types', function() { it('should warn for invalid strings', function() { typeCheckFail( PropTypes.string, [], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, false, 'Invalid prop `testProp` of type `boolean` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, 0, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, {}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected `string`.' ); }); it('should fail date and regexp correctly', function() { typeCheckFail( PropTypes.string, new Date(), 'Invalid prop `testProp` of type `date` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, /please/, 'Invalid prop `testProp` of type `regexp` supplied to ' + '`testComponent`, expected `string`.' ); }); it('should not warn for valid values', function() { typeCheckPass(PropTypes.array, []); typeCheckPass(PropTypes.bool, false); typeCheckPass(PropTypes.func, function() {}); typeCheckPass(PropTypes.number, 0); typeCheckPass(PropTypes.string, ''); typeCheckPass(PropTypes.object, {}); typeCheckPass(PropTypes.object, new Date()); typeCheckPass(PropTypes.object, /please/); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass(PropTypes.string, null); typeCheckPass(PropTypes.string, undefined); }); it('should warn for missing required values', function() { typeCheckFail(PropTypes.string.isRequired, null, requiredMessage); typeCheckFail(PropTypes.string.isRequired, undefined, requiredMessage); }); }); describe('Any type', function() { it('should should accept any value', function() { typeCheckPass(PropTypes.any, 0); typeCheckPass(PropTypes.any, 'str'); typeCheckPass(PropTypes.any, []); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass(PropTypes.any, null); typeCheckPass(PropTypes.any, undefined); }); it('should warn for missing required values', function() { typeCheckFail(PropTypes.any.isRequired, null, requiredMessage); typeCheckFail(PropTypes.any.isRequired, undefined, requiredMessage); }); }); describe('ArrayOf Type', function() { it('should support the arrayOf propTypes', function() { typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]); typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']); typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']); }); it('should support arrayOf with complex types', function() { typeCheckPass( PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})), [{a: 1}, {a: 2}] ); function Thing() {} typeCheckPass( PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [new Thing(), new Thing()] ); }); it('should warn with invalid items in the array', function() { typeCheckFail( PropTypes.arrayOf(PropTypes.number), [1, 2, 'b'], 'Invalid prop `testProp[2]` of type `string` supplied to ' + '`testComponent`, expected `number`.' ); }); it('should warn with invalid complex types', function() { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [new Thing(), 'xyz'], 'Invalid prop `testProp[1]` of type `String` supplied to ' + '`testComponent`, expected instance of `' + name + '`.' ); }); it('should warn when passed something other than an array', function() { typeCheckFail( PropTypes.arrayOf(PropTypes.number), {'0': 'maybe-array', length: 1}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected an array.' ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an array.' ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an array.' ); }); it('should not warn when passing an empty array', function() { typeCheckPass(PropTypes.arrayOf(PropTypes.number), []); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass(PropTypes.arrayOf(PropTypes.number), null); typeCheckPass(PropTypes.arrayOf(PropTypes.number), undefined); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.arrayOf(PropTypes.number).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.arrayOf(PropTypes.number).isRequired, undefined, requiredMessage ); }); }); describe('Component Type', function() { beforeEach(function() { Component = React.createClass({ propTypes: { label: PropTypes.element.isRequired, }, render: function() { return <div>{this.props.label}</div>; }, }); spyOn(console, 'error'); }); it('should support components', () => { typeCheckPass(PropTypes.element, <div />); }); it('should not support multiple components or scalar values', () => { var message = 'Invalid prop `testProp` supplied to `testComponent`, ' + 'expected a single ReactElement.'; typeCheckFail(PropTypes.element, [<div />, <div />], message); typeCheckFail(PropTypes.element, 123, message); typeCheckFail(PropTypes.element, 'foo', message); typeCheckFail(PropTypes.element, false, message); }); it('should be able to define a single child as label', () => { var instance = <Component label={<div />} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.error.argsForCall.length).toBe(0); }); it('should warn when passing no label and isRequired is set', () => { var instance = <Component />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.error.argsForCall.length).toBe(1); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass(PropTypes.element, null); typeCheckPass(PropTypes.element, undefined); }); it('should warn for missing required values', function() { typeCheckFail(PropTypes.element.isRequired, null, requiredMessage); typeCheckFail(PropTypes.element.isRequired, undefined, requiredMessage); }); }); describe('Instance Types', function() { it('should warn for invalid instances', function() { function Person() {} function Cat() {} var personName = Person.name || '<<anonymous>>'; var dateName = Date.name || '<<anonymous>>'; var regExpName = RegExp.name || '<<anonymous>>'; typeCheckFail( PropTypes.instanceOf(Person), false, 'Invalid prop `testProp` of type `Boolean` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.' ); typeCheckFail( PropTypes.instanceOf(Person), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.' ); typeCheckFail( PropTypes.instanceOf(Person), '', 'Invalid prop `testProp` of type `String` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.' ); typeCheckFail( PropTypes.instanceOf(Date), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + dateName + '`.' ); typeCheckFail( PropTypes.instanceOf(RegExp), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + regExpName + '`.' ); typeCheckFail( PropTypes.instanceOf(Person), new Cat(), 'Invalid prop `testProp` of type `Cat` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.' ); typeCheckFail( PropTypes.instanceOf(Person), Object.create(null), 'Invalid prop `testProp` of type `<<anonymous>>` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.' ); }); it('should not warn for valid values', function() { function Person() {} function Engineer() {} Engineer.prototype = new Person(); typeCheckPass(PropTypes.instanceOf(Person), new Person()); typeCheckPass(PropTypes.instanceOf(Person), new Engineer()); typeCheckPass(PropTypes.instanceOf(Date), new Date()); typeCheckPass(PropTypes.instanceOf(RegExp), /please/); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass(PropTypes.instanceOf(String), null); typeCheckPass(PropTypes.instanceOf(String), undefined); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.instanceOf(String).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.instanceOf(String).isRequired, undefined, requiredMessage ); }); }); describe('React Component Types', function() { beforeEach(function() { MyComponent = React.createClass({ render: function() { return <div />; }, }); }); it('should warn for invalid values', function() { var failMessage = 'Invalid prop `testProp` supplied to ' + '`testComponent`, expected a ReactNode.'; typeCheckFail(PropTypes.node, true, failMessage); typeCheckFail(PropTypes.node, function() {}, failMessage); typeCheckFail(PropTypes.node, {key: function() {}}, failMessage); typeCheckFail(PropTypes.node, {key: <div />}, failMessage); }); it('should not warn for valid values', function() { spyOn(console, 'error'); typeCheckPass(PropTypes.node, <div />); typeCheckPass(PropTypes.node, false); typeCheckPass(PropTypes.node, <MyComponent />); typeCheckPass(PropTypes.node, 'Some string'); typeCheckPass(PropTypes.node, []); typeCheckPass(PropTypes.node, [ 123, 'Some string', <div />, ['Another string', [456], <span />, <MyComponent />], <MyComponent />, ]); // Object of renderable things var frag = ReactFragment.create; typeCheckPass(PropTypes.node, frag({ k0: 123, k1: 'Some string', k2: <div />, k3: frag({ k30: <MyComponent />, k31: frag({k310: <a />}), k32: 'Another string', }), k4: null, k5: undefined, })); expect(console.error.calls).toEqual([]); }); it('should not warn for iterables', function() { var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return {value: done ? undefined : <MyComponent />, done: done}; }, }; }, }; typeCheckPass(PropTypes.node, iterable); }); it('should not warn for entry iterables', function() { var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return {value: done ? undefined : ['#' + i, <MyComponent />], done: done}; }, }; }, }; iterable.entries = iterable['@@iterator']; typeCheckPass(PropTypes.node, iterable); }); it('should not warn for null/undefined if not required', function() { typeCheckPass(PropTypes.node, null); typeCheckPass(PropTypes.node, undefined); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.node.isRequired, null, 'Required prop `testProp` was not specified in `testComponent`.' ); typeCheckFail( PropTypes.node.isRequired, undefined, 'Required prop `testProp` was not specified in `testComponent`.' ); }); it('should accept empty array for required props', function() { typeCheckPass(PropTypes.node.isRequired, []); }); }); describe('ObjectOf Type', function() { it('should support the objectOf propTypes', function() { typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3}); typeCheckPass( PropTypes.objectOf(PropTypes.string), {a: 'a', b: 'b', c: 'c'} ); typeCheckPass( PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])), {a: 'a', b: 'b'} ); }); it('should support objectOf with complex types', function() { typeCheckPass( PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})), {a: {a: 1}, b: {a: 2}} ); function Thing() {} typeCheckPass( PropTypes.objectOf(PropTypes.instanceOf(Thing)), {a: new Thing(), b: new Thing()} ); }); it('should warn with invalid items in the object', function() { typeCheckFail( PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 'b'}, 'Invalid prop `testProp.c` of type `string` supplied to `testComponent`, ' + 'expected `number`.' ); }); it('should warn with invalid complex types', function() { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.objectOf(PropTypes.instanceOf(Thing)), {a: new Thing(), b: 'xyz'}, 'Invalid prop `testProp.b` of type `String` supplied to ' + '`testComponent`, expected instance of `' + name + '`.' ); }); it('should warn when passed something other than an object', function() { typeCheckFail( PropTypes.objectOf(PropTypes.number), [1, 2], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected an object.' ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an object.' ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an object.' ); }); it('should not warn when passing an empty object', function() { typeCheckPass(PropTypes.objectOf(PropTypes.number), {}); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass(PropTypes.objectOf(PropTypes.number), null); typeCheckPass(PropTypes.objectOf(PropTypes.number), undefined); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.objectOf(PropTypes.number).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.objectOf(PropTypes.number).isRequired, undefined, requiredMessage ); }); }); describe('OneOf Types', function() { it('should fail for invalid argument', function() { typeCheckFail( PropTypes.oneOf('red', 'blue'), 'red', 'Invalid argument supplied to oneOf, expected an instance of array.' ); }); it('should warn for invalid strings', function() { typeCheckFail( PropTypes.oneOf(['red', 'blue']), true, 'Invalid prop `testProp` of value `true` supplied to ' + '`testComponent`, expected one of ["red","blue"].' ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), [], 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].' ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), '', 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].' ); typeCheckFail( PropTypes.oneOf([0, 'false']), false, 'Invalid prop `testProp` of value `false` supplied to ' + '`testComponent`, expected one of [0,"false"].' ); }); it('should not warn for valid values', function() { typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'red'); typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'blue'); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass(PropTypes.oneOf(['red', 'blue']), null); typeCheckPass(PropTypes.oneOf(['red', 'blue']), undefined); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.oneOf(['red', 'blue']).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.oneOf(['red', 'blue']).isRequired, undefined, requiredMessage ); }); }); describe('Union Types', function() { it('should fail for invalid argument', function() { typeCheckFail( PropTypes.oneOfType(PropTypes.string, PropTypes.number), 'red', 'Invalid argument supplied to oneOfType, expected an instance of array.' ); }); it('should warn if none of the types are valid', function() { typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), [], 'Invalid prop `testProp` supplied to `testComponent`.' ); var checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}), ]); typeCheckFail( checker, {c: 1}, 'Invalid prop `testProp` supplied to `testComponent`.' ); }); it('should not warn if one of the types are valid', function() { var checker = PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]); typeCheckPass(checker, null); typeCheckPass(checker, 'foo'); typeCheckPass(checker, 123); checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}), ]); typeCheckPass(checker, {a: 1}); typeCheckPass(checker, {b: 1}); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null ); typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined ); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, undefined, requiredMessage ); }); }); describe('Shape Types', function() { it('should warn for non objects', function() { typeCheckFail( PropTypes.shape({}), 'some string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected `object`.' ); typeCheckFail( PropTypes.shape({}), ['array'], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `object`.' ); }); it('should not warn for empty values', function() { typeCheckPass(PropTypes.shape({}), undefined); typeCheckPass(PropTypes.shape({}), null); typeCheckPass(PropTypes.shape({}), {}); }); it('should not warn for an empty object', function() { typeCheckPass(PropTypes.shape({}).isRequired, {}); }); it('should not warn for non specified types', function() { typeCheckPass(PropTypes.shape({}), {key: 1}); }); it('should not warn for valid types', function() { typeCheckPass(PropTypes.shape({key: PropTypes.number}), {key: 1}); }); it('should warn for required valid types', function() { typeCheckFail( PropTypes.shape({key: PropTypes.number.isRequired}), {}, 'Required prop `testProp.key` was not specified in `testComponent`.' ); }); it('should warn for the first required type', function() { typeCheckFail( PropTypes.shape({ key: PropTypes.number.isRequired, secondKey: PropTypes.number.isRequired, }), {}, 'Required prop `testProp.key` was not specified in `testComponent`.' ); }); it('should warn for invalid key types', function() { typeCheckFail(PropTypes.shape({key: PropTypes.number}), {key: 'abc'}, 'Invalid prop `testProp.key` of type `string` supplied to `testComponent`, ' + 'expected `number`.' ); }); it('should be implicitly optional and not warn without values', function() { typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), null ); typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), undefined ); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.shape({key: PropTypes.number}).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.shape({key: PropTypes.number}).isRequired, undefined, requiredMessage ); }); }); describe('Custom validator', function() { beforeEach(function() { require('mock-modules').dumpCache(); spyOn(console, 'error'); }); it('should have been called with the right params', function() { var spy = jasmine.createSpy(); Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; }, }); var instance = <Component num={5} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(spy.argsForCall.length).toBe(2); // temp double validation expect(spy.argsForCall[0][1]).toBe('num'); expect(spy.argsForCall[0][2]).toBe('Component'); }); it('should have been called even if the prop is not present', function() { var spy = jasmine.createSpy(); Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; }, }); var instance = <Component bla={5} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(spy.argsForCall.length).toBe(2); // temp double validation }); it('should have received the validator\'s return value', function() { var spy = jasmine.createSpy().andCallFake( function(props, propName, componentName) { if (props[propName] !== 5) { return new Error('num must be 5!'); } } ); Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; }, }); var instance = <Component num={6} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toBe( 'Warning: Failed propType: num must be 5!' ); }); it('should not warn if the validator returned null', function() { var spy = jasmine.createSpy().andCallFake( function(props, propName, componentName) { return null; } ); Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; }, }); var instance = <Component num={5} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.error.argsForCall.length).toBe(0); } ); }); });
import _ from "lodash"; import { Meteor } from "meteor/meteor"; import { ReactiveVar } from "meteor/reactive-var"; import { Logger } from "/client/api"; export const PaypalClientAPI = { load: _.once(function () { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.src = "//www.paypalobjects.com/api/checkout.js"; document.head.appendChild(script); this._checkReady(); }), _checkReady() { let i = 0; const checkReady = Meteor.setInterval(() => { if (typeof paypal !== "undefined") { this._loaded.set(true); Meteor.clearInterval(checkReady); } else { i += 100; if (i > 10000) { // stop checking and warn if the lib isn't loaded within 10 secs Meteor.clearInterval(checkReady); Logger.warn("Error loading Paypal lib from CDN"); } } }, 100); }, _loaded: new ReactiveVar(false), loaded() { return this._loaded.get(); } };
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-redux"),require("redux")):"function"==typeof define&&define.amd?define(["react","react-redux","redux"],t):"object"==typeof exports?exports.ReduxForm=t(require("react"),require("react-redux"),require("redux")):e.ReduxForm=t(e.React,e.ReactRedux,e.Redux)}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=59)}([function(e,t,r){e.exports=r(143)()},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=r(81),o=n(i),u=r(78),a=n(u),s=r(80),c=n(s),f=r(76),l=n(f),d=r(77),p=n(d),y=r(79),v=n(y);t.default={allowsArrayErrors:!0,empty:{},emptyList:[],getIn:a.default,setIn:c.default,deepEqual:l.default,deleteIn:p.default,fromJS:function(e){return e},keys:v.default,size:function(e){return e?e.length:0},splice:o.default,toJS:function(e){return e}}},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t,r){"use strict";function n(e,t){var r=e._reduxForm.sectionPrefix;return r?r+"."+t:t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,r){"use strict";e.exports=function(e,t,r,n,i,o,u,a){if(!e){var s;if(void 0===t)s=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,n,i,o,u,a],f=0;s=Error(t.replace(/%s/g,function(){return c[f++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}}},function(e,t,r){function n(e,t){for(var r=e.length;r--;)if(i(e[r][0],t))return r;return-1}var i=r(15);e.exports=n},function(e,t,r){function n(e,t,r){"__proto__"==t&&i?i(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var i=r(111);e.exports=n},function(e,t){e.exports=Array.isArray},function(e,t){function r(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}e.exports=r},function(e,t,r){function n(e){return u(e)?i(e,c):a(e)?[e]:o(s(f(e)))}var i=r(92),o=r(29),u=r(8),a=r(138),s=r(130),c=r(131),f=r(142);e.exports=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=t.prefix="@@redux-form/";t.ARRAY_INSERT=n+"ARRAY_INSERT",t.ARRAY_MOVE=n+"ARRAY_MOVE",t.ARRAY_POP=n+"ARRAY_POP",t.ARRAY_PUSH=n+"ARRAY_PUSH",t.ARRAY_REMOVE=n+"ARRAY_REMOVE",t.ARRAY_REMOVE_ALL=n+"ARRAY_REMOVE_ALL",t.ARRAY_SHIFT=n+"ARRAY_SHIFT",t.ARRAY_SPLICE=n+"ARRAY_SPLICE",t.ARRAY_UNSHIFT=n+"ARRAY_UNSHIFT",t.ARRAY_SWAP=n+"ARRAY_SWAP",t.AUTOFILL=n+"AUTOFILL",t.BLUR=n+"BLUR",t.CHANGE=n+"CHANGE",t.CLEAR_SUBMIT=n+"CLEAR_SUBMIT",t.CLEAR_SUBMIT_ERRORS=n+"CLEAR_SUBMIT_ERRORS",t.CLEAR_ASYNC_ERROR=n+"CLEAR_ASYNC_ERROR",t.DESTROY=n+"DESTROY",t.FOCUS=n+"FOCUS",t.INITIALIZE=n+"INITIALIZE",t.REGISTER_FIELD=n+"REGISTER_FIELD",t.RESET=n+"RESET",t.SET_SUBMIT_FAILED=n+"SET_SUBMIT_FAILED",t.SET_SUBMIT_SUCCEEDED=n+"SET_SUBMIT_SUCCEEDED",t.START_ASYNC_VALIDATION=n+"START_ASYNC_VALIDATION",t.START_SUBMIT=n+"START_SUBMIT",t.STOP_ASYNC_VALIDATION=n+"STOP_ASYNC_VALIDATION",t.STOP_SUBMIT=n+"STOP_SUBMIT",t.SUBMIT=n+"SUBMIT",t.TOUCH=n+"TOUCH",t.UNREGISTER_FIELD=n+"UNREGISTER_FIELD",t.UNTOUCH=n+"UNTOUCH",t.UPDATE_SYNC_ERRORS=n+"UPDATE_SYNC_ERRORS",t.UPDATE_SYNC_WARNINGS=n+"UPDATE_SYNC_WARNINGS"},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(58),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){var t=e.getIn,r=e.keys,n=(0,i.default)(e);return function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")},o=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function(u){var a=i(u);if(t(a,e+".syncError"))return!1;if(!o){if(t(a,e+".error"))return!1}var s=t(a,e+".syncErrors"),c=t(a,e+".asyncErrors"),f=o?void 0:t(a,e+".submitErrors");if(!s&&!c&&!f)return!0;var l=t(a,e+".registeredFields");return!l||!r(l).filter(function(e){return t(l,"['"+e+"'].count")>0}).some(function(e){return n(t(l,"['"+e+"']"),s,c,f)})}}}},function(e,t){function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.exports=r},function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},function(e,t){function r(e){return null!=e&&"object"==typeof e}e.exports=r},function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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 o(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)}Object.defineProperty(t,"__esModule",{value:!0});var u=r(85),a=function(e){return e&&e.__esModule?e:{default:e}}(u);t.default=function(e){function t(e){n(this,t);var r=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,"Submit Validation Failed"));return r.errors=e,r}return o(t,e),t}(a.default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateSyncWarnings=t.updateSyncErrors=t.untouch=t.unregisterField=t.touch=t.setSubmitSucceeded=t.setSubmitFailed=t.submit=t.stopSubmit=t.stopAsyncValidation=t.startSubmit=t.startAsyncValidation=t.reset=t.registerField=t.initialize=t.focus=t.destroy=t.clearAsyncError=t.clearSubmitErrors=t.clearSubmit=t.change=t.blur=t.autofill=t.arrayUnshift=t.arraySwap=t.arraySplice=t.arrayShift=t.arrayRemoveAll=t.arrayRemove=t.arrayPush=t.arrayPop=t.arrayMove=t.arrayInsert=void 0;var n=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=r(11);t.arrayInsert=function(e,t,r,n){return{type:i.ARRAY_INSERT,meta:{form:e,field:t,index:r},payload:n}},t.arrayMove=function(e,t,r,n){return{type:i.ARRAY_MOVE,meta:{form:e,field:t,from:r,to:n}}},t.arrayPop=function(e,t){return{type:i.ARRAY_POP,meta:{form:e,field:t}}},t.arrayPush=function(e,t,r){return{type:i.ARRAY_PUSH,meta:{form:e,field:t},payload:r}},t.arrayRemove=function(e,t,r){return{type:i.ARRAY_REMOVE,meta:{form:e,field:t,index:r}}},t.arrayRemoveAll=function(e,t){return{type:i.ARRAY_REMOVE_ALL,meta:{form:e,field:t}}},t.arrayShift=function(e,t){return{type:i.ARRAY_SHIFT,meta:{form:e,field:t}}},t.arraySplice=function(e,t,r,n,o){var u={type:i.ARRAY_SPLICE,meta:{form:e,field:t,index:r,removeNum:n}};return void 0!==o&&(u.payload=o),u},t.arraySwap=function(e,t,r,n){if(r===n)throw Error("Swap indices cannot be equal");if(0>r||0>n)throw Error("Swap indices cannot be negative");return{type:i.ARRAY_SWAP,meta:{form:e,field:t,indexA:r,indexB:n}}},t.arrayUnshift=function(e,t,r){return{type:i.ARRAY_UNSHIFT,meta:{form:e,field:t},payload:r}},t.autofill=function(e,t,r){return{type:i.AUTOFILL,meta:{form:e,field:t},payload:r}},t.blur=function(e,t,r,n){return{type:i.BLUR,meta:{form:e,field:t,touch:n},payload:r}},t.change=function(e,t,r,n,o){return{type:i.CHANGE,meta:{form:e,field:t,touch:n,persistentSubmitErrors:o},payload:r}},t.clearSubmit=function(e){return{type:i.CLEAR_SUBMIT,meta:{form:e}}},t.clearSubmitErrors=function(e){return{type:i.CLEAR_SUBMIT_ERRORS,meta:{form:e}}},t.clearAsyncError=function(e,t){return{type:i.CLEAR_ASYNC_ERROR,meta:{form:e,field:t}}},t.destroy=function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return{type:i.DESTROY,meta:{form:t}}},t.focus=function(e,t){return{type:i.FOCUS,meta:{form:e,field:t}}},t.initialize=function(e,t,r){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return r instanceof Object&&(o=r,r=!1),{type:i.INITIALIZE,meta:n({form:e,keepDirty:r},o),payload:t}},t.registerField=function(e,t,r){return{type:i.REGISTER_FIELD,meta:{form:e},payload:{name:t,type:r}}},t.reset=function(e){return{type:i.RESET,meta:{form:e}}},t.startAsyncValidation=function(e,t){return{type:i.START_ASYNC_VALIDATION,meta:{form:e,field:t}}},t.startSubmit=function(e){return{type:i.START_SUBMIT,meta:{form:e}}},t.stopAsyncValidation=function(e,t){var r={type:i.STOP_ASYNC_VALIDATION,meta:{form:e},payload:t};return t&&Object.keys(t).length&&(r.error=!0),r},t.stopSubmit=function(e,t){var r={type:i.STOP_SUBMIT,meta:{form:e},payload:t};return t&&Object.keys(t).length&&(r.error=!0),r},t.submit=function(e){return{type:i.SUBMIT,meta:{form:e}}},t.setSubmitFailed=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:i.SET_SUBMIT_FAILED,meta:{form:e,fields:r},error:!0}},t.setSubmitSucceeded=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:i.SET_SUBMIT_SUCCEEDED,meta:{form:e,fields:r},error:!1}},t.touch=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:i.TOUCH,meta:{form:e,fields:r}}},t.unregisterField=function(e,t){return{type:i.UNREGISTER_FIELD,meta:{form:e},payload:{name:t,destroyOnUnmount:2>=arguments.length||void 0===arguments[2]||arguments[2]}}},t.untouch=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:i.UNTOUCH,meta:{form:e,fields:r}}},t.updateSyncErrors=function(e){return{type:i.UPDATE_SYNC_ERRORS,meta:{form:e},payload:{syncErrors:arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},error:arguments[2]}}},t.updateSyncWarnings=function(e){return{type:i.UPDATE_SYNC_WARNINGS,meta:{form:e},payload:{syncWarnings:arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},warning:arguments[2]}}}},function(e,t,r){"use strict";function n(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},o=function(e,t,r){var n=t.value;return"checkbox"===e?i({},t,{checked:!!n}):"radio"===e?i({},t,{checked:n===r,value:r}):"select-multiple"===e?i({},t,{value:n||[]}):"file"===e?i({},t,{value:n||void 0}):t};t.default=function(e,t,r){var u=e.getIn,a=e.toJS,s=r.asyncError,c=r.asyncValidating,f=r.onBlur,l=r.onChange,d=r.onDrop,p=r.onDragStart,y=r.dirty,v=r.dispatch,m=r.onFocus,h=r.form,b=r.format,g=r.pristine,_=r.props,O=r.state,S=r.submitError,E=r.submitFailed,R=r.submitting,F=r.syncError,A=r.syncWarning,j=r.value,w=r._value,x=n(r,["asyncError","asyncValidating","onBlur","onChange","onDrop","onDragStart","dirty","dispatch","onFocus","form","format","parse","pristine","props","state","submitError","submitFailed","submitting","syncError","syncWarning","validate","value","_value","warn"]),P=F||s||S,I=A,T=function(e,r){if(null===r)return e;var n=null==e?"":e;return r?r(e,t):n}(j,b);return{input:o(x.type,{name:t,onBlur:f,onChange:l,onDragStart:p,onDrop:d,onFocus:m,value:T},w),meta:i({},a(O),{active:!(!O||!u(O,"active")),asyncValidating:c,autofilled:!(!O||!u(O,"autofilled")),dirty:y,dispatch:v,error:P,form:h,warning:I,invalid:!!P,pristine:g,submitting:!!R,submitFailed:!!E,touched:!(!O||!u(O,"touched")),valid:!P,visited:!(!O||!u(O,"visited"))}),custom:i({},x,_)}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return!!(e&&e.stopPropagation&&e.preventDefault)}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=r(53),o=n(i),u=r(60),a=n(u);t.default=function(e,t){var r=t.name,n=t.parse,i=t.normalize,u=(0,o.default)(e,a.default);return n&&(u=n(u,r)),i&&(u=i(r,u)),u}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(20),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){var t=(0,i.default)(e);return t&&e.preventDefault(),t}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.deepEqual,r=e.empty,n=e.getIn;return function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return n(e,"form")};return function(o){var u=i(o),a=n(u,e+".initial")||r,s=n(u,e+".values")||a;return t(a,s)}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(33),i=function(e){return e&&e.__esModule?e:{default:e}}(n),o=function(e,t,r,n,i,o){if(o)return e===t};t.default=function(e,t,r){return!(0,i.default)(e.props,t,o)||!(0,i.default)(e.state,r,o)}},function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var i=r(122),o=r(123),u=r(124),a=r(125),s=r(126);n.prototype.clear=i,n.prototype.delete=o,n.prototype.get=u,n.prototype.has=a,n.prototype.set=s,e.exports=n},function(e,t,r){function n(e,t,r){(void 0===r||o(e[t],r))&&(void 0!==r||t in e)||i(e,t,r)}var i=r(7),o=r(15);e.exports=n},function(e,t,r){e.exports=r(110)()},function(e,t){function r(e){return i.call(e)}var n=Object.prototype,i=n.toString;e.exports=r},function(e,t){function r(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}e.exports=r},function(e,t,r){e.exports=r(14)(Object.getPrototypeOf,Object)},function(e,t,r){var n=r(115),i="object"==typeof self&&self&&self.Object===Object&&self;e.exports=n||i||Function("return this")()},function(e,t){function r(){return!1}e.exports=r},function(e,t,r){function n(e,t,r){r="function"==typeof r?r:void 0;var n=r?r(e,t):void 0;return void 0===n?i(e,t,void 0,r):!!n}var i=r(98);e.exports=n},function(e,t,r){function n(e){if(!o(e))return!1;var t=i(e);return t==a||t==s||t==u||t==c}var i=r(28),o=r(9),u="[object AsyncFunction]",a="[object Function]",s="[object GeneratorFunction]",c="[object Proxy]";e.exports=n},function(e,t){function r(){return!1}e.exports=r},function(e,t){function r(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}e.exports=r},function(e,t,r){function n(e,t){var r={};return t=u(t,3),o(e,function(e,n,o){i(r,n,t(e,n,o))}),r}var i=r(7),o=r(96),u=r(100);e.exports=n},function(e,t){e.exports=r},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(62),a=i(u),s=r(63),c=i(s),f=r(43),l=i(f),d=r(45),p=i(d),y=r(44),v=i(y),m=r(55),h=i(m),b=r(84),g=i(b),_=r(66),O=i(_),S=r(70),E=i(S),R=r(65),F=i(R),A=r(68),j=i(A),w=r(64),x=i(w),P=r(69),I=i(P),T=r(67),k=i(T),C=r(73),M=i(C),V=r(74),U=i(V),N=r(23),D=i(N),W=r(12),q=i(W),L=r(75),Y=i(L),z=r(72),B=i(z),H=r(71),G=i(H),K=r(46),J=i(K),Z=r(47),$=i(Z),Q=r(17),X=i(Q),ee=r(61),te=i(ee),re=r(18),ne=n(re),ie=r(11),oe=n(ie);t.default=function(e){return o({actionTypes:oe},ne,{Field:(0,l.default)(e),Fields:(0,p.default)(e),FieldArray:(0,v.default)(e),Form:J.default,FormSection:$.default,formValueSelector:(0,h.default)(e),getFormNames:(0,O.default)(e),getFormValues:(0,E.default)(e),getFormInitialValues:(0,F.default)(e),getFormSyncErrors:(0,j.default)(e),getFormAsyncErrors:(0,x.default)(e),getFormSyncWarnings:(0,I.default)(e),getFormSubmitErrors:(0,k.default)(e),isDirty:(0,M.default)(e),isInvalid:(0,U.default)(e),isPristine:(0,D.default)(e),isValid:(0,q.default)(e),isSubmitting:(0,Y.default)(e),hasSubmitSucceeded:(0,B.default)(e),hasSubmitFailed:(0,G.default)(e),propTypes:te.default,reduxForm:(0,c.default)(e),reducer:(0,a.default)(e),SubmissionError:X.default,values:(0,g.default)(e)})}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(2),l=r(0),d=n(l),p=r(3),y=r(19),v=n(y),m=r(21),h=n(m),b=r(82),g=r(1),_=n(g),O=["_reduxForm"];t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.toJS,l=function(e,t){var r=_.default.getIn(e,t);return r&&r._error?r._error:r},y=function(e,t){var n=r(e,t);return n&&n._warning?n._warning:n},m=function(e){function l(e){o(this,l);var t=u(this,(l.__proto__||Object.getPrototypeOf(l)).call(this,e));return t.handleChange=t.handleChange.bind(t),t.handleFocus=t.handleFocus.bind(t),t.handleBlur=t.handleBlur.bind(t),t.handleDragStart=t.handleDragStart.bind(t),t.handleDrop=t.handleDrop.bind(t),t}return a(l,e),c(l,[{key:"shouldComponentUpdate",value:function(e){var r=this,n=Object.keys(e);return n.length!==Object.keys(this.props).length||n.some(function(n){return!~O.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"isPristine",value:function(){return this.props.pristine}},{key:"getValue",value:function(){return this.props.value}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"handleChange",value:function(e){var t=this.props,r=t.name,n=t.dispatch,i=t.parse,o=t.normalize,u=t.onChange,a=t._reduxForm,c=t.value,f=(0,h.default)(e,{name:r,parse:i,normalize:o}),l=!1;u&&u(s({},e,{preventDefault:function(){return l=!0,e.preventDefault()}}),f,c),l||n(a.change(r,f))}},{key:"handleFocus",value:function(e){var t=this.props,r=t.name,n=t.dispatch,i=t.onFocus,o=t._reduxForm,u=!1;i&&i(s({},e,{preventDefault:function(){return u=!0,e.preventDefault()}})),u||n(o.focus(r))}},{key:"handleBlur",value:function(e){var t=this.props,r=t.name,n=t.dispatch,i=t.parse,o=t.normalize,u=t.onBlur,a=t._reduxForm,c=t._value,f=t.value,l=(0,h.default)(e,{name:r,parse:i,normalize:o});l===c&&void 0!==c&&(l=f);var d=!1;u&&u(s({},e,{preventDefault:function(){return d=!0,e.preventDefault()}}),l,f),d||(n(a.blur(r,l)),a.asyncValidate&&a.asyncValidate(r,l))}},{key:"handleDragStart",value:function(e){var t=this.props,r=t.onDragStart,n=t.value;e.dataTransfer.setData(b.dataKey,null==n?"":n),r&&r(e)}},{key:"handleDrop",value:function(e){var t=this.props,r=t.name,n=t.dispatch,i=t.onDrop,o=t._reduxForm,u=t.value,a=e.dataTransfer.getData(b.dataKey),c=!1;i&&i(s({},e,{preventDefault:function(){return c=!0,e.preventDefault()}}),a,u),c||(n(o.change(r,a)),e.preventDefault())}},{key:"render",value:function(){var e=this.props,t=e.component,o=e.withRef,u=e.name,a=e._reduxForm,c=i(e,["component","withRef","name","_reduxForm","normalize","onBlur","onChange","onFocus","onDragStart","onDrop"]),l=(0,v.default)({getIn:r,toJS:n},u,s({},c,{form:a.form,onBlur:this.handleBlur,onChange:this.handleChange,onDrop:this.handleDrop,onDragStart:this.handleDragStart,onFocus:this.handleFocus})),d=l.custom,p=i(l,["custom"]);if(o&&(d.ref="renderedComponent"),"string"==typeof t){var y=p.input;return(0,f.createElement)(t,s({},y,d))}return(0,f.createElement)(t,s({},p,d))}}]),l}(f.Component);return m.propTypes={component:d.default.oneOfType([d.default.func,d.default.string]).isRequired,props:d.default.object},(0,p.connect)(function(e,n){var i=n.name,o=n._reduxForm,u=o.initialValues,a=o.getFormState,s=a(e),c=r(s,"initial."+i),f=void 0!==c?c:u&&r(u,i),d=r(s,"values."+i),p=r(s,"submitting"),v=l(r(s,"syncErrors"),i),m=y(r(s,"syncWarnings"),i),h=t(d,f);return{asyncError:r(s,"asyncErrors."+i),asyncValidating:r(s,"asyncValidating")===i,dirty:!h,pristine:h,state:r(s,"fields."+i),submitError:r(s,"submitErrors."+i),submitFailed:r(s,"submitFailed"),submitting:p,syncError:v,syncWarning:m,value:d,_value:n.value}},void 0,void 0,{withRef:!0})(m)}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=r(37),c=n(s),f=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(2),d=r(0),p=n(d),y=r(3),v=r(38),m=r(49),h=n(m),b=r(1),g=n(b),_=["_reduxForm","value"];t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.size,s=function(e,t){return g.default.getIn(e,t+"._error")},d=function(e,t){return r(e,t+"._warning")},m=function(e){function n(){o(this,n);var e=u(this,(n.__proto__||Object.getPrototypeOf(n)).call(this));return e.getValue=e.getValue.bind(e),e}return a(n,e),f(n,[{key:"shouldComponentUpdate",value:function(e){var r=this,n=this.props.value,i=e.value;if(n&&i&&(n.length!==i.length||n.every(function(e){return i.some(function(r){return t(e,r)})})))return!0;var o=Object.keys(e);return o.length!==Object.keys(this.props).length||o.some(function(n){return!~_.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"getValue",value:function(e){return this.props.value&&r(this.props.value,e)}},{key:"render",value:function(){var e=this.props,t=e.component,n=e.withRef,o=e.name,u=e._reduxForm,a=i(e,["component","withRef","name","_reduxForm","validate","warn"]),s=(0,h.default)(r,o,u.form,u.sectionPrefix,this.getValue,a);return n&&(s.ref="renderedComponent"),(0,l.createElement)(t,s)}},{key:"dirty",get:function(){return this.props.dirty}},{key:"pristine",get:function(){return this.props.pristine}},{key:"value",get:function(){return this.props.value}}]),n}(l.Component);return m.propTypes={component:p.default.oneOfType([p.default.func,p.default.string]).isRequired,props:p.default.object},m.contextTypes={_reduxForm:p.default.object},(0,y.connect)(function(e,i){var o=i.name,u=i._reduxForm,a=u.initialValues,c=u.getFormState,f=c(e),l=r(f,"initial."+o)||a&&r(a,o),p=r(f,"values."+o),y=r(f,"submitting"),v=s(r(f,"syncErrors"),o),m=d(r(f,"syncWarnings"),o),h=t(p,l);return{asyncError:r(f,"asyncErrors."+o+"._error"),dirty:!h,pristine:h,state:r(f,"fields."+o),submitError:r(f,"submitErrors."+o+"._error"),submitFailed:r(f,"submitFailed"),submitting:y,syncError:v,syncWarning:m,value:p,length:n(p)}},function(e,t){var r=t.name,n=t._reduxForm;return(0,c.default)({arrayInsert:n.arrayInsert,arrayMove:n.arrayMove,arrayPop:n.arrayPop,arrayPush:n.arrayPush,arrayRemove:n.arrayRemove,arrayRemoveAll:n.arrayRemoveAll,arrayShift:n.arrayShift,arraySplice:n.arraySplice,arraySwap:n.arraySwap,arrayUnshift:n.arrayUnshift},function(t){return(0,v.bindActionCreators)(t.bind(null,r),e)})},void 0,{withRef:!0})(m)}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(2),l=r(0),d=n(l),p=r(3),y=r(19),v=n(y),m=r(1),h=n(m),b=r(21),g=n(b),_=["_reduxForm"];t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.toJS,l=e.size,y=function(e,t){return h.default.getIn(e,t+"._error")||h.default.getIn(e,t)},m=function(e,t){var n=r(e,t);return n&&n._warning?n._warning:n},b=function(e){function d(e){o(this,d);var t=u(this,(d.__proto__||Object.getPrototypeOf(d)).call(this,e));return t.handleChange=t.handleChange.bind(t),t.handleFocus=t.handleFocus.bind(t),t.handleBlur=t.handleBlur.bind(t),t.onChangeFns=e.names.reduce(function(e,r){return e[r]=function(e){return t.handleChange(r,e)},e},{}),t.onFocusFns=e.names.reduce(function(e,r){return e[r]=function(){return t.handleFocus(r)},e},{}),t.onBlurFns=e.names.reduce(function(e,r){return e[r]=function(e){return t.handleBlur(r,e)},e},{}),t}return a(d,e),c(d,[{key:"componentWillReceiveProps",value:function(e){var t=this;this.props.names===e.names||l(this.props.names)===l(e.names)&&!e.names.some(function(e){return!t.props._fields[e]})||(this.onChangeFns=e.names.reduce(function(e,r){return e[r]=function(e){return t.handleChange(r,e)},e},{}),this.onFocusFns=e.names.reduce(function(e,r){return e[r]=function(){return t.handleFocus(r)},e},{}),this.onBlurFns=e.names.reduce(function(e,r){return e[r]=function(e){return t.handleBlur(r,e)},e},{}))}},{key:"shouldComponentUpdate",value:function(e){var r=this,n=Object.keys(e);return n.length!==Object.keys(this.props).length||n.some(function(n){return!~_.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"isDirty",value:function(){var e=this.props._fields;return Object.keys(e).some(function(t){return e[t].dirty})}},{key:"getValues",value:function(){var e=this.props._fields;return Object.keys(e).reduce(function(t,r){return h.default.setIn(t,r,e[r].value)},{})}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"handleChange",value:function(e,t){var r=this.props;(0,r.dispatch)(r._reduxForm.change(e,(0,g.default)(t,{name:e,parse:r.parse,normalize:r.normalize})))}},{key:"handleFocus",value:function(e){var t=this.props;(0,t.dispatch)(t._reduxForm.focus(e))}},{key:"handleBlur",value:function(e,t){var r=this.props,n=r.dispatch,i=r.parse,o=r.normalize,u=r._reduxForm,a=(0,g.default)(t,{name:e,parse:i,normalize:o});n(u.blur(e,a)),u.asyncValidate&&u.asyncValidate(e,a)}},{key:"render",value:function(){var e=this,t=this.props,o=t.component,u=t.withRef,a=t._fields,c=t._reduxForm,l=i(t,["component","withRef","_fields","_reduxForm"]),d=c.sectionPrefix,p=c.form,y=Object.keys(a).reduce(function(t,o){var u=a[o],c=(0,v.default)({getIn:r,toJS:n},o,s({},u,l,{form:p,onBlur:e.onBlurFns[o],onChange:e.onChangeFns[o],onFocus:e.onFocusFns[o]})),f=c.custom,y=i(c,["custom"]);t.custom=f;var m=d?o.replace(d+".",""):o;return h.default.setIn(t,m,y)},{}),m=y.custom,b=i(y,["custom"]);return u&&(b.ref="renderedComponent"),(0,f.createElement)(o,s({},b,m))}}]),d}(f.Component);return b.propTypes={component:d.default.oneOfType([d.default.func,d.default.string]).isRequired,_fields:d.default.object.isRequired,props:d.default.object},(0,p.connect)(function(e,t){var n=t.names,i=t._reduxForm,o=i.initialValues,u=i.getFormState,a=u(e);return{_fields:n.reduce(function(e,n){var i=r(a,"initial."+n),u=void 0!==i?i:o&&r(o,n),s=r(a,"values."+n),c=y(r(a,"syncErrors"),n),f=m(r(a,"syncWarnings"),n),l=r(a,"submitting"),d=s===u;return e[n]={asyncError:r(a,"asyncErrors."+n),asyncValidating:r(a,"asyncValidating")===n,dirty:!d,pristine:d,state:r(a,"fields."+n),submitError:r(a,"submitErrors."+n),submitFailed:r(a,"submitFailed"),submitting:l,syncError:c,syncWarning:f,value:s,_value:t.value},e},{})}},void 0,void 0,{withRef:!0})(b)}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(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 u(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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c=r(2),f=r(0),l=n(f),d=r(5),p=n(d),y=r(40),v=n(y),m=r(24),h=n(m),b=r(4),g=n(b);t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.setIn,f=e.toJS,d=(0,v.default)({deepEqual:t,getIn:r,toJS:f}),y=function(e){function t(e,r){i(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));if(!r._reduxForm)throw Error("Field must be inside a component decorated with reduxForm()");return n.normalize=n.normalize.bind(n),n}return u(t,e),s(t,[{key:"shouldComponentUpdate",value:function(e,t){return(0,h.default)(this,e,t)}},{key:"componentWillMount",value:function(){var e=this;this.context._reduxForm.register(this.name,"Field",function(){return e.props.validate},function(){return e.props.warn})}},{key:"componentWillReceiveProps",value:function(e){this.props.name!==e.name&&(this.context._reduxForm.unregister(this.name),this.context._reduxForm.register((0,g.default)(this.context,e.name),"Field"))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return(0,p.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to Field"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"normalize",value:function(e,t){var r=this.props.normalize;if(!r)return t;var i=this.context._reduxForm.getValues();return r(t,this.value,n(i,e,t),i)}},{key:"render",value:function(){return(0,c.createElement)(d,a({},this.props,{name:this.name,normalize:this.normalize,_reduxForm:this.context._reduxForm,ref:"connected"}))}},{key:"name",get:function(){return(0,g.default)(this.context,this.props.name)}},{key:"dirty",get:function(){return!this.pristine}},{key:"pristine",get:function(){return this.refs.connected.getWrappedInstance().isPristine()}},{key:"value",get:function(){return this.refs.connected&&this.refs.connected.getWrappedInstance().getValue()}}]),t}(c.Component);return y.propTypes={name:l.default.string.isRequired,component:l.default.oneOfType([l.default.func,l.default.string]).isRequired,format:l.default.func,normalize:l.default.func,onBlur:l.default.func,onChange:l.default.func,onFocus:l.default.func,onDragStart:l.default.func,onDrop:l.default.func,parse:l.default.func,props:l.default.object,validate:l.default.oneOfType([l.default.func,l.default.arrayOf(l.default.func)]),warn:l.default.oneOfType([l.default.func,l.default.arrayOf(l.default.func)]),withRef:l.default.bool},y.contextTypes={_reduxForm:l.default.object},y}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(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 u(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 a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(2),l=r(0),d=n(l),p=r(5),y=n(p),v=r(41),m=n(v),h=r(4),b=n(h),g=function(e){return Array.isArray(e)?e:[e]},_=function(e,t){return e&&function(){for(var r=g(e),n=0;r.length>n;n++){var i=r[n].apply(r,arguments);if(i)return a({},t,i)}}};t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.size,a=(0,m.default)({deepEqual:t,getIn:r,size:n}),l=function(e){function t(e,r){i(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));if(!r._reduxForm)throw Error("FieldArray must be inside a component decorated with reduxForm()");return n}return u(t,e),c(t,[{key:"componentWillMount",value:function(){var e=this;this.context._reduxForm.register(this.name,"FieldArray",function(){return _(e.props.validate,"_error")},function(){return _(e.props.warn,"_warning")})}},{key:"componentWillReceiveProps",value:function(e){this.props.name!==e.name&&(this.context._reduxForm.unregister(this.name),this.context._reduxForm.register((0,b.default)(this.context,e.name),"FieldArray"))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return(0,y.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to FieldArray"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){return(0,f.createElement)(a,s({},this.props,{name:this.name,syncError:this.syncError,syncWarning:this.syncWarning,_reduxForm:this.context._reduxForm,ref:"connected"}))}},{key:"name",get:function(){return(0,b.default)(this.context,this.props.name)}},{key:"dirty",get:function(){return this.refs.connected.getWrappedInstance().dirty}},{key:"pristine",get:function(){return this.refs.connected.getWrappedInstance().pristine}},{key:"value",get:function(){return this.refs.connected.getWrappedInstance().value}}]),t}(f.Component);return l.propTypes={name:d.default.string.isRequired,component:d.default.func.isRequired,props:d.default.object,validate:d.default.oneOfType([d.default.func,d.default.arrayOf(d.default.func)]),warn:d.default.oneOfType([d.default.func,d.default.arrayOf(d.default.func)]),withRef:d.default.bool},l.contextTypes={_reduxForm:d.default.object},l}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(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 u(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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c=r(2),f=r(0),l=n(f),d=r(5),p=n(d),y=r(42),v=n(y),m=r(24),h=n(m),b=r(1),g=n(b),_=r(4),O=n(_),S=function(e){return e?Array.isArray(e)||e._isFieldArray?void 0:Error('Invalid prop "names" supplied to <Fields/>. Must be either an array of strings or the fields array generated by FieldArray.'):Error('No "names" prop was specified <Fields/>')};t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.toJS,f=e.size,d=(0,v.default)({deepEqual:t,getIn:r,toJS:n,size:f}),y=function(e){function t(e,r){i(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));if(!r._reduxForm)throw Error("Fields must be inside a component decorated with reduxForm()");return n}return u(t,e),s(t,[{key:"shouldComponentUpdate",value:function(e,t){return(0,h.default)(this,e,t)}},{key:"componentWillMount",value:function(){var e=S(this.props.names);if(e)throw e;var t=this.context,r=t._reduxForm.register;this.names.forEach(function(e){return r(e,"Field")})}},{key:"componentWillReceiveProps",value:function(e){if(!g.default.deepEqual(this.props.names,e.names)){var t=this.context,r=t._reduxForm,n=r.register,i=r.unregister;this.props.names.forEach(function(e){return i((0,O.default)(t,e))}),e.names.forEach(function(e){return n((0,O.default)(t,e),"Field")})}}},{key:"componentWillUnmount",value:function(){var e=this.context,t=e._reduxForm.unregister;this.props.names.forEach(function(r){return t((0,O.default)(e,r))})}},{key:"getRenderedComponent",value:function(){return(0,p.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to Fields"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){var e=this.context;return(0,c.createElement)(d,a({},this.props,{names:this.props.names.map(function(t){return(0,O.default)(e,t)}),_reduxForm:this.context._reduxForm,ref:"connected"}))}},{key:"names",get:function(){var e=this.context;return this.props.names.map(function(t){return(0,O.default)(e,t)})}},{key:"dirty",get:function(){return this.refs.connected.getWrappedInstance().isDirty()}},{key:"pristine",get:function(){return!this.dirty}},{key:"values",get:function(){return this.refs.connected&&this.refs.connected.getWrappedInstance().getValues()}}]),t}(c.Component);return y.propTypes={names:function(e,t){return S(e[t])},component:l.default.oneOfType([l.default.func,l.default.string]).isRequired,format:l.default.func,parse:l.default.func,props:l.default.object,withRef:l.default.bool},y.contextTypes={_reduxForm:l.default.object},y}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(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 u(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)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(2),c=n(s),f=r(0),l=n(f),d=function(e){function t(e,r){i(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));if(!r._reduxForm)throw Error("Form must be inside a component decorated with reduxForm()");return n}return u(t,e),a(t,[{key:"componentWillMount",value:function(){this.context._reduxForm.registerInnerOnSubmit(this.props.onSubmit)}},{key:"render",value:function(){return c.default.createElement("form",this.props)}}]),t}(s.Component);d.propTypes={onSubmit:l.default.func.isRequired},d.contextTypes={_reduxForm:l.default.object},t.default=d},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(2),l=n(f),d=r(0),p=n(d),y=r(4),v=n(y),m=function(e){function t(e,r){o(this,t);var n=u(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));if(!r._reduxForm)throw Error("FormSection must be inside a component decorated with reduxForm()");return n}return a(t,e),c(t,[{key:"getChildContext",value:function(){var e=this.context;return{_reduxForm:s({},e._reduxForm,{sectionPrefix:(0,v.default)(e,this.props.name)})}}},{key:"render",value:function(){var e=this.props,t=e.children,r=e.component,n=i(e,["children","name","component"]);return l.default.isValidElement(t)?t:(0,f.createElement)(r,s({},n,{children:t}))}}]),t}(f.Component);m.propTypes={name:p.default.string.isRequired,component:p.default.oneOfType([p.default.func,p.default.string])},m.defaultProps={component:"div"},m.childContextTypes={_reduxForm:p.default.object.isRequired},m.contextTypes={_reduxForm:p.default.object},t.default=m},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(13),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e,t,r,n){t(n);var o=e();if(!(0,i.default)(o))throw Error("asyncValidate function passed to reduxForm must return a promise");var u=function(e){return function(t){if(t&&Object.keys(t).length)return r(t),t;if(e)throw r(),Error("Asynchronous validation promise was rejected without errors.");return r(),Promise.resolve()}};return o.then(u(!1),u(!0))}},function(e,t,r){"use strict";function n(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.default=function(e,t,r,o,u,a){var s=a.arrayInsert,c=a.arrayMove,f=a.arrayPop,l=a.arrayPush,d=a.arrayRemove,p=a.arrayRemoveAll,y=a.arrayShift,v=a.arraySwap,m=a.arrayUnshift,h=a.asyncError,b=a.dirty,g=a.length,_=a.pristine,O=a.submitError,S=a.state,E=a.submitFailed,R=a.submitting,F=a.syncError,A=a.syncWarning,j=a.value,w=a.props,x=n(a,["arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncError","dirty","length","pristine","submitError","state","submitFailed","submitting","syncError","syncWarning","value","props"]),P=F||h||O,I=A,T=o?t.replace(o+".",""):t,k=i({fields:{_isFieldArray:!0,forEach:function(e){return(j||[]).forEach(function(t,r){return e(T+"["+r+"]",r,k.fields)})},get:u,getAll:function(){return j},insert:s,length:g,map:function(e){return(j||[]).map(function(t,r){return e(T+"["+r+"]",r,k.fields)})},move:c,name:t,pop:function(){return f(),e(j,g-1)},push:l,reduce:function(e,t){return(j||[]).reduce(function(t,r,n){return e(t,T+"["+n+"]",n,k.fields)},t)},remove:d,removeAll:p,shift:function(){return y(),e(j,0)},swap:v,unshift:m},meta:{dirty:b,error:P,form:r,warning:I,invalid:!!P,pristine:_,submitting:R,submitFailed:E,touched:!(!S||!e(S,"touched")),valid:!P}},w,x);return k}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.initialized,r=e.trigger,n=e.pristine;if(!e.syncValidationPasses)return!1;switch(r){case"blur":return!0;case"submit":return!n||!t;default:return!1}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.values,r=e.nextProps,n=e.initialRender,i=e.lastFieldValidatorKeys,o=e.fieldValidatorKeys,u=e.structure;return!!n||(!u.deepEqual(t,r.values)||!u.deepEqual(i,o))}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(10),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){var t=e.deepEqual,r=e.empty,n=e.getIn,o=e.deleteIn,u=e.setIn;return function e(a,s){if("]"===s[s.length-1]){var c=(0,i.default)(s);c.pop();return n(a,c.join("."))?u(a,s,void 0):a}var f=o(a,s),l=s.lastIndexOf(".");if(l>0){var d=s.substring(0,l);if("]"!==d[d.length-1]){var p=n(f,d);if(t(p,r))return e(f,d)}}return f}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(20),i=function(e){return e&&e.__esModule?e:{default:e}}(n),o=function(e){var t=[];if(e)for(var r=0;e.length>r;r++){var n=e[r];n.selected&&t.push(n.value)}return t};t.default=function(e,t){if((0,i.default)(e)){if(!t&&e.nativeEvent&&void 0!==e.nativeEvent.text)return e.nativeEvent.text;if(t&&void 0!==e.nativeEvent)return e.nativeEvent.text;var r=e.target,n=r.type,u=r.value,a=r.checked,s=r.files,c=e.dataTransfer;return"checkbox"===n?a:"file"===n?s||c&&c.files:"select-multiple"===n?o(e.target.options):u}return e}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(22),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){return function(t){for(var r=arguments.length,n=Array(r>1?r-1:0),o=1;r>o;o++)n[o-1]=arguments[o];return(0,i.default)(t)?e.apply(void 0,n):e.apply(void 0,[t].concat(n))}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=r(5),o=n(i),u=r(1),a=n(u);t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return(0,o.default)(e,"Form value must be specified"),function(n){for(var i=arguments.length,u=Array(i>1?i-1:0),s=1;i>s;s++)u[s-1]=arguments[s];return(0,o.default)(u.length,"No fields specified"),1===u.length?t(r(n),e+".values."+u[0]):u.reduce(function(i,o){var u=t(r(n),e+".values."+o);return void 0===u?i:a.default.setIn(i,o,u)},{})}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1),i=function(e){return e&&e.__esModule?e:{default:e}}(n),o=function(e){return Array.isArray(e)?e:[e]},u=function(e,t,r,n){for(var i=o(n),u=0;i.length>u;u++){var a=i[u](e,t,r);if(a)return a}};t.default=function(e,t){var r=t.getIn;return function(t,n){var o={};return Object.keys(e).forEach(function(a){var s=r(t,a),c=u(s,t,n,e[a]);c&&(o=i.default.setIn(o,a,c))}),o}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var o=r(13),u=n(o),a=r(17),s=n(a);t.default=function(e,t,r,n,o){var a=t.dispatch,c=t.onSubmitFail,f=t.onSubmitSuccess,l=t.startSubmit,d=t.stopSubmit,p=t.setSubmitFailed,y=t.setSubmitSucceeded,v=t.syncErrors,m=t.touch,h=t.values,b=t.persistentSubmitErrors;if(m.apply(void 0,i(o)),r||b){var g=function(){var r=void 0;try{r=e(h,a,t)}catch(e){var n=e instanceof s.default?e.errors:void 0;if(d(n),p.apply(void 0,i(o)),c&&c(n,a,e,t),n||c)return n;throw e}return(0,u.default)(r)?(l(),r.then(function(e){return d(),y(),f&&f(e,a,t),e},function(e){var r=e instanceof s.default?e.errors:void 0;if(d(r),p.apply(void 0,i(o)),c&&c(r,a,e,t),r||c)return r;throw e})):(y(),f&&f(r,a,t),r)},_=n&&n();return _?_.then(function(e){if(e)throw e;return g()}).catch(function(e){return p.apply(void 0,i(o)),c&&c(e,a,null,t),Promise.reject(e)}):g()}return p.apply(void 0,i(o)),c&&c(v,a,null,t),v}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e,t){switch(t){case"Field":return[e,e+"._error"];case"FieldArray":return[e+"._error"];default:throw Error("Unknown field type")}};t.default=function(e){var t=e.getIn;return function(e,r,i,o){if(!r&&!i&&!o)return!1;var u=t(e,"name"),a=t(e,"type");return n(u,a).some(function(e){return t(r,e)||t(i,e)||t(o,e)})}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.values=t.untouch=t.unregisterField=t.touch=t.SubmissionError=t.submit=t.stopSubmit=t.stopAsyncValidation=t.startSubmit=t.startAsyncValidation=t.setSubmitSucceeded=t.setSubmitFailed=t.reset=t.registerField=t.reduxForm=t.reducer=t.propTypes=t.hasSubmitFailed=t.hasSubmitSucceeded=t.isSubmitting=t.isValid=t.isPristine=t.isInvalid=t.isDirty=t.initialize=t.getFormSubmitErrors=t.getFormSyncWarnings=t.getFormAsyncErrors=t.getFormSyncErrors=t.getFormInitialValues=t.getFormValues=t.getFormNames=t.formValueSelector=t.focus=t.FormSection=t.Form=t.FieldArray=t.Fields=t.Field=t.destroy=t.clearSubmitErrors=t.change=t.blur=t.autofill=t.arrayUnshift=t.arraySwap=t.arraySplice=t.arrayShift=t.arrayRemoveAll=t.arrayRemove=t.arrayPush=t.arrayPop=t.arrayMove=t.arrayInsert=t.actionTypes=void 0;var i=r(39),o=n(i),u=r(1),a=n(u),s=(0,o.default)(a.default),c=s.actionTypes,f=s.arrayInsert,l=s.arrayMove,d=s.arrayPop,p=s.arrayPush,y=s.arrayRemove,v=s.arrayRemoveAll,m=s.arrayShift,h=s.arraySplice,b=s.arraySwap,g=s.arrayUnshift,_=s.autofill,O=s.blur,S=s.change,E=s.clearSubmitErrors,R=s.destroy,F=s.Field,A=s.Fields,j=s.FieldArray,w=s.Form,x=s.FormSection,P=s.focus,I=s.formValueSelector,T=s.getFormNames,k=s.getFormValues,C=s.getFormInitialValues,M=s.getFormSyncErrors,V=s.getFormAsyncErrors,U=s.getFormSyncWarnings,N=s.getFormSubmitErrors,D=s.initialize,W=s.isDirty,q=s.isInvalid,L=s.isPristine,Y=s.isValid,z=s.isSubmitting,B=s.hasSubmitSucceeded,H=s.hasSubmitFailed,G=s.propTypes,K=s.reducer,J=s.reduxForm,Z=s.registerField,$=s.reset,Q=s.setSubmitFailed,X=s.setSubmitSucceeded,ee=s.startAsyncValidation,te=s.startSubmit,re=s.stopAsyncValidation,ne=s.stopSubmit,ie=s.submit,oe=s.SubmissionError,ue=s.touch,ae=s.unregisterField,se=s.untouch,ce=s.values;t.actionTypes=c,t.arrayInsert=f,t.arrayMove=l,t.arrayPop=d,t.arrayPush=p,t.arrayRemove=y,t.arrayRemoveAll=v,t.arrayShift=m,t.arraySplice=h,t.arraySwap=b,t.arrayUnshift=g,t.autofill=_,t.blur=O,t.change=S,t.clearSubmitErrors=E,t.destroy=R,t.Field=F,t.Fields=A,t.FieldArray=j,t.Form=w,t.FormSection=x,t.focus=P,t.formValueSelector=I,t.getFormNames=T,t.getFormValues=k,t.getFormInitialValues=C,t.getFormSyncErrors=M,t.getFormAsyncErrors=V,t.getFormSyncWarnings=U,t.getFormSubmitErrors=N,t.initialize=D,t.isDirty=W,t.isInvalid=q,t.isPristine=L,t.isValid=Y,t.isSubmitting=z,t.hasSubmitSucceeded=B,t.hasSubmitFailed=H,t.propTypes=G,t.reducer=K,t.reduxForm=J,t.registerField=Z,t.reset=$,t.setSubmitFailed=Q,t.setSubmitSucceeded=X,t.startAsyncValidation=ee,t.startSubmit=te,t.stopAsyncValidation=re,t.stopSubmit=ne,t.submit=ie,t.SubmissionError=oe,t.touch=ue,t.unregisterField=ae,t.untouch=se,t.values=ce},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default="undefined"!=typeof window&&window.navigator&&window.navigator.product&&"ReactNative"===window.navigator.product},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),i=function(e){return e&&e.__esModule?e:{default:e}}(n),o=i.default.any,u=i.default.bool,a=i.default.func,s=i.default.shape,c=i.default.string,f=i.default.oneOfType,l=i.default.object;t.default={anyTouched:u.isRequired,asyncValidating:f([u,c]).isRequired,dirty:u.isRequired,error:o,form:c.isRequired,invalid:u.isRequired,initialized:u.isRequired,initialValues:l,pristine:u.isRequired,pure:u.isRequired,submitting:u.isRequired,submitFailed:u.isRequired,submitSucceeded:u.isRequired,valid:u.isRequired,warning:o,array:s({insert:a.isRequired,move:a.isRequired,pop:a.isRequired,push:a.isRequired,remove:a.isRequired,removeAll:a.isRequired,shift:a.isRequired,splice:a.isRequired,swap:a.isRequired,unshift:a.isRequired}),asyncValidate:a.isRequired,autofill:a.isRequired,blur:a.isRequired,change:a.isRequired,clearAsyncError:a.isRequired,destroy:a.isRequired,dispatch:a.isRequired,handleSubmit:a.isRequired,initialize:a.isRequired,reset:a.isRequired,touch:a.isRequired,submit:a.isRequired,untouch:a.isRequired,triggerSubmit:u,clearSubmit:a.isRequired}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var u=r(11),a=r(52),s=n(a),c=r(1),f=n(c),l=function(e){return e&&e.type&&e.type.length>u.prefix.length&&e.type.substring(0,u.prefix.length)===u.prefix};t.default=function(e){function t(e){return e.plugin=function(e){var r=this;return t(function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(e).reduce(function(r,i){var o=c(r,i),u=e[i](o,n,c(t,i));return u===o?r:d(r,i,u)},r(t,n))})},e}var r,n=e.deepEqual,a=e.empty,c=e.getIn,d=e.setIn,p=e.deleteIn,y=e.fromJS,v=e.keys,m=e.size,h=e.splice,b=(0,s.default)(e),g=function(e,t,r,n,i,o,u){var a=c(e,t+"."+r);return a||u?d(e,t+"."+r,h(a,n,i,o)):e},_=function(e,t,r,n,i,o,u){var a=c(e,t),s=f.default.getIn(a,r);return s||u?d(e,t,f.default.setIn(a,r,f.default.splice(s,n,i,o))):e},O=["values","fields","submitErrors","asyncErrors"],S=function(e,t,r,n,i){var o=e,u=null!=i?a:void 0;return o=g(o,"values",t,r,n,i,!0),o=g(o,"fields",t,r,n,u),o=_(o,"syncErrors",t,r,n,void 0),o=_(o,"syncWarnings",t,r,n,void 0),o=g(o,"submitErrors",t,r,n,void 0),o=g(o,"asyncErrors",t,r,n,void 0)},E=(r={},i(r,u.ARRAY_INSERT,function(e,t){var r=t.meta;return S(e,r.field,r.index,0,t.payload)}),i(r,u.ARRAY_MOVE,function(e,t){var r=t.meta,n=r.field,i=r.from,o=r.to,u=c(e,"values."+n),a=u?m(u):0,s=e;return a&&O.forEach(function(e){var t=e+"."+n;if(c(s,t)){var r=c(s,t+"["+i+"]");s=d(s,t,h(c(s,t),i,1)),s=d(s,t,h(c(s,t),o,0,r))}}),s}),i(r,u.ARRAY_POP,function(e,t){var r=t.meta.field,n=c(e,"values."+r),i=n?m(n):0;return i?S(e,r,i-1,1):e}),i(r,u.ARRAY_PUSH,function(e,t){var r=t.meta.field,n=t.payload,i=c(e,"values."+r),o=i?m(i):0;return S(e,r,o,0,n)}),i(r,u.ARRAY_REMOVE,function(e,t){var r=t.meta;return S(e,r.field,r.index,1)}),i(r,u.ARRAY_REMOVE_ALL,function(e,t){var r=t.meta.field,n=c(e,"values."+r),i=n?m(n):0;return i?S(e,r,0,i):e}),i(r,u.ARRAY_SHIFT,function(e,t){return S(e,t.meta.field,0,1)}),i(r,u.ARRAY_SPLICE,function(e,t){var r=t.meta;return S(e,r.field,r.index,r.removeNum,t.payload)}),i(r,u.ARRAY_SWAP,function(e,t){var r=t.meta,n=r.field,i=r.indexA,o=r.indexB,u=e;return O.forEach(function(e){var t=c(u,e+"."+n+"["+i+"]"),r=c(u,e+"."+n+"["+o+"]");void 0===t&&void 0===r||(u=d(u,e+"."+n+"["+i+"]",r),u=d(u,e+"."+n+"["+o+"]",t))}),u}),i(r,u.ARRAY_UNSHIFT,function(e,t){return S(e,t.meta.field,0,0,t.payload)}),i(r,u.AUTOFILL,function(e,t){var r=t.meta.field,n=t.payload,i=e;return i=b(i,"asyncErrors."+r),i=b(i,"submitErrors."+r),i=d(i,"fields."+r+".autofilled",!0),i=d(i,"values."+r,n)}),i(r,u.BLUR,function(e,t){var r=t.meta,n=r.field,i=r.touch,o=t.payload,u=e;return void 0===c(u,"initial."+n)&&""===o?u=b(u,"values."+n):void 0!==o&&(u=d(u,"values."+n,o)),n===c(u,"active")&&(u=p(u,"active")),u=p(u,"fields."+n+".active"),i&&(u=d(u,"fields."+n+".touched",!0),u=d(u,"anyTouched",!0)),u}),i(r,u.CHANGE,function(e,t){var r=t.meta,n=r.field,i=r.touch,o=r.persistentSubmitErrors,u=t.payload,a=e;return void 0===c(a,"initial."+n)&&""===u?a=b(a,"values."+n):void 0!==u&&(a=d(a,"values."+n,u)),a=b(a,"asyncErrors."+n),o||(a=b(a,"submitErrors."+n)),a=b(a,"fields."+n+".autofilled"),i&&(a=d(a,"fields."+n+".touched",!0),a=d(a,"anyTouched",!0)),a}),i(r,u.CLEAR_SUBMIT,function(e){return p(e,"triggerSubmit")}),i(r,u.CLEAR_SUBMIT_ERRORS,function(e){return b(e,"submitErrors")}),i(r,u.CLEAR_ASYNC_ERROR,function(e,t){return p(e,"asyncErrors."+t.meta.field)}),i(r,u.FOCUS,function(e,t){var r=t.meta.field,n=e,i=c(e,"active");return n=p(n,"fields."+i+".active"),n=d(n,"fields."+r+".visited",!0),n=d(n,"fields."+r+".active",!0),n=d(n,"active",r)}),i(r,u.INITIALIZE,function(e,t){var r=t.payload,i=t.meta,o=i.keepDirty,u=i.keepSubmitSucceeded,s=y(r),f=a,l=c(e,"warning");l&&(f=d(f,"warning",l));var p=c(e,"syncWarnings");p&&(f=d(f,"syncWarnings",p));var m=c(e,"error");m&&(f=d(f,"error",m));var h=c(e,"syncErrors");h&&(f=d(f,"syncErrors",h));var b=c(e,"registeredFields");b&&(f=d(f,"registeredFields",b));var g=s;if(o&&b){var _=c(e,"values"),O=c(e,"initial");v(b).forEach(function(e){var t=c(O,e),r=c(_,e);n(r,t)||(g=d(g,e,r))})}return u&&c(e,"submitSucceeded")&&(f=d(f,"submitSucceeded",!0)),f=d(f,"values",g),f=d(f,"initial",s)}),i(r,u.REGISTER_FIELD,function(e,t){var r=t.payload,n=r.name,i=r.type,o="registeredFields['"+n+"']",u=c(e,o);if(u){var a=c(u,"count")+1;u=d(u,"count",a)}else u=y({name:n,type:i,count:1});return d(e,o,u)}),i(r,u.RESET,function(e){var t=a,r=c(e,"registeredFields");r&&(t=d(t,"registeredFields",r));var n=c(e,"initial");return n&&(t=d(t,"values",n),t=d(t,"initial",n)),t}),i(r,u.SUBMIT,function(e){return d(e,"triggerSubmit",!0)}),i(r,u.START_ASYNC_VALIDATION,function(e,t){return d(e,"asyncValidating",t.meta.field||!0)}),i(r,u.START_SUBMIT,function(e){return d(e,"submitting",!0)}),i(r,u.STOP_ASYNC_VALIDATION,function(e,t){var r=t.payload,n=e;if(n=p(n,"asyncValidating"),r&&Object.keys(r).length){var i=r._error,u=o(r,["_error"]);i&&(n=d(n,"error",i)),n=Object.keys(u).length?d(n,"asyncErrors",y(u)):p(n,"asyncErrors")}else n=p(n,"error"),n=p(n,"asyncErrors");return n}),i(r,u.STOP_SUBMIT,function(e,t){var r=t.payload,n=e;if(n=p(n,"submitting"),n=p(n,"submitFailed"),n=p(n,"submitSucceeded"),r&&Object.keys(r).length){var i=r._error,u=o(r,["_error"]);n=i?d(n,"error",i):p(n,"error"),n=Object.keys(u).length?d(n,"submitErrors",y(u)):p(n,"submitErrors"),n=d(n,"submitFailed",!0)}else n=d(n,"submitSucceeded",!0),n=p(n,"error"),n=p(n,"submitErrors");return n}),i(r,u.SET_SUBMIT_FAILED,function(e,t){var r=t.meta.fields,n=e;return n=d(n,"submitFailed",!0),n=p(n,"submitSucceeded"),n=p(n,"submitting"),r.forEach(function(e){return n=d(n,"fields."+e+".touched",!0)}),r.length&&(n=d(n,"anyTouched",!0)),n}),i(r,u.SET_SUBMIT_SUCCEEDED,function(e){var t=e;return t=p(t,"submitFailed"),t=d(t,"submitSucceeded",!0)}),i(r,u.TOUCH,function(e,t){var r=t.meta.fields,n=e;return r.forEach(function(e){return n=d(n,"fields."+e+".touched",!0)}),n=d(n,"anyTouched",!0)}),i(r,u.UNREGISTER_FIELD,function(e,t){var r=t.payload,i=r.name,o=r.destroyOnUnmount,u=e,s="registeredFields['"+i+"']",f=c(u,s);if(!f)return u;var l=c(f,"count")-1;return 0>=l&&o?(u=p(u,s),n(c(u,"registeredFields"),a)&&(u=p(u,"registeredFields"))):(f=d(f,"count",l),u=d(u,s,f)),u}),i(r,u.UNTOUCH,function(e,t){var r=t.meta.fields,n=e;r.forEach(function(e){return n=p(n,"fields."+e+".touched")});var i=v(c(n,"registeredFields")).some(function(e){return c(n,"fields."+e+".touched")});return n=i?d(n,"anyTouched",!0):p(n,"anyTouched")}),i(r,u.UPDATE_SYNC_ERRORS,function(e,t){var r=t.payload,n=r.syncErrors,i=r.error,o=e;return i?(o=d(o,"error",i),o=d(o,"syncError",!0)):(o=p(o,"error"),o=p(o,"syncError")),o=Object.keys(n).length?d(o,"syncErrors",n):p(o,"syncErrors")}),i(r,u.UPDATE_SYNC_WARNINGS,function(e,t){var r=t.payload,n=r.syncWarnings,i=r.warning,o=e;return o=i?d(o,"warning",i):p(o,"warning"),o=Object.keys(n).length?d(o,"syncWarnings",n):p(o,"syncWarnings")}),r),R=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a,t=arguments[1],r=E[t.type];return r?r(e,t):e};return t(function(e){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r&&r.meta&&r.meta.form;if(!n||!l(r))return t;if(r.type===u.DESTROY)return r.meta.form.reduce(function(e,t){return b(e,t)},t);var i=c(t,n),o=e(i,r);return o===i?t:d(t,n,o)}}(R))}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 a(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 s(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var c=r(140),f=n(c),l=r(37),d=n(l),p=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),y=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m=r(88),h=n(m),b=r(13),g=n(b),_=r(2),O=r(0),S=n(O),E=r(3),R=r(38),F=r(18),A=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(F),j=r(48),w=n(j),x=r(50),P=n(x),I=r(51),T=n(I),k=r(22),C=n(k),M=r(54),V=n(M),U=r(56),N=n(U),D=r(57),W=n(D),q=r(12),L=n(q),Y=r(1),z=n(Y),B=r(83),H=n(B),G=function(e){return!(!e||!e.prototype||"object"!==v(e.prototype.isReactComponent))},K=A.arrayInsert,J=A.arrayMove,Z=A.arrayPop,$=A.arrayPush,Q=A.arrayRemove,X=A.arrayRemoveAll,ee=A.arrayShift,te=A.arraySplice,re=A.arraySwap,ne=A.arrayUnshift,ie=A.blur,oe=A.change,ue=A.focus,ae=s(A,["arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","blur","change","focus"]),se={arrayInsert:K,arrayMove:J,arrayPop:Z,arrayPush:$,arrayRemove:Q,arrayRemoveAll:X,arrayShift:ee,arraySplice:te,arraySwap:re,arrayUnshift:ne},ce=[].concat(function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}(Object.keys(A)),["array","asyncErrors","initialized","initialValues","syncErrors","syncWarnings","values","registeredFields"]),fe=function(e){if(!e||"function"!=typeof e)throw Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");return e};t.default=function(e){var t=e.deepEqual,r=e.empty,n=e.getIn,c=e.setIn,l=e.keys,v=e.fromJS,m=(0,L.default)(e);return function(b){var O=y({touchOnBlur:!0,touchOnChange:!1,persistentSubmitErrors:!1,destroyOnUnmount:!0,shouldAsyncValidate:P.default,shouldValidate:T.default,enableReinitialize:!1,keepDirtyOnReinitialize:!1,getFormState:function(e){return n(e,"form")},pure:!0,forceUnregisterOnUnmount:!1},b);return function(b){var F=function(r){function d(e){o(this,d);var t=u(this,(d.__proto__||Object.getPrototypeOf(d)).call(this,e));return t.submit=t.submit.bind(t),t.reset=t.reset.bind(t),t.asyncValidate=t.asyncValidate.bind(t),t.getValues=t.getValues.bind(t),t.register=t.register.bind(t),t.unregister=t.unregister.bind(t),t.submitCompleted=t.submitCompleted.bind(t),t.submitFailed=t.submitFailed.bind(t),t.fieldValidators={},t.lastFieldValidatorKeys=[],t.fieldWarners={},t.lastFieldWarnerKeys=[],t}return a(d,r),p(d,[{key:"getChildContext",value:function(){var e=this;return{_reduxForm:y({},this.props,{getFormState:function(t){return n(e.props.getFormState(t),e.props.form)},asyncValidate:this.asyncValidate,getValues:this.getValues,sectionPrefix:void 0,register:this.register,unregister:this.unregister,registerInnerOnSubmit:function(t){return e.innerOnSubmit=t}})}}},{key:"initIfNeeded",value:function(e){var r=this.props.enableReinitialize;if(e){if((r||!e.initialized)&&!t(this.props.initialValues,e.initialValues)){var n=e.initialized&&this.props.keepDirtyOnReinitialize;this.props.initialize(e.initialValues,n)}}else!this.props.initialValues||this.props.initialized&&!r||this.props.initialize(this.props.initialValues,this.props.keepDirtyOnReinitialize)}},{key:"updateSyncErrorsIfNeeded",value:function(e,t){var r=this.props,n=r.error,i=r.updateSyncErrors,o=!(this.lastSyncErrors&&Object.keys(this.lastSyncErrors).length||n),u=!(e&&Object.keys(e).length||t);o&&u||z.default.deepEqual(this.lastSyncErrors,e)&&z.default.deepEqual(n,t)||(this.lastSyncErrors=e,i(e,t))}},{key:"clearSubmitPromiseIfNeeded",value:function(e){var t=this.props.submitting;this.submitPromise&&t&&!e.submitting&&delete this.submitPromise}},{key:"submitIfNeeded",value:function(e){var t=this.props,r=t.clearSubmit;!t.triggerSubmit&&e.triggerSubmit&&(r(),this.submit())}},{key:"validateIfNeeded",value:function(t){var r=this.props,n=r.shouldValidate,i=r.validate,o=r.values,u=this.generateValidator();if(i||u){var a=void 0===t,c=Object.keys(this.getValidators());if(n({values:o,nextProps:t,props:this.props,initialRender:a,lastFieldValidatorKeys:this.lastFieldValidatorKeys,fieldValidatorKeys:c,structure:e})){var l=a?this.props:t,d=(0,f.default)(i?i(l.values,l)||{}:{},u?u(l.values,l)||{}:{}),p=d._error,y=s(d,["_error"]);this.lastFieldValidatorKeys=c,this.updateSyncErrorsIfNeeded(y,p)}}}},{key:"updateSyncWarningsIfNeeded",value:function(e,t){var r=this.props,n=r.warning,i=r.syncWarnings,o=r.updateSyncWarnings,u=!(i&&Object.keys(i).length||n),a=!(e&&Object.keys(e).length||t);u&&a||z.default.deepEqual(i,e)&&z.default.deepEqual(n,t)||o(e,t)}},{key:"warnIfNeeded",value:function(t){var r=this.props,n=r.shouldValidate,i=r.warn,o=r.values,u=this.generateWarner();if(i||u){var a=void 0===t,c=Object.keys(this.getWarners());if(n({values:o,nextProps:t,props:this.props,initialRender:a,lastFieldValidatorKeys:this.lastFieldWarnerKeys,fieldValidatorKeys:c,structure:e})){var l=a?this.props:t,d=(0,f.default)(i?i(l.values,l):{},u?u(l.values,l):{}),p=d._warning,y=s(d,["_warning"]);this.lastFieldWarnerKeys=c,this.updateSyncWarningsIfNeeded(y,p)}}}},{key:"componentWillMount",value:function(){this.initIfNeeded(),this.validateIfNeeded(),this.warnIfNeeded()}},{key:"componentWillReceiveProps",value:function(e){this.initIfNeeded(e),this.validateIfNeeded(e),this.warnIfNeeded(e),this.clearSubmitPromiseIfNeeded(e),this.submitIfNeeded(e),e.onChange&&(t(e.values,this.props.values)||e.onChange(e.values,e.dispatch,e))}},{key:"shouldComponentUpdate",value:function(e){var r=this;return!this.props.pure||Object.keys(e).some(function(n){return!~ce.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"componentWillUnmount",value:function(){var e=this.props,t=e.destroyOnUnmount,r=e.destroy;t&&(this.destroyed=!0,r())}},{key:"getValues",value:function(){return this.props.values}},{key:"isValid",value:function(){return this.props.valid}},{key:"isPristine",value:function(){return this.props.pristine}},{key:"register",value:function(e,t,r,n){this.props.registerField(e,t),r&&(this.fieldValidators[e]=r),n&&(this.fieldWarners[e]=n)}},{key:"unregister",value:function(e){this.destroyed||(this.props.destroyOnUnmount||this.props.forceUnregisterOnUnmount?(this.props.unregisterField(e),delete this.fieldValidators[e],delete this.fieldWarners[e]):this.props.unregisterField(e,!1))}},{key:"getFieldList",value:function(e){var t=this.props.registeredFields,r=[];if(!t)return r;var i=l(t);return e&&e.excludeFieldArray&&(i=i.filter(function(e){return"FieldArray"!==n(t,"['"+e+"'].type")})),v(i.reduce(function(e,t){return e.push(t),e},r))}},{key:"getValidators",value:function(){var e=this,t={};return Object.keys(this.fieldValidators).forEach(function(r){var n=e.fieldValidators[r]();n&&(t[r]=n)}),t}},{key:"generateValidator",value:function(){var t=this.getValidators();return Object.keys(t).length?(0,N.default)(t,e):void 0}},{key:"getWarners",value:function(){var e=this,t={};return Object.keys(this.fieldWarners).forEach(function(r){var n=e.fieldWarners[r]();n&&(t[r]=n)}),t}},{key:"generateWarner",value:function(){var t=this.getWarners();return Object.keys(t).length?(0,N.default)(t,e):void 0}},{key:"asyncValidate",value:function(e,t){var r=this,i=this.props,o=i.asyncBlurFields,u=i.asyncErrors,a=i.asyncValidate,s=i.dispatch,f=i.initialized,l=i.pristine,d=i.shouldAsyncValidate,p=i.startAsyncValidation,y=i.stopAsyncValidation,v=i.syncErrors,m=i.values,h=!e;if(a){var b=h?m:c(m,e,t),g=h||!n(v,e);if((!h&&(!o||~o.indexOf(e.replace(/\[[0-9]+\]/g,"[]")))||h)&&d({asyncErrors:u,initialized:f,trigger:h?"submit":"blur",blurredField:e,pristine:l,syncValidationPasses:g}))return(0,w.default)(function(){return a(b,s,r.props,e)},p,y,e)}}},{key:"submitCompleted",value:function(e){return delete this.submitPromise,e}},{key:"submitFailed",value:function(e){throw delete this.submitPromise,e}},{key:"listenToSubmit",value:function(e){return(0,g.default)(e)?(this.submitPromise=e,e.then(this.submitCompleted,this.submitFailed)):e}},{key:"submit",value:function(e){var t=this,r=this.props,n=r.onSubmit,i=r.blur,o=r.change,u=r.dispatch;return e&&!(0,C.default)(e)?(0,V.default)(function(){return!t.submitPromise&&t.listenToSubmit((0,W.default)(fe(e),y({},t.props,(0,R.bindActionCreators)({blur:i,change:o},u)),t.props.validExceptSubmit,t.asyncValidate,t.getFieldList({excludeFieldArray:!0})))}):this.submitPromise?void 0:this.innerOnSubmit?this.innerOnSubmit():this.listenToSubmit((0,W.default)(fe(n),y({},this.props,(0,R.bindActionCreators)({blur:i,change:o},u)),this.props.validExceptSubmit,this.asyncValidate,this.getFieldList({excludeFieldArray:!0})))}},{key:"reset",value:function(){this.props.reset()}},{key:"render",value:function(){var e=this.props,t=e.anyTouched,r=e.asyncValidating,n=e.blur,o=e.change,u=e.destroy,a=e.dirty,c=e.dispatch,f=e.error,l=e.form,d=e.initialize,p=e.initialized,v=e.initialValues,m=e.invalid,h=e.pristine,g=e.propNamespace,O=e.reset,S=e.submitting,E=e.submitFailed,F=e.submitSucceeded,A=e.touch,j=e.untouch,w=e.valid,x=e.warning,P=s(e,["anyTouched","arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncErrors","asyncValidate","asyncValidating","blur","change","destroy","destroyOnUnmount","forceUnregisterOnUnmount","dirty","dispatch","enableReinitialize","error","focus","form","getFormState","initialize","initialized","initialValues","invalid","keepDirtyOnReinitialize","pristine","propNamespace","registeredFields","registerField","reset","setSubmitFailed","setSubmitSucceeded","shouldAsyncValidate","shouldValidate","startAsyncValidation","startSubmit","stopAsyncValidation","stopSubmit","submitting","submitFailed","submitSucceeded","touch","touchOnBlur","touchOnChange","persistentSubmitErrors","syncErrors","syncWarnings","unregisterField","untouch","updateSyncErrors","updateSyncWarnings","valid","validExceptSubmit","values","warning"]),I=y({anyTouched:t,asyncValidate:this.asyncValidate,asyncValidating:r},(0,R.bindActionCreators)({blur:n,change:o},c),{destroy:u,dirty:a,dispatch:c,error:f,form:l,handleSubmit:this.submit,initialize:d,initialized:p,initialValues:v,invalid:m,pristine:h,reset:O,submitting:S,submitFailed:E,submitSucceeded:F,touch:A,untouch:j,valid:w,warning:x}),T=y({},g?i({},g,I):I,P);return G(b)&&(T.ref="wrapped"),(0,_.createElement)(b,T)}}]),d}(_.Component);F.displayName="Form("+(0,H.default)(b)+")",F.WrappedComponent=b,F.childContextTypes={_reduxForm:S.default.object.isRequired},F.propTypes={destroyOnUnmount:S.default.bool,forceUnregisterOnUnmount:S.default.bool,form:S.default.string.isRequired,initialValues:S.default.object,getFormState:S.default.func,onSubmitFail:S.default.func,onSubmitSuccess:S.default.func,propNameSpace:S.default.string,validate:S.default.func,warn:S.default.func,touchOnBlur:S.default.bool,touchOnChange:S.default.bool,triggerSubmit:S.default.bool,persistentSubmitErrors:S.default.bool,registeredFields:S.default.any};var A=(0,E.connect)(function(e,i){var o=i.form,u=i.getFormState,a=i.initialValues,s=i.enableReinitialize,c=i.keepDirtyOnReinitialize,f=n(u(e)||r,o)||r,l=n(f,"initial"),d=!!l,p=s&&d&&!t(a,l),y=p&&!c,v=a||l||r;p&&(v=l||r);var h=n(f,"values")||v;y&&(h=v);var b=y||t(v,h),g=n(f,"asyncErrors"),_=n(f,"syncErrors")||{},O=n(f,"syncWarnings")||{},S=n(f,"registeredFields"),E=m(o,u,!1)(e),R=m(o,u,!0)(e),F=!!n(f,"anyTouched"),A=!!n(f,"submitting"),j=!!n(f,"submitFailed"),w=!!n(f,"submitSucceeded"),x=n(f,"error"),P=n(f,"warning"),I=n(f,"triggerSubmit");return{anyTouched:F,asyncErrors:g,asyncValidating:n(f,"asyncValidating")||!1,dirty:!b,error:x,initialized:d,invalid:!E,pristine:b,registeredFields:S,submitting:A,submitFailed:j,submitSucceeded:w,syncErrors:_,syncWarnings:O,triggerSubmit:I,values:h,valid:E,validExceptSubmit:R,warning:P}},function(e,t){var r=function(e){return e.bind(null,t.form)},n=(0,d.default)(ae,r),i=(0,d.default)(se,r),o=function(e,r){return ie(t.form,e,r,!!t.touchOnBlur)},u=function(e,r){return oe(t.form,e,r,!!t.touchOnChange,!!t.persistentSubmitErrors)},a=r(ue),s=(0,R.bindActionCreators)(n,e),c={insert:(0,R.bindActionCreators)(i.arrayInsert,e),move:(0,R.bindActionCreators)(i.arrayMove,e),pop:(0,R.bindActionCreators)(i.arrayPop,e),push:(0,R.bindActionCreators)(i.arrayPush,e),remove:(0,R.bindActionCreators)(i.arrayRemove,e),removeAll:(0,R.bindActionCreators)(i.arrayRemoveAll,e),shift:(0,R.bindActionCreators)(i.arrayShift,e),splice:(0,R.bindActionCreators)(i.arraySplice,e),swap:(0,R.bindActionCreators)(i.arraySwap,e),unshift:(0,R.bindActionCreators)(i.arrayUnshift,e)},f=y({},s,i,{blur:o,change:u,array:c,focus:a,dispatch:e});return function(){return f}},void 0,{withRef:!0}),j=(0,h.default)(A(F),b);return j.defaultProps=O,function(e){function t(){return o(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),p(t,[{key:"submit",value:function(){return this.refs.wrapped.getWrappedInstance().submit()}},{key:"reset",value:function(){return this.refs.wrapped.getWrappedInstance().reset()}},{key:"render",value:function(){var e=this.props,t=e.initialValues,r=s(e,["initialValues"]);return(0,_.createElement)(j,y({},r,{ref:"wrapped",initialValues:v(t)}))}},{key:"valid",get:function(){return this.refs.wrapped.getWrappedInstance().isValid()}},{key:"invalid",get:function(){return!this.valid}},{key:"pristine",get:function(){return this.refs.wrapped.getWrappedInstance().isPristine()}},{key:"dirty",get:function(){return!this.pristine}},{key:"values",get:function(){return this.refs.wrapped.getWrappedInstance().getValues()}},{key:"fieldList",get:function(){return this.refs.wrapped.getWrappedInstance().getFieldList()}},{key:"wrappedInstance",get:function(){return this.refs.wrapped.getWrappedInstance().refs.wrapped}}]),t}(_.Component)}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){return t(r(n),e+".asyncErrors")}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){return t(r(n),e+".initial")}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn,r=e.keys;return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(e){return t(e,"form")};return function(t){return r(e(t))}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){return t(r(n),e+".submitErrors")}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){return t(r(n),e+".syncErrors")}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){return t(r(n),e+".syncWarnings")}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){return t(r(n),e+".values")}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){var i=r(n);return t(i,e+".submitFailed")||!1}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){var i=r(n);return t(i,e+".submitSucceeded")||!1}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(23),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){return function(t,r){var n=(0,i.default)(e)(t,r);return function(e){return!n(e)}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(12),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){return function(t,r){var n=(0,i.default)(e)(t,r);return function(e){return!n(e)}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(n){var i=r(n);return t(i,e+".submitting")||!1}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(33),i=function(e){return e&&e.__esModule?e:{default:e}}(n),o=function(e,t){return e===t||(!(null!=e&&""!==e&&!1!==e||null!=t&&""!==t&&!1!==t)||(!e||!t||e._error===t._error)&&((!e||!t||e._warning===t._warning)&&void 0))};t.default=function(e,t){return(0,i.default)(e,t,o)}},function(e,t,r){"use strict";function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var o=r(10),u=function(e){return e&&e.__esModule?e:{default:e}}(o),a=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function e(t,r){for(var o=arguments.length,u=Array(o>2?o-2:0),s=2;o>s;s++)u[s-2]=arguments[s];if(void 0===t||void 0===r)return t;if(u.length){if(Array.isArray(t)){if(t.length>r){var c=e.apply(void 0,[t&&t[r]].concat(u));if(c!==t[r]){var f=[].concat(i(t));return f[r]=c,f}}return t}if(r in t){var l=e.apply(void 0,[t&&t[r]].concat(u));return t[r]===l?t:a({},t,n({},r,l))}return t}if(Array.isArray(t)){if(isNaN(r))throw Error("Cannot delete non-numerical index from an array");if(t.length>r){var d=[].concat(i(t));return d.splice(r,1),d}return t}if(r in t){var p=a({},t);return delete p[r],p}return t};t.default=function(e,t){return s.apply(void 0,[e].concat(i((0,u.default)(t))))}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(10),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e,t){if(!e)return e;var r=(0,i.default)(t),n=r.length;if(n){for(var o=e,u=0;n>u&&o;++u)o=o[r[u]];return o}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e?Object.keys(e):[]}},function(e,t,r){"use strict";function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var i=r(10),o=function(e){return e&&e.__esModule?e:{default:e}}(i),u=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=function e(t,r,i,o){if(o>=i.length)return r;var a=i[o],s=e(t&&t[a],r,i,o+1);if(!t){var c=isNaN(a)?{}:[];return c[a]=s,c}if(Array.isArray(t)){var f=[].concat(t);return f[a]=s,f}return u({},t,n({},a,s))};t.default=function(e,t,r){return a(e,r,(0,o.default)(t),0)}},function(e,t,r){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r,i){if(e=e||[],e.length>t){if(void 0===i&&!r){var o=[].concat(n(e));return o.splice(t,0,null),o[t]=void 0,o}if(null!=i){var u=[].concat(n(e));return u.splice(t,r,i),u}var a=[].concat(n(e));return a.splice(t,r),a}if(r)return e;var s=[].concat(n(e));return s[t]=i,s}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.dataKey="text"},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e.displayName||e.name||"Component"}},function(e,t,r){"use strict";function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},o=r(3);t.default=function(e){var t=e.getIn;return function(e){var r=i({prop:"values",getFormState:function(e){return t(e,"form")}},e),u=r.form,a=r.prop,s=r.getFormState;return(0,o.connect)(function(e){return n({},a,t(s(e),u+".values"))},function(){return{}})}}},function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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 o(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)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";n(this,t);var r=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return Object.defineProperty(r,"message",{configurable:!0,enumerable:!1,value:e,writable:!0}),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:r.constructor.name,writable:!0}),Error.hasOwnProperty("captureStackTrace")?(Error.captureStackTrace(r,r.constructor),i(r)):(Object.defineProperty(r,"stack",{configurable:!0,enumerable:!1,value:Error(e).stack,writable:!0}),r)}return o(t,e),t}(function(e){function t(){e.apply(this,arguments)}return t.prototype=Object.create(e.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e,t}(Error)),e.exports=t.default},function(e,t,r){"use strict";function n(e){return function(){return e}}var i=function(){};i.thatReturns=n,i.thatReturnsFalse=n(!1),i.thatReturnsTrue=n(!0),i.thatReturnsNull=n(null),i.thatReturnsThis=function(){return this},i.thatReturnsArgument=function(e){return e},e.exports=i},function(e,t,r){"use strict";function n(e,t,r,n,o,u,a,s){if(i(t),!e){var c;if(void 0===t)c=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var f=[r,n,o,u,a,s],l=0;c=Error(t.replace(/%s/g,function(){return f[l++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}}var i=function(e){};e.exports=n},function(e,t,r){"use strict";var n={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},i={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,r){if("string"!=typeof t){var u=Object.getOwnPropertyNames(t);o&&(u=u.concat(Object.getOwnPropertySymbols(t)));for(var a=0;u.length>a;++a)if(!(n[u[a]]||i[u[a]]||r&&r[u[a]]))try{e[u[a]]=t[u[a]]}catch(e){}}return e}},function(e,t,r){function n(){if(!arguments.length)return[];var e=arguments[0];return i(e)?e:[e]}var i=r(8);e.exports=n},function(e,t,r){e.exports=r(31).Uint8Array},function(e,t){function r(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}e.exports=r},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}e.exports=r},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}e.exports=r},function(e,t,r){function n(e,t,r){var n=e[t];a.call(e,t)&&o(n,r)&&(void 0!==r||t in e)||i(e,t,r)}var i=r(7),o=r(15),u=Object.prototype,a=u.hasOwnProperty;e.exports=n},function(e,t,r){var n=r(9),i=Object.create;e.exports=function(){function e(){}return function(t){if(!n(t))return{};if(i)return i(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}()},function(e,t,r){function n(e,t){return e&&i(e,t,o)}var i=r(27),o=r(139);e.exports=n},function(e,t){function r(e,t,r){for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1}e.exports=r},function(e,t,r){function n(e,t,r,u,a){return e===t||(null==e||null==t||!o(e)&&!o(t)?e!==e&&t!==t:i(e,t,r,u,n,a))}var i=r(99),o=r(16);e.exports=n},function(e,t,r){function n(e,t,r,n,m,b){var g=c(e),_=c(t),O=g?y:s(e),S=_?y:s(t);O=O==p?v:O,S=S==p?v:S;var E=O==v,R=S==v,F=O==S;if(F&&f(e)){if(!f(t))return!1;g=!0,E=!1}if(F&&!E)return b||(b=new i),g||l(e)?o(e,t,r,n,m,b):u(e,t,O,r,n,m,b);if(!(r&d)){var A=E&&h.call(e,"__wrapped__"),j=R&&h.call(t,"__wrapped__");if(A||j){var w=A?e.value():e,x=j?t.value():t;return b||(b=new i),m(w,x,r,n,b)}}return!!F&&(b||(b=new i),a(e,t,r,n,m,b))}var i=r(25),o=r(112),u=r(113),a=r(114),s=r(118),c=r(8),f=r(32),l=r(35),d=1,p="[object Arguments]",y="[object Array]",v="[object Object]",m=Object.prototype,h=m.hasOwnProperty;e.exports=n},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){function n(e,t,r,f,l){e!==t&&u(t,function(u,c){if(s(u))l||(l=new i),a(e,t,c,r,n,f,l);else{var d=f?f(e[c],u,c+"",e,t,l):void 0;void 0===d&&(d=u),o(e,c,d)}},c)}var i=r(25),o=r(26),u=r(27),a=r(102),s=r(9),c=r(36);e.exports=n},function(e,t,r){function n(e,t,r,n,b,g,_){var O=e[r],S=t[r],E=_.get(S);if(E)return void i(e,r,E);var R=g?g(O,S,r+"",e,t,_):void 0,F=void 0===R;if(F){var A=f(S),j=!A&&d(S),w=!A&&!j&&m(S);R=S,A||j||w?f(O)?R=O:l(O)?R=a(O):j?(F=!1,R=o(S,!0)):w?(F=!1,R=u(S,!0)):R=[]:v(S)||c(S)?(R=O,c(O)?R=h(O):(!y(O)||n&&p(O))&&(R=s(S))):F=!1}F&&(_.set(S,R),b(R,S,n,g,_),_.delete(S)),i(e,r,R)}var i=r(26),o=r(106),u=r(107),a=r(29),s=r(119),c=r(133),f=r(8),l=r(135),d=r(32),p=r(34),y=r(9),v=r(137),m=r(35),h=r(141);e.exports=n},function(e,t,r){function n(e,t){return u(o(e,t,i),e+"")}var i=r(132),o=r(128),u=r(129);e.exports=n},function(e,t,r){function n(e,t){return!!(null==e?0:e.length)&&i(e,t,0)>-1}var i=r(97);e.exports=n},function(e,t,r){function n(e){var t=new e.constructor(e.byteLength);return new i(t).set(new i(e)),t}var i=r(90);e.exports=n},function(e,t,r){(function(e){function n(e,t){if(t)return e.slice();var r=e.length,n=c?c(r):new e.constructor(r);return e.copy(n),n}var i=r(31),o="object"==typeof t&&t&&!t.nodeType&&t,u=o&&"object"==typeof e&&e&&!e.nodeType&&e,a=u&&u.exports===o,s=a?i.Buffer:void 0,c=s?s.allocUnsafe:void 0;e.exports=n}).call(t,r(145)(e))},function(e,t,r){function n(e,t){return new e.constructor(t?i(e.buffer):e.buffer,e.byteOffset,e.length)}var i=r(105);e.exports=n},function(e,t,r){function n(e,t,r,n){var u=!r;r||(r={});for(var a=-1,s=t.length;++a<s;){var c=t[a],f=n?n(r[c],e[c],c,r,e):void 0;void 0===f&&(f=e[c]),u?o(r,c,f):i(r,c,f)}return r}var i=r(94),o=r(7);e.exports=n},function(e,t,r){function n(e){return i(function(t,r){var n=-1,i=r.length,u=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(u=e.length>3&&"function"==typeof u?(i--,u):void 0,a&&o(r[0],r[1],a)&&(u=3>i?void 0:u,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,u)}return t})}var i=r(103),o=r(120);e.exports=n},function(e,t){function r(e){return function(t,r,n){for(var i=-1,o=Object(t),u=n(t),a=u.length;a--;){var s=u[e?a:++i];if(!1===r(o[s],s,o))break}return t}}e.exports=r},function(e,t,r){var n=r(117);e.exports=function(){try{var e=n(Object,"defineProperty");return e({},"",{}),e}catch(e){}}()},function(e,t,r){function n(e,t,r,n,c,f){var l=r&a,d=e.length,p=t.length;if(!(d==p||l&&p>d))return!1;var y=f.get(e);if(y&&f.get(t))return y==t;var v=-1,m=!0,h=r&s?new i:void 0;for(f.set(e,t),f.set(t,e);++v<d;){var b=e[v],g=t[v];if(n)var _=l?n(g,b,v,t,e,f):n(b,g,v,e,t,f);if(void 0!==_){if(_)continue;m=!1;break}if(h){if(!o(t,function(e,t){if(!u(h,t)&&(b===e||c(b,e,r,n,f)))return h.push(t)})){m=!1;break}}else if(b!==g&&!c(b,g,r,n,f)){m=!1;break}}return f.delete(e),f.delete(t),m}var i=r(89),o=r(93),u=r(104),a=1,s=2;e.exports=n},function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},function(e,t,r){function n(e,t,r,n,u,s){var c=r&o,f=i(e),l=f.length;if(l!=i(t).length&&!c)return!1;for(var d=l;d--;){var p=f[d];if(!(c?p in t:a.call(t,p)))return!1}var y=s.get(e);if(y&&s.get(t))return y==t;var v=!0;s.set(e,t),s.set(t,e);for(var m=c;++d<l;){p=f[d];var h=e[p],b=t[p];if(n)var g=c?n(b,h,p,t,e,s):n(h,b,p,e,t,s);if(!(void 0===g?h===b||u(h,b,r,n,s):g)){v=!1;break}m||(m="constructor"==p)}if(v&&!m){var _=e.constructor,O=t.constructor;_!=O&&"constructor"in e&&"constructor"in t&&!("function"==typeof _&&_ instanceof _&&"function"==typeof O&&O instanceof O)&&(v=!1)}return s.delete(e),s.delete(t),v}var i=r(116),o=1,u=Object.prototype,a=u.hasOwnProperty;e.exports=n},function(e,t,r){(function(t){var r="object"==typeof t&&t&&t.Object===Object&&t;e.exports=r}).call(t,r(144))},function(e,t,r){e.exports=r(14)(Object.keys,Object)},function(e,t){function r(e,t){return null==e?void 0:e[t]}e.exports=r},function(e,t){function r(e){return i.call(e)}var n=Object.prototype,i=n.toString;e.exports=r},function(e,t,r){function n(e){return"function"!=typeof e.constructor||u(e)?{}:i(o(e))}var i=r(95),o=r(30),u=r(121);e.exports=n},function(e,t){function r(){return!1}e.exports=r},function(e,t){function r(){return!1}e.exports=r},function(e,t){function r(){this.__data__=[],this.size=0}e.exports=r},function(e,t,r){function n(e){var t=this.__data__,r=i(t,e);return r>=0&&(r==t.length-1?t.pop():u.call(t,r,1),--this.size,!0)}var i=r(6),o=Array.prototype,u=o.splice;e.exports=n},function(e,t,r){function n(e){var t=this.__data__,r=i(t,e);return 0>r?void 0:t[r][1]}var i=r(6);e.exports=n},function(e,t,r){function n(e){return i(this.__data__,e)>-1}var i=r(6);e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__,n=i(r,e);return 0>n?(++this.size,r.push([e,t])):r[n][1]=t,this}var i=r(6);e.exports=n},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){function n(e,t,r){return t=o(void 0===t?e.length-1:t,0),function(){for(var n=arguments,u=-1,a=o(n.length-t,0),s=Array(a);++u<a;)s[u]=n[t+u];u=-1;for(var c=Array(t+1);++u<t;)c[u]=n[u];return c[t]=r(s),i(e,this,c)}}var i=r(91),o=Math.max;e.exports=n},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){var n=/^\./;e.exports=r(127)(function(e){var t=[];return n.test(e)&&t.push(""),e.replace(/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,function(e,r,n,i){t.push(n?i.replace(/\\(\\)?/g,"$1"):r||e)}),t})},function(e,t){function r(e){return e}e.exports=r},function(e,t){function r(e){return e}e.exports=r},function(e,t){function r(){return!1}e.exports=r},function(e,t,r){function n(e){return null!=e&&o(e.length)&&!i(e)}var i=r(34),o=r(136);e.exports=n},function(e,t,r){function n(e){return o(e)&&i(e)}var i=r(134),o=r(16);e.exports=n},function(e,t){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&n>=e}var n=9007199254740991;e.exports=r},function(e,t,r){function n(e){if(!u(e)||i(e)!=a)return!1;var t=o(e);if(null===t)return!0;var r=l.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&f.call(r)==d}var i=r(28),o=r(30),u=r(16),a="[object Object]",s=Function.prototype,c=Object.prototype,f=s.toString,l=c.hasOwnProperty,d=f.call(Object);e.exports=n},function(e,t){function r(){return!1}e.exports=r},function(e,t,r){e.exports=r(14)(Object.keys,Object)},function(e,t,r){var n=r(101);e.exports=r(109)(function(e,t,r){n(e,t,r)})},function(e,t,r){function n(e){return i(e,o(e))}var i=r(108),o=r(36);e.exports=n},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){"use strict";var n=r(86),i=r(87);e.exports=function(){function e(){i(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t};return r.checkPropTypes=n,r.PropTypes=r,r}},function(e,t){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}}])});
import React from 'react'; class SignUp extends React.Component { render() { return ( <div className="row"> <div className="col s2"></div> <form className="col s8"> <div className="row"> <div className="input-field col s12"> <input placeholder="Placeholder" id="first_name" type="text" className="validate"/> <label htmlFor="firstName">First Name</label> </div> <div className="input-field col s12"> <input id="last_name" type="text" className="validate"/> <label for="lastName">Last Name</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="password" type="text" className="validate"/> <label for="username">Username</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="password" type="password" className="validate"/> <label for="password">Password</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="phoneNumber" type="number" className=""/> <label for="phoneNumber">Phone Number</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="email" type="email" className="validate"/> <label for="email">Email</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="websiteURL" type="url" className=""/> <label for="websiteURL">Website URL</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="bio" type="text" className=""/> <label for="bio">Bio (optional)</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="quickIntro" type="text" className="validate"/> <label for="quickIntro">Quick Intro</label> </div> </div> <div className="row"> <div className="col s12"> This is an inline input field: <div className="input-field inline"> <input id="email" type="email" className="validate"/> <label for="email" data-error="wrong" data-success="right">Email</label> </div> </div> </div> </form> <div className="col s2"></div> </div> ); } } export default SignUp;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function __extends(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}var OBFUSCATED_ERROR="An invariant failed, however the error is obfuscated because this is an production build.",EMPTY_ARRAY=[];Object.freeze(EMPTY_ARRAY);var EMPTY_OBJECT={};function getNextId(){return++globalState.mobxGuid}function fail(e){throw invariant(!1,e),"X"}function invariant(e,t){if(!e)throw new Error("[mobx] "+(t||OBFUSCATED_ERROR))}Object.freeze(EMPTY_OBJECT);var deprecatedMessages=[];function deprecated(e,t){return!1}function once(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}var noop=function(){};function unique(e){var t=[];return e.forEach(function(e){-1===t.indexOf(e)&&t.push(e)}),t}function isObject(e){return null!==e&&"object"==typeof e}function isPlainObject(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function addHiddenProp(e,t,r){Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:r})}function addHiddenFinalProp(e,t,r){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:r})}function isPropertyConfigurable(e,t){var r=Object.getOwnPropertyDescriptor(e,t);return!r||!1!==r.configurable&&!1!==r.writable}function createInstanceofPredicate(e,t){var r="isMobX"+e;return t.prototype[r]=!0,function(e){return isObject(e)&&!0===e[r]}}function isArrayLike(e){return Array.isArray(e)||isObservableArray(e)}function isES6Map(e){return e instanceof Map}function isES6Set(e){return e instanceof Set}function getPlainObjectKeys(e){var t=new Set;for(var r in e)t.add(r);return Object.getOwnPropertySymbols(e).forEach(function(r){Object.getOwnPropertyDescriptor(e,r).enumerable&&t.add(r)}),Array.from(t)}function stringifyKey(e){return e&&e.toString?e.toString():new String(e).toString()}function getMapLikeKeys(e){return isPlainObject(e)?Object.keys(e):Array.isArray(e)?e.map(function(e){return __read(e,1)[0]}):isES6Map(e)||isObservableMap(e)?Array.from(e.keys()):fail("Cannot get keys from '"+e+"'")}function toPrimitive(e){return null===e?null:"object"==typeof e?""+e:e}var $mobx=Symbol("mobx administration"),Atom=function(){function e(e){void 0===e&&(e="Atom@"+getNextId()),this.name=e,this.isPendingUnobservation=!1,this.isBeingObserved=!1,this.observers=new Set,this.diffValue=0,this.lastAccessedBy=0,this.lowestObserverState=exports.IDerivationState.NOT_TRACKING}return e.prototype.onBecomeObserved=function(){this.onBecomeObservedListeners&&this.onBecomeObservedListeners.forEach(function(e){return e()})},e.prototype.onBecomeUnobserved=function(){this.onBecomeUnobservedListeners&&this.onBecomeUnobservedListeners.forEach(function(e){return e()})},e.prototype.reportObserved=function(){return reportObserved(this)},e.prototype.reportChanged=function(){startBatch(),propagateChanged(this),endBatch()},e.prototype.toString=function(){return this.name},e}(),isAtom=createInstanceofPredicate("Atom",Atom);function createAtom(e,t,r){void 0===t&&(t=noop),void 0===r&&(r=noop);var n=new Atom(e);return t!==noop&&onBecomeObserved(n,t),r!==noop&&onBecomeUnobserved(n,r),n}function identityComparer(e,t){return e===t}function structuralComparer(e,t){return deepEqual(e,t)}function shallowComparer(e,t){return deepEqual(e,t,1)}function defaultComparer(e,t){return Object.is(e,t)}var comparer={identity:identityComparer,structural:structuralComparer,default:defaultComparer,shallow:shallowComparer},mobxDidRunLazyInitializersSymbol=Symbol("mobx did run lazy initializers"),mobxPendingDecorators=Symbol("mobx pending decorators"),enumerableDescriptorCache={},nonEnumerableDescriptorCache={};function createPropertyInitializerDescriptor(e,t){var r=t?enumerableDescriptorCache:nonEnumerableDescriptorCache;return r[e]||(r[e]={configurable:!0,enumerable:t,get:function(){return initializeInstance(this),this[e]},set:function(t){initializeInstance(this),this[e]=t}})}function initializeInstance(e){if(!0!==e[mobxDidRunLazyInitializersSymbol]){var t=e[mobxPendingDecorators];if(t)for(var r in addHiddenProp(e,mobxDidRunLazyInitializersSymbol,!0),t){var n=t[r];n.propertyCreator(e,n.prop,n.descriptor,n.decoratorTarget,n.decoratorArguments)}}}function createPropDecorator(e,t){return function(){var r,n=function(n,o,a,i){if(!0===i)return t(n,o,a,n,r),null;if(!Object.prototype.hasOwnProperty.call(n,mobxPendingDecorators)){var s=n[mobxPendingDecorators];addHiddenProp(n,mobxPendingDecorators,__assign({},s))}return n[mobxPendingDecorators][o]={prop:o,propertyCreator:t,descriptor:a,decoratorTarget:n,decoratorArguments:r},createPropertyInitializerDescriptor(o,e)};return quacksLikeADecorator(arguments)?(r=EMPTY_ARRAY,n.apply(null,arguments)):(r=Array.prototype.slice.call(arguments),n)}}function quacksLikeADecorator(e){return(2===e.length||3===e.length)&&"string"==typeof e[1]||4===e.length&&!0===e[3]}function deepEnhancer(e,t,r){return isObservable(e)?e:Array.isArray(e)?observable.array(e,{name:r}):isPlainObject(e)?observable.object(e,void 0,{name:r}):isES6Map(e)?observable.map(e,{name:r}):isES6Set(e)?observable.set(e,{name:r}):e}function shallowEnhancer(e,t,r){return null==e?e:isObservableObject(e)||isObservableArray(e)||isObservableMap(e)||isObservableSet(e)?e:Array.isArray(e)?observable.array(e,{name:r,deep:!1}):isPlainObject(e)?observable.object(e,void 0,{name:r,deep:!1}):isES6Map(e)?observable.map(e,{name:r,deep:!1}):isES6Set(e)?observable.set(e,{name:r,deep:!1}):fail(!1)}function referenceEnhancer(e){return e}function refStructEnhancer(e,t,r){return deepEqual(e,t)?t:e}function createDecoratorForEnhancer(e){invariant(e);var t=createPropDecorator(!0,function(t,r,n,o,a){var i=n?n.initializer?n.initializer.call(t):n.value:void 0;asObservableObject(t).addObservableProp(r,i,e)}),r=("undefined"!=typeof process&&process.env,t);return r.enhancer=e,r}var defaultCreateObservableOptions={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function asCreateObservableOptions(e){return null==e?defaultCreateObservableOptions:"string"==typeof e?{name:e,deep:!0,proxy:!0}:e}Object.freeze(defaultCreateObservableOptions);var deepDecorator=createDecoratorForEnhancer(deepEnhancer),shallowDecorator=createDecoratorForEnhancer(shallowEnhancer),refDecorator=createDecoratorForEnhancer(referenceEnhancer),refStructDecorator=createDecoratorForEnhancer(refStructEnhancer);function getEnhancerFromOptions(e){return e.defaultDecorator?e.defaultDecorator.enhancer:!1===e.deep?referenceEnhancer:deepEnhancer}function createObservable(e,t,r){if("string"==typeof arguments[1])return deepDecorator.apply(null,arguments);if(isObservable(e))return e;var n=isPlainObject(e)?observable.object(e,t,r):Array.isArray(e)?observable.array(e,t):isES6Map(e)?observable.map(e,t):isES6Set(e)?observable.set(e,t):e;if(n!==e)return n;fail(!1)}var observableFactories={box:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("box");var r=asCreateObservableOptions(t);return new ObservableValue(e,getEnhancerFromOptions(r),r.name,!0,r.equals)},array:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("array");var r=asCreateObservableOptions(t);return createObservableArray(e,getEnhancerFromOptions(r),r.name)},map:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("map");var r=asCreateObservableOptions(t);return new ObservableMap(e,getEnhancerFromOptions(r),r.name)},set:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("set");var r=asCreateObservableOptions(t);return new ObservableSet(e,getEnhancerFromOptions(r),r.name)},object:function(e,t,r){"string"==typeof arguments[1]&&incorrectlyUsedAsDecorator("object");var n=asCreateObservableOptions(r);if(!1===n.proxy)return extendObservable({},e,t,n);var o=getDefaultDecoratorFromObjectOptions(n),a=createDynamicObservableObject(extendObservable({},void 0,void 0,n));return extendObservableObjectWithProperties(a,e,t,o),a},ref:refDecorator,shallow:shallowDecorator,deep:deepDecorator,struct:refStructDecorator},observable=createObservable;function incorrectlyUsedAsDecorator(e){fail("Expected one or two arguments to observable."+e+". Did you accidentally try to use observable."+e+" as decorator?")}Object.keys(observableFactories).forEach(function(e){return observable[e]=observableFactories[e]});var TraceMode,computedDecorator=createPropDecorator(!1,function(e,t,r,n,o){var a=r.get,i=r.set,s=o[0]||{};asObservableObject(e).addComputedProp(e,t,__assign({get:a,set:i,context:e},s))}),computedStructDecorator=computedDecorator({equals:comparer.structural}),computed=function(e,t,r){if("string"==typeof t)return computedDecorator.apply(null,arguments);if(null!==e&&"object"==typeof e&&1===arguments.length)return computedDecorator.apply(null,arguments);var n="object"==typeof t?t:{};return n.get=e,n.set="function"==typeof t?t:n.set,n.name=n.name||e.name||"",new ComputedValue(n)};computed.struct=computedStructDecorator,function(e){e[e.NOT_TRACKING=-1]="NOT_TRACKING",e[e.UP_TO_DATE=0]="UP_TO_DATE",e[e.POSSIBLY_STALE=1]="POSSIBLY_STALE",e[e.STALE=2]="STALE"}(exports.IDerivationState||(exports.IDerivationState={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(TraceMode||(TraceMode={}));var CaughtException=function(){return function(e){this.cause=e}}();function isCaughtException(e){return e instanceof CaughtException}function shouldCompute(e){switch(e.dependenciesState){case exports.IDerivationState.UP_TO_DATE:return!1;case exports.IDerivationState.NOT_TRACKING:case exports.IDerivationState.STALE:return!0;case exports.IDerivationState.POSSIBLY_STALE:for(var t=untrackedStart(),r=e.observing,n=r.length,o=0;o<n;o++){var a=r[o];if(isComputedValue(a)){if(globalState.disableErrorBoundaries)a.get();else try{a.get()}catch(e){return untrackedEnd(t),!0}if(e.dependenciesState===exports.IDerivationState.STALE)return untrackedEnd(t),!0}}return changeDependenciesStateTo0(e),untrackedEnd(t),!1}}function isComputingDerivation(){return null!==globalState.trackingDerivation}function checkIfStateModificationsAreAllowed(e){var t=e.observers.size>0;globalState.computationDepth>0&&t&&fail(!1),globalState.allowStateChanges||!t&&"strict"!==globalState.enforceActions||fail(!1)}function trackDerivedFunction(e,t,r){var n=allowStateReadsStart(!0);changeDependenciesStateTo0(e),e.newObserving=new Array(e.observing.length+100),e.unboundDepsCount=0,e.runId=++globalState.runId;var o,a=globalState.trackingDerivation;if(globalState.trackingDerivation=e,!0===globalState.disableErrorBoundaries)o=t.call(r);else try{o=t.call(r)}catch(e){o=new CaughtException(e)}return globalState.trackingDerivation=a,bindDependencies(e),warnAboutDerivationWithoutDependencies(e),allowStateReadsEnd(n),o}function warnAboutDerivationWithoutDependencies(e){}function bindDependencies(e){for(var t=e.observing,r=e.observing=e.newObserving,n=exports.IDerivationState.UP_TO_DATE,o=0,a=e.unboundDepsCount,i=0;i<a;i++){0===(s=r[i]).diffValue&&(s.diffValue=1,o!==i&&(r[o]=s),o++),s.dependenciesState>n&&(n=s.dependenciesState)}for(r.length=o,e.newObserving=null,a=t.length;a--;){0===(s=t[a]).diffValue&&removeObserver(s,e),s.diffValue=0}for(;o--;){var s;1===(s=r[o]).diffValue&&(s.diffValue=0,addObserver(s,e))}n!==exports.IDerivationState.UP_TO_DATE&&(e.dependenciesState=n,e.onBecomeStale())}function clearObserving(e){var t=e.observing;e.observing=[];for(var r=t.length;r--;)removeObserver(t[r],e);e.dependenciesState=exports.IDerivationState.NOT_TRACKING}function untracked(e){var t=untrackedStart();try{return e()}finally{untrackedEnd(t)}}function untrackedStart(){var e=globalState.trackingDerivation;return globalState.trackingDerivation=null,e}function untrackedEnd(e){globalState.trackingDerivation=e}function allowStateReadsStart(e){var t=globalState.allowStateReads;return globalState.allowStateReads=e,t}function allowStateReadsEnd(e){globalState.allowStateReads=e}function changeDependenciesStateTo0(e){if(e.dependenciesState!==exports.IDerivationState.UP_TO_DATE){e.dependenciesState=exports.IDerivationState.UP_TO_DATE;for(var t=e.observing,r=t.length;r--;)t[r].lowestObserverState=exports.IDerivationState.UP_TO_DATE}}var currentActionId=0,nextActionId=1;function createAction(e,t,r){var n=function(){return executeAction(e,t,r||this,arguments)};return n.isMobxAction=!0,n}function executeAction(e,t,r,n){var o=_startAction(e,r,n);try{return t.apply(r,n)}catch(e){throw o.error=e,e}finally{_endAction(o)}}function _startAction(e,t,r){var n=isSpyEnabled(),o=untrackedStart();startBatch();var a={prevDerivation:o,prevAllowStateChanges:allowStateChangesStart(!0),prevAllowStateReads:allowStateReadsStart(!0),notifySpy:n,startTime:0,actionId:nextActionId++,parentActionId:currentActionId};return currentActionId=a.actionId,a}function _endAction(e){currentActionId!==e.actionId&&fail("invalid action stack. did you forget to finish an action?"),currentActionId=e.parentActionId,void 0!==e.error&&(globalState.suppressReactionErrors=!0),allowStateChangesEnd(e.prevAllowStateChanges),allowStateReadsEnd(e.prevAllowStateReads),endBatch(),untrackedEnd(e.prevDerivation),e.notifySpy,globalState.suppressReactionErrors=!1}function allowStateChanges(e,t){var r,n=allowStateChangesStart(e);try{r=t()}finally{allowStateChangesEnd(n)}return r}function allowStateChangesStart(e){var t=globalState.allowStateChanges;return globalState.allowStateChanges=e,t}function allowStateChangesEnd(e){globalState.allowStateChanges=e}function allowStateChangesInsideComputed(e){var t,r=globalState.computationDepth;globalState.computationDepth=0;try{t=e()}finally{globalState.computationDepth=r}return t}var ObservableValue=function(e){function t(t,r,n,o,a){void 0===n&&(n="ObservableValue@"+getNextId()),void 0===o&&(o=!0),void 0===a&&(a=comparer.default);var i=e.call(this,n)||this;return i.enhancer=r,i.name=n,i.equals=a,i.hasUnreportedChange=!1,i.value=r(t,void 0,n),o&&isSpyEnabled(),i}return __extends(t,e),t.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},t.prototype.set=function(e){this.value;if((e=this.prepareNewValue(e))!==globalState.UNCHANGED){isSpyEnabled();0,this.setNewValue(e)}},t.prototype.prepareNewValue=function(e){if(checkIfStateModificationsAreAllowed(this),hasInterceptors(this)){var t=interceptChange(this,{object:this,type:"update",newValue:e});if(!t)return globalState.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value,this.name),this.equals(this.value,e)?globalState.UNCHANGED:e},t.prototype.setNewValue=function(e){var t=this.value;this.value=e,this.reportChanged(),hasListeners(this)&&notifyListeners(this,{type:"update",object:this,newValue:e,oldValue:t})},t.prototype.get=function(){return this.reportObserved(),this.dehanceValue(this.value)},t.prototype.intercept=function(e){return registerInterceptor(this,e)},t.prototype.observe=function(e,t){return t&&e({object:this,type:"update",newValue:this.value,oldValue:void 0}),registerListener(this,e)},t.prototype.toJSON=function(){return this.get()},t.prototype.toString=function(){return this.name+"["+this.value+"]"},t.prototype.valueOf=function(){return toPrimitive(this.get())},t.prototype[Symbol.toPrimitive]=function(){return this.valueOf()},t}(Atom),isObservableValue=createInstanceofPredicate("ObservableValue",ObservableValue),ComputedValue=function(){function e(e){this.dependenciesState=exports.IDerivationState.NOT_TRACKING,this.observing=[],this.newObserving=null,this.isBeingObserved=!1,this.isPendingUnobservation=!1,this.observers=new Set,this.diffValue=0,this.runId=0,this.lastAccessedBy=0,this.lowestObserverState=exports.IDerivationState.UP_TO_DATE,this.unboundDepsCount=0,this.__mapid="#"+getNextId(),this.value=new CaughtException(null),this.isComputing=!1,this.isRunningSetter=!1,this.isTracing=TraceMode.NONE,this.derivation=e.get,this.name=e.name||"ComputedValue@"+getNextId(),e.set&&(this.setter=createAction(this.name+"-setter",e.set)),this.equals=e.equals||(e.compareStructural||e.struct?comparer.structural:comparer.default),this.scope=e.context,this.requiresReaction=!!e.requiresReaction,this.keepAlive=!!e.keepAlive}return e.prototype.onBecomeStale=function(){propagateMaybeChanged(this)},e.prototype.onBecomeObserved=function(){this.onBecomeObservedListeners&&this.onBecomeObservedListeners.forEach(function(e){return e()})},e.prototype.onBecomeUnobserved=function(){this.onBecomeUnobservedListeners&&this.onBecomeUnobservedListeners.forEach(function(e){return e()})},e.prototype.get=function(){this.isComputing&&fail("Cycle detected in computation "+this.name+": "+this.derivation),0!==globalState.inBatch||0!==this.observers.size||this.keepAlive?(reportObserved(this),shouldCompute(this)&&this.trackAndCompute()&&propagateChangeConfirmed(this)):shouldCompute(this)&&(this.warnAboutUntrackedRead(),startBatch(),this.value=this.computeValue(!1),endBatch());var e=this.value;if(isCaughtException(e))throw e.cause;return e},e.prototype.peek=function(){var e=this.computeValue(!1);if(isCaughtException(e))throw e.cause;return e},e.prototype.set=function(e){if(this.setter){invariant(!this.isRunningSetter,"The setter of computed value '"+this.name+"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"),this.isRunningSetter=!0;try{this.setter.call(this.scope,e)}finally{this.isRunningSetter=!1}}else invariant(!1,!1)},e.prototype.trackAndCompute=function(){var e=this.value,t=this.dependenciesState===exports.IDerivationState.NOT_TRACKING,r=this.computeValue(!0),n=t||isCaughtException(e)||isCaughtException(r)||!this.equals(e,r);return n&&(this.value=r),n},e.prototype.computeValue=function(e){var t;if(this.isComputing=!0,globalState.computationDepth++,e)t=trackDerivedFunction(this,this.derivation,this.scope);else if(!0===globalState.disableErrorBoundaries)t=this.derivation.call(this.scope);else try{t=this.derivation.call(this.scope)}catch(e){t=new CaughtException(e)}return globalState.computationDepth--,this.isComputing=!1,t},e.prototype.suspend=function(){this.keepAlive||(clearObserving(this),this.value=void 0)},e.prototype.observe=function(e,t){var r=this,n=!0,o=void 0;return autorun(function(){var a=r.get();if(!n||t){var i=untrackedStart();e({type:"update",object:r,newValue:a,oldValue:o}),untrackedEnd(i)}n=!1,o=a})},e.prototype.warnAboutUntrackedRead=function(){},e.prototype.toJSON=function(){return this.get()},e.prototype.toString=function(){return this.name+"["+this.derivation.toString()+"]"},e.prototype.valueOf=function(){return toPrimitive(this.get())},e.prototype[Symbol.toPrimitive]=function(){return this.valueOf()},e}(),isComputedValue=createInstanceofPredicate("ComputedValue",ComputedValue),persistentKeys=["mobxGuid","spyListeners","enforceActions","computedRequiresReaction","reactionRequiresObservable","observableRequiresReaction","allowStateReads","disableErrorBoundaries","runId","UNCHANGED"],MobXGlobals=function(){return function(){this.version=5,this.UNCHANGED={},this.trackingDerivation=null,this.computationDepth=0,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!0,this.allowStateReads=!0,this.enforceActions=!1,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.computedConfigurable=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1}}(),canMergeGlobalState=!0,isolateCalled=!1,globalState=function(){var e=getGlobal();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(canMergeGlobalState=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==(new MobXGlobals).version&&(canMergeGlobalState=!1),canMergeGlobalState?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new MobXGlobals):(setTimeout(function(){isolateCalled||fail("There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`")},1),new MobXGlobals)}();function isolateGlobalState(){(globalState.pendingReactions.length||globalState.inBatch||globalState.isRunningReactions)&&fail("isolateGlobalState should be called before MobX is running any reactions"),isolateCalled=!0,canMergeGlobalState&&(0==--getGlobal().__mobxInstanceCount&&(getGlobal().__mobxGlobals=void 0),globalState=new MobXGlobals)}function getGlobalState(){return globalState}function resetGlobalState(){var e=new MobXGlobals;for(var t in e)-1===persistentKeys.indexOf(t)&&(globalState[t]=e[t]);globalState.allowStateChanges=!globalState.enforceActions}var mockGlobal={};function getGlobal(){return"undefined"!=typeof window?window:"undefined"!=typeof global?global:mockGlobal}function hasObservers(e){return e.observers&&e.observers.size>0}function getObservers(e){return e.observers}function addObserver(e,t){e.observers.add(t),e.lowestObserverState>t.dependenciesState&&(e.lowestObserverState=t.dependenciesState)}function removeObserver(e,t){e.observers.delete(t),0===e.observers.size&&queueForUnobservation(e)}function queueForUnobservation(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,globalState.pendingUnobservations.push(e))}function startBatch(){globalState.inBatch++}function endBatch(){if(0==--globalState.inBatch){runReactions();for(var e=globalState.pendingUnobservations,t=0;t<e.length;t++){var r=e[t];r.isPendingUnobservation=!1,0===r.observers.size&&(r.isBeingObserved&&(r.isBeingObserved=!1,r.onBecomeUnobserved()),r instanceof ComputedValue&&r.suspend())}globalState.pendingUnobservations=[]}}function reportObserved(e){var t=globalState.trackingDerivation;return null!==t?(t.runId!==e.lastAccessedBy&&(e.lastAccessedBy=t.runId,t.newObserving[t.unboundDepsCount++]=e,e.isBeingObserved||(e.isBeingObserved=!0,e.onBecomeObserved())),!0):(0===e.observers.size&&globalState.inBatch>0&&queueForUnobservation(e),!1)}function propagateChanged(e){e.lowestObserverState!==exports.IDerivationState.STALE&&(e.lowestObserverState=exports.IDerivationState.STALE,e.observers.forEach(function(t){t.dependenciesState===exports.IDerivationState.UP_TO_DATE&&(t.isTracing!==TraceMode.NONE&&logTraceInfo(t,e),t.onBecomeStale()),t.dependenciesState=exports.IDerivationState.STALE}))}function propagateChangeConfirmed(e){e.lowestObserverState!==exports.IDerivationState.STALE&&(e.lowestObserverState=exports.IDerivationState.STALE,e.observers.forEach(function(t){t.dependenciesState===exports.IDerivationState.POSSIBLY_STALE?t.dependenciesState=exports.IDerivationState.STALE:t.dependenciesState===exports.IDerivationState.UP_TO_DATE&&(e.lowestObserverState=exports.IDerivationState.UP_TO_DATE)}))}function propagateMaybeChanged(e){e.lowestObserverState===exports.IDerivationState.UP_TO_DATE&&(e.lowestObserverState=exports.IDerivationState.POSSIBLY_STALE,e.observers.forEach(function(t){t.dependenciesState===exports.IDerivationState.UP_TO_DATE&&(t.dependenciesState=exports.IDerivationState.POSSIBLY_STALE,t.isTracing!==TraceMode.NONE&&logTraceInfo(t,e),t.onBecomeStale())}))}function logTraceInfo(e,t){if(console.log("[mobx.trace] '"+e.name+"' is invalidated due to a change in: '"+t.name+"'"),e.isTracing===TraceMode.BREAK){var r=[];printDepTree(getDependencyTree(e),r,1),new Function("debugger;\n/*\nTracing '"+e.name+"'\n\nYou are entering this break point because derivation '"+e.name+"' is being traced and '"+t.name+"' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n"+(e instanceof ComputedValue?e.derivation.toString().replace(/[*]\//g,"/"):"")+"\n\nThe dependencies for this derivation are:\n\n"+r.join("\n")+"\n*/\n ")()}}function printDepTree(e,t,r){t.length>=1e3?t.push("(and many more)"):(t.push(""+new Array(r).join("\t")+e.name),e.dependencies&&e.dependencies.forEach(function(e){return printDepTree(e,t,r+1)}))}var Reaction=function(){function e(e,t,r,n){void 0===e&&(e="Reaction@"+getNextId()),void 0===n&&(n=!1),this.name=e,this.onInvalidate=t,this.errorHandler=r,this.requiresObservable=n,this.observing=[],this.newObserving=[],this.dependenciesState=exports.IDerivationState.NOT_TRACKING,this.diffValue=0,this.runId=0,this.unboundDepsCount=0,this.__mapid="#"+getNextId(),this.isDisposed=!1,this._isScheduled=!1,this._isTrackPending=!1,this._isRunning=!1,this.isTracing=TraceMode.NONE}return e.prototype.onBecomeStale=function(){this.schedule()},e.prototype.schedule=function(){this._isScheduled||(this._isScheduled=!0,globalState.pendingReactions.push(this),runReactions())},e.prototype.isScheduled=function(){return this._isScheduled},e.prototype.runReaction=function(){if(!this.isDisposed){if(startBatch(),this._isScheduled=!1,shouldCompute(this)){this._isTrackPending=!0;try{this.onInvalidate(),this._isTrackPending&&isSpyEnabled()}catch(e){this.reportExceptionInDerivation(e)}}endBatch()}},e.prototype.track=function(e){if(!this.isDisposed){startBatch(),this._isRunning=!0;var t=trackDerivedFunction(this,e,void 0);this._isRunning=!1,this._isTrackPending=!1,this.isDisposed&&clearObserving(this),isCaughtException(t)&&this.reportExceptionInDerivation(t.cause),endBatch()}},e.prototype.reportExceptionInDerivation=function(e){var t=this;if(this.errorHandler)this.errorHandler(e,this);else{if(globalState.disableErrorBoundaries)throw e;var r="[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '"+this+"'";globalState.suppressReactionErrors?console.warn("[mobx] (error in reaction '"+this.name+"' suppressed, fix error of causing action below)"):console.error(r,e),globalState.globalReactionErrorHandlers.forEach(function(r){return r(e,t)})}},e.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this._isRunning||(startBatch(),clearObserving(this),endBatch()))},e.prototype.getDisposer=function(){var e=this.dispose.bind(this);return e[$mobx]=this,e},e.prototype.toString=function(){return"Reaction["+this.name+"]"},e.prototype.trace=function(e){void 0===e&&(e=!1),trace(this,e)},e}();function onReactionError(e){return globalState.globalReactionErrorHandlers.push(e),function(){var t=globalState.globalReactionErrorHandlers.indexOf(e);t>=0&&globalState.globalReactionErrorHandlers.splice(t,1)}}var MAX_REACTION_ITERATIONS=100,reactionScheduler=function(e){return e()};function runReactions(){globalState.inBatch>0||globalState.isRunningReactions||reactionScheduler(runReactionsHelper)}function runReactionsHelper(){globalState.isRunningReactions=!0;for(var e=globalState.pendingReactions,t=0;e.length>0;){++t===MAX_REACTION_ITERATIONS&&(console.error("Reaction doesn't converge to a stable state after "+MAX_REACTION_ITERATIONS+" iterations. Probably there is a cycle in the reactive function: "+e[0]),e.splice(0));for(var r=e.splice(0),n=0,o=r.length;n<o;n++)r[n].runReaction()}globalState.isRunningReactions=!1}var isReaction=createInstanceofPredicate("Reaction",Reaction);function setReactionScheduler(e){var t=reactionScheduler;reactionScheduler=function(r){return e(function(){return t(r)})}}function isSpyEnabled(){return!1}function spyReport(e){}function spyReportStart(e){}var END_EVENT={spyReportEnd:!0};function spyReportEnd(e){}function spy(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}}function dontReassignFields(){fail(!1)}function namedActionDecorator(e){return function(t,r,n){if(n){if(n.value)return{value:createAction(e,n.value),enumerable:!1,configurable:!0,writable:!0};var o=n.initializer;return{enumerable:!1,configurable:!0,writable:!0,initializer:function(){return createAction(e,o.call(this))}}}return actionFieldDecorator(e).apply(this,arguments)}}function actionFieldDecorator(e){return function(t,r,n){Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get:function(){},set:function(t){addHiddenProp(this,r,action(e,t))}})}}function boundActionDecorator(e,t,r,n){return!0===n?(defineBoundAction(e,t,r.value),null):r?{configurable:!0,enumerable:!1,get:function(){return defineBoundAction(this,t,r.value||r.initializer.call(this)),this[t]},set:dontReassignFields}:{enumerable:!1,configurable:!0,set:function(e){defineBoundAction(this,t,e)},get:function(){}}}var action=function(e,t,r,n){return 1===arguments.length&&"function"==typeof e?createAction(e.name||"<unnamed action>",e):2===arguments.length&&"function"==typeof t?createAction(e,t):1===arguments.length&&"string"==typeof e?namedActionDecorator(e):!0!==n?namedActionDecorator(t).apply(null,arguments):void addHiddenProp(e,t,createAction(e.name||t,r.value,this))};function runInAction(e,t){return executeAction("string"==typeof e?e:e.name||"<unnamed action>","function"==typeof e?e:t,this,void 0)}function isAction(e){return"function"==typeof e&&!0===e.isMobxAction}function defineBoundAction(e,t,r){addHiddenProp(e,t,createAction(t,r.bind(e)))}function autorun(e,t){void 0===t&&(t=EMPTY_OBJECT);var r,n=t&&t.name||e.name||"Autorun@"+getNextId();if(!t.scheduler&&!t.delay)r=new Reaction(n,function(){this.track(i)},t.onError,t.requiresObservable);else{var o=createSchedulerFromOptions(t),a=!1;r=new Reaction(n,function(){a||(a=!0,o(function(){a=!1,r.isDisposed||r.track(i)}))},t.onError,t.requiresObservable)}function i(){e(r)}return r.schedule(),r.getDisposer()}action.bound=boundActionDecorator;var run=function(e){return e()};function createSchedulerFromOptions(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:run}function reaction(e,t,r){void 0===r&&(r=EMPTY_OBJECT);var n,o=r.name||"Reaction@"+getNextId(),a=action(o,r.onError?wrapErrorHandler(r.onError,t):t),i=!r.scheduler&&!r.delay,s=createSchedulerFromOptions(r),c=!0,u=!1,l=r.compareStructural?comparer.structural:r.equals||comparer.default,p=new Reaction(o,function(){c||i?d():u||(u=!0,s(d))},r.onError,r.requiresObservable);function d(){if(u=!1,!p.isDisposed){var t=!1;p.track(function(){var r=e(p);t=c||!l(n,r),n=r}),c&&r.fireImmediately&&a(n,p),c||!0!==t||a(n,p),c&&(c=!1)}}return p.schedule(),p.getDisposer()}function wrapErrorHandler(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function onBecomeObserved(e,t,r){return interceptHook("onBecomeObserved",e,t,r)}function onBecomeUnobserved(e,t,r){return interceptHook("onBecomeUnobserved",e,t,r)}function interceptHook(e,t,r,n){var o="function"==typeof n?getAtom(t,r):getAtom(t),a="function"==typeof n?n:r,i=e+"Listeners";return o[i]?o[i].add(a):o[i]=new Set([a]),"function"!=typeof o[e]?fail(!1):function(){var e=o[i];e&&(e.delete(a),0===e.size&&delete o[i])}}function configure(e){var t=e.enforceActions,r=e.computedRequiresReaction,n=e.computedConfigurable,o=e.disableErrorBoundaries,a=e.reactionScheduler,i=e.reactionRequiresObservable,s=e.observableRequiresReaction;if(!0===e.isolateGlobalState&&isolateGlobalState(),void 0!==t){"boolean"!=typeof t&&"strict"!==t||deprecated("Deprecated value for 'enforceActions', use 'false' => '\"never\"', 'true' => '\"observed\"', '\"strict\"' => \"'always'\" instead");var c=void 0;switch(t){case!0:case"observed":c=!0;break;case!1:case"never":c=!1;break;case"strict":case"always":c="strict";break;default:fail("Invalid value for 'enforceActions': '"+t+"', expected 'never', 'always' or 'observed'")}globalState.enforceActions=c,globalState.allowStateChanges=!0!==c&&"strict"!==c}void 0!==r&&(globalState.computedRequiresReaction=!!r),void 0!==i&&(globalState.reactionRequiresObservable=!!i),void 0!==s&&(globalState.observableRequiresReaction=!!s,globalState.allowStateReads=!globalState.observableRequiresReaction),void 0!==n&&(globalState.computedConfigurable=!!n),void 0!==o&&(!0===o&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),globalState.disableErrorBoundaries=!!o),a&&setReactionScheduler(a)}function decorate(e,t){var r="function"==typeof e?e.prototype:e,n=function(e){var n=t[e];Array.isArray(n)||(n=[n]);var o=Object.getOwnPropertyDescriptor(r,e),a=n.reduce(function(t,n){return n(r,e,t)},o);a&&Object.defineProperty(r,e,a)};for(var o in t)n(o);return e}function extendObservable(e,t,r,n){var o=getDefaultDecoratorFromObjectOptions(n=asCreateObservableOptions(n));return initializeInstance(e),asObservableObject(e,n.name,o.enhancer),t&&extendObservableObjectWithProperties(e,t,r,o),e}function getDefaultDecoratorFromObjectOptions(e){return e.defaultDecorator||(!1===e.deep?refDecorator:deepDecorator)}function extendObservableObjectWithProperties(e,t,r,n){var o,a;startBatch();try{var i=getPlainObjectKeys(t);try{for(var s=__values(i),c=s.next();!c.done;c=s.next()){var u=c.value,l=Object.getOwnPropertyDescriptor(t,u),p=(r&&u in r?r[u]:l.get?computedDecorator:n)(e,u,l,!0);p&&Object.defineProperty(e,u,p)}}catch(e){o={error:e}}finally{try{c&&!c.done&&(a=s.return)&&a.call(s)}finally{if(o)throw o.error}}}finally{endBatch()}}function getDependencyTree(e,t){return nodeToDependencyTree(getAtom(e,t))}function nodeToDependencyTree(e){var t={name:e.name};return e.observing&&e.observing.length>0&&(t.dependencies=unique(e.observing).map(nodeToDependencyTree)),t}function getObserverTree(e,t){return nodeToObserverTree(getAtom(e,t))}function nodeToObserverTree(e){var t={name:e.name};return hasObservers(e)&&(t.observers=Array.from(getObservers(e)).map(nodeToObserverTree)),t}var generatorId=0;function flow(e){1!==arguments.length&&fail("Flow expects one 1 argument and cannot be used as decorator");var t=e.name||"<unnamed flow>";return function(){var r,n=arguments,o=++generatorId,a=action(t+" - runid: "+o+" - init",e).apply(this,n),i=void 0,s=new Promise(function(e,n){var s=0;function c(e){var r;i=void 0;try{r=action(t+" - runid: "+o+" - yield "+s++,a.next).call(a,e)}catch(e){return n(e)}l(r)}function u(e){var r;i=void 0;try{r=action(t+" - runid: "+o+" - yield "+s++,a.throw).call(a,e)}catch(e){return n(e)}l(r)}function l(t){if(!t||"function"!=typeof t.then)return t.done?e(t.value):(i=Promise.resolve(t.value)).then(c,u);t.then(l,n)}r=n,c(void 0)});return s.cancel=action(t+" - runid: "+o+" - cancel",function(){try{i&&cancelPromise(i);var e=a.return(),t=Promise.resolve(e.value);t.then(noop,noop),cancelPromise(t),r(new Error("FLOW_CANCELLED"))}catch(e){r(e)}}),s}}function cancelPromise(e){"function"==typeof e.cancel&&e.cancel()}function interceptReads(e,t,r){var n;if(isObservableMap(e)||isObservableArray(e)||isObservableValue(e))n=getAdministration(e);else{if(!isObservableObject(e))return fail(!1);if("string"!=typeof t)return fail(!1);n=getAdministration(e,t)}return void 0!==n.dehancer?fail(!1):(n.dehancer="function"==typeof t?t:r,function(){n.dehancer=void 0})}function intercept(e,t,r){return"function"==typeof r?interceptProperty(e,t,r):interceptInterceptable(e,t)}function interceptInterceptable(e,t){return getAdministration(e).intercept(t)}function interceptProperty(e,t,r){return getAdministration(e,t).intercept(r)}function _isComputed(e,t){if(null==e)return!1;if(void 0!==t){if(!1===isObservableObject(e))return!1;if(!e[$mobx].values.has(t))return!1;var r=getAtom(e,t);return isComputedValue(r)}return isComputedValue(e)}function isComputed(e){return arguments.length>1?fail(!1):_isComputed(e)}function isComputedProp(e,t){return"string"!=typeof t?fail(!1):_isComputed(e,t)}function _isObservable(e,t){return null!=e&&(void 0!==t?!!isObservableObject(e)&&e[$mobx].values.has(t):isObservableObject(e)||!!e[$mobx]||isAtom(e)||isReaction(e)||isComputedValue(e))}function isObservable(e){return 1!==arguments.length&&fail(!1),_isObservable(e)}function isObservableProp(e,t){return"string"!=typeof t?fail(!1):_isObservable(e,t)}function keys(e){return isObservableObject(e)?e[$mobx].getKeys():isObservableMap(e)?Array.from(e.keys()):isObservableSet(e)?Array.from(e.keys()):isObservableArray(e)?e.map(function(e,t){return t}):fail(!1)}function values(e){return isObservableObject(e)?keys(e).map(function(t){return e[t]}):isObservableMap(e)?keys(e).map(function(t){return e.get(t)}):isObservableSet(e)?Array.from(e.values()):isObservableArray(e)?e.slice():fail(!1)}function entries(e){return isObservableObject(e)?keys(e).map(function(t){return[t,e[t]]}):isObservableMap(e)?keys(e).map(function(t){return[t,e.get(t)]}):isObservableSet(e)?Array.from(e.entries()):isObservableArray(e)?e.map(function(e,t){return[t,e]}):fail(!1)}function set(e,t,r){if(2!==arguments.length||isObservableSet(e))if(isObservableObject(e)){var n=e[$mobx];n.values.get(t)?n.write(t,r):n.addObservableProp(t,r,n.defaultEnhancer)}else if(isObservableMap(e))e.set(t,r);else if(isObservableSet(e))e.add(t);else{if(!isObservableArray(e))return fail(!1);"number"!=typeof t&&(t=parseInt(t,10)),invariant(t>=0,"Not a valid index: '"+t+"'"),startBatch(),t>=e.length&&(e.length=t+1),e[t]=r,endBatch()}else{startBatch();var o=t;try{for(var a in o)set(e,a,o[a])}finally{endBatch()}}}function remove(e,t){if(isObservableObject(e))e[$mobx].remove(t);else if(isObservableMap(e))e.delete(t);else if(isObservableSet(e))e.delete(t);else{if(!isObservableArray(e))return fail(!1);"number"!=typeof t&&(t=parseInt(t,10)),invariant(t>=0,"Not a valid index: '"+t+"'"),e.splice(t,1)}}function has(e,t){return isObservableObject(e)?getAdministration(e).has(t):isObservableMap(e)?e.has(t):isObservableSet(e)?e.has(t):isObservableArray(e)?t>=0&&t<e.length:fail(!1)}function get(e,t){if(has(e,t))return isObservableObject(e)?e[t]:isObservableMap(e)?e.get(t):isObservableArray(e)?e[t]:fail(!1)}function observe(e,t,r,n){return"function"==typeof r?observeObservableProperty(e,t,r,n):observeObservable(e,t,r)}function observeObservable(e,t,r){return getAdministration(e).observe(t,r)}function observeObservableProperty(e,t,r,n){return getAdministration(e,t).observe(r,n)}var defaultOptions={detectCycles:!0,exportMapsAsObjects:!0,recurseEverything:!1};function cache(e,t,r,n){return n.detectCycles&&e.set(t,r),r}function toJSHelper(e,t,r){if(!t.recurseEverything&&!isObservable(e))return e;if("object"!=typeof e)return e;if(null===e)return null;if(e instanceof Date)return e;if(isObservableValue(e))return toJSHelper(e.get(),t,r);if(isObservable(e)&&keys(e),!0===t.detectCycles&&null!==e&&r.has(e))return r.get(e);if(isObservableArray(e)||Array.isArray(e)){var n=cache(r,e,[],t),o=e.map(function(e){return toJSHelper(e,t,r)});n.length=o.length;for(var a=0,i=o.length;a<i;a++)n[a]=o[a];return n}if(isObservableSet(e)||Object.getPrototypeOf(e)===Set.prototype){if(!1===t.exportMapsAsObjects){var s=cache(r,e,new Set,t);return e.forEach(function(e){s.add(toJSHelper(e,t,r))}),s}var c=cache(r,e,[],t);return e.forEach(function(e){c.push(toJSHelper(e,t,r))}),c}if(isObservableMap(e)||Object.getPrototypeOf(e)===Map.prototype){if(!1===t.exportMapsAsObjects){var u=cache(r,e,new Map,t);return e.forEach(function(e,n){u.set(n,toJSHelper(e,t,r))}),u}var l=cache(r,e,{},t);return e.forEach(function(e,n){l[n]=toJSHelper(e,t,r)}),l}var p=cache(r,e,{},t);return getPlainObjectKeys(e).forEach(function(n){p[n]=toJSHelper(e[n],t,r)}),p}function toJS(e,t){var r;return"boolean"==typeof t&&(t={detectCycles:t}),t||(t=defaultOptions),t.detectCycles=void 0===t.detectCycles?!0===t.recurseEverything:!0===t.detectCycles,t.detectCycles&&(r=new Map),toJSHelper(e,t,r)}function trace(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=!1;"boolean"==typeof e[e.length-1]&&(r=e.pop());var n=getAtomFromArgs(e);if(!n)return fail(!1);n.isTracing===TraceMode.NONE&&console.log("[mobx.trace] '"+n.name+"' tracing enabled"),n.isTracing=r?TraceMode.BREAK:TraceMode.LOG}function getAtomFromArgs(e){switch(e.length){case 0:return globalState.trackingDerivation;case 1:return getAtom(e[0]);case 2:return getAtom(e[0],e[1])}}function transaction(e,t){void 0===t&&(t=void 0),startBatch();try{return e.apply(t)}finally{endBatch()}}function when(e,t,r){return 1===arguments.length||t&&"object"==typeof t?whenPromise(e,t):_when(e,t,r||{})}function _when(e,t,r){var n;"number"==typeof r.timeout&&(n=setTimeout(function(){if(!a[$mobx].isDisposed){a();var e=new Error("WHEN_TIMEOUT");if(!r.onError)throw e;r.onError(e)}},r.timeout)),r.name=r.name||"When@"+getNextId();var o=createAction(r.name+"-effect",t),a=autorun(function(t){e()&&(t.dispose(),n&&clearTimeout(n),o())},r);return a}function whenPromise(e,t){var r,n=new Promise(function(n,o){var a=_when(e,n,__assign({},t,{onError:o}));r=function(){a(),o("WHEN_CANCELLED")}});return n.cancel=r,n}function getAdm(e){return e[$mobx]}function isPropertyKey(e){return"string"==typeof e||"number"==typeof e||"symbol"==typeof e}var objectProxyTraps={has:function(e,t){if(t===$mobx||"constructor"===t||t===mobxDidRunLazyInitializersSymbol)return!0;var r=getAdm(e);return isPropertyKey(t)?r.has(t):t in e},get:function(e,t){if(t===$mobx||"constructor"===t||t===mobxDidRunLazyInitializersSymbol)return e[t];var r=getAdm(e),n=r.values.get(t);if(n instanceof Atom){var o=n.get();return void 0===o&&r.has(t),o}return isPropertyKey(t)&&r.has(t),e[t]},set:function(e,t,r){return!!isPropertyKey(t)&&(set(e,t,r),!0)},deleteProperty:function(e,t){return!!isPropertyKey(t)&&(getAdm(e).remove(t),!0)},ownKeys:function(e){return getAdm(e).keysAtom.reportObserved(),Reflect.ownKeys(e)},preventExtensions:function(e){return fail("Dynamic observable objects cannot be frozen"),!1}};function createDynamicObservableObject(e){var t=new Proxy(e,objectProxyTraps);return e[$mobx].proxy=t,t}function hasInterceptors(e){return void 0!==e.interceptors&&e.interceptors.length>0}function registerInterceptor(e,t){var r=e.interceptors||(e.interceptors=[]);return r.push(t),once(function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)})}function interceptChange(e,t){var r=untrackedStart();try{for(var n=__spread(e.interceptors||[]),o=0,a=n.length;o<a&&(invariant(!(t=n[o](t))||t.type,"Intercept handlers should return nothing or a change object"),t);o++);return t}finally{untrackedEnd(r)}}function hasListeners(e){return void 0!==e.changeListeners&&e.changeListeners.length>0}function registerListener(e,t){var r=e.changeListeners||(e.changeListeners=[]);return r.push(t),once(function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)})}function notifyListeners(e,t){var r=untrackedStart(),n=e.changeListeners;if(n){for(var o=0,a=(n=n.slice()).length;o<a;o++)n[o](t);untrackedEnd(r)}}var MAX_SPLICE_SIZE=1e4,arrayTraps={get:function(e,t){return t===$mobx?e[$mobx]:"length"===t?e[$mobx].getArrayLength():"number"==typeof t?arrayExtensions.get.call(e,t):"string"!=typeof t||isNaN(t)?arrayExtensions.hasOwnProperty(t)?arrayExtensions[t]:e[t]:arrayExtensions.get.call(e,parseInt(t))},set:function(e,t,r){return"length"===t&&e[$mobx].setArrayLength(r),"number"==typeof t&&arrayExtensions.set.call(e,t,r),"symbol"==typeof t||isNaN(t)?e[t]=r:arrayExtensions.set.call(e,parseInt(t),r),!0},preventExtensions:function(e){return fail("Observable arrays cannot be frozen"),!1}};function createObservableArray(e,t,r,n){void 0===r&&(r="ObservableArray@"+getNextId()),void 0===n&&(n=!1);var o=new ObservableArrayAdministration(r,t,n);addHiddenFinalProp(o.values,$mobx,o);var a=new Proxy(o.values,arrayTraps);if(o.proxy=a,e&&e.length){var i=allowStateChangesStart(!0);o.spliceWithArray(0,0,e),allowStateChangesEnd(i)}return a}var ObservableArrayAdministration=function(){function e(e,t,r){this.owned=r,this.values=[],this.proxy=void 0,this.lastKnownLength=0,this.atom=new Atom(e||"ObservableArray@"+getNextId()),this.enhancer=function(r,n){return t(r,n,e+"[..]")}}return e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.dehanceValues=function(e){return void 0!==this.dehancer&&e.length>0?e.map(this.dehancer):e},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e.prototype.observe=function(e,t){return void 0===t&&(t=!1),t&&e({object:this.proxy,type:"splice",index:0,added:this.values.slice(),addedCount:this.values.length,removed:[],removedCount:0}),registerListener(this,e)},e.prototype.getArrayLength=function(){return this.atom.reportObserved(),this.values.length},e.prototype.setArrayLength=function(e){if("number"!=typeof e||e<0)throw new Error("[mobx.array] Out of range: "+e);var t=this.values.length;if(e!==t)if(e>t){for(var r=new Array(e-t),n=0;n<e-t;n++)r[n]=void 0;this.spliceWithArray(t,0,r)}else this.spliceWithArray(e,t-e)},e.prototype.updateArrayLength=function(e,t){if(e!==this.lastKnownLength)throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed.");this.lastKnownLength+=t},e.prototype.spliceWithArray=function(e,t,r){var n=this;checkIfStateModificationsAreAllowed(this.atom);var o=this.values.length;if(void 0===e?e=0:e>o?e=o:e<0&&(e=Math.max(0,o+e)),t=1===arguments.length?o-e:null==t?0:Math.max(0,Math.min(t,o-e)),void 0===r&&(r=EMPTY_ARRAY),hasInterceptors(this)){var a=interceptChange(this,{object:this.proxy,type:"splice",index:e,removedCount:t,added:r});if(!a)return EMPTY_ARRAY;t=a.removedCount,r=a.added}r=0===r.length?r:r.map(function(e){return n.enhancer(e,void 0)});var i=this.spliceItemsIntoValues(e,t,r);return 0===t&&0===r.length||this.notifyArraySplice(e,r,i),this.dehanceValues(i)},e.prototype.spliceItemsIntoValues=function(e,t,r){var n;if(r.length<MAX_SPLICE_SIZE)return(n=this.values).splice.apply(n,__spread([e,t],r));var o=this.values.slice(e,e+t);return this.values=this.values.slice(0,e).concat(r,this.values.slice(e+t)),o},e.prototype.notifyArrayChildUpdate=function(e,t,r){var n=!this.owned&&isSpyEnabled(),o=hasListeners(this),a=o||n?{object:this.proxy,type:"update",index:e,newValue:t,oldValue:r}:null;this.atom.reportChanged(),o&&notifyListeners(this,a)},e.prototype.notifyArraySplice=function(e,t,r){var n=!this.owned&&isSpyEnabled(),o=hasListeners(this),a=o||n?{object:this.proxy,type:"splice",index:e,removed:r,added:t,removedCount:r.length,addedCount:t.length}:null;this.atom.reportChanged(),o&&notifyListeners(this,a)},e}(),arrayExtensions={intercept:function(e){return this[$mobx].intercept(e)},observe:function(e,t){return void 0===t&&(t=!1),this[$mobx].observe(e,t)},clear:function(){return this.splice(0)},replace:function(e){var t=this[$mobx];return t.spliceWithArray(0,t.values.length,e)},toJS:function(){return this.slice()},toJSON:function(){return this.toJS()},splice:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=this[$mobx];switch(arguments.length){case 0:return[];case 1:return o.spliceWithArray(e);case 2:return o.spliceWithArray(e,t)}return o.spliceWithArray(e,t,r)},spliceWithArray:function(e,t,r){return this[$mobx].spliceWithArray(e,t,r)},push:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this[$mobx];return r.spliceWithArray(r.values.length,0,e),r.values.length},pop:function(){return this.splice(Math.max(this[$mobx].values.length-1,0),1)[0]},shift:function(){return this.splice(0,1)[0]},unshift:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this[$mobx];return r.spliceWithArray(0,0,e),r.values.length},reverse:function(){var e=this.slice();return e.reverse.apply(e,arguments)},sort:function(e){var t=this.slice();return t.sort.apply(t,arguments)},remove:function(e){var t=this[$mobx],r=t.dehanceValues(t.values).indexOf(e);return r>-1&&(this.splice(r,1),!0)},get:function(e){var t=this[$mobx];if(t){if(e<t.values.length)return t.atom.reportObserved(),t.dehanceValue(t.values[e]);console.warn("[mobx.array] Attempt to read an array index ("+e+") that is out of bounds ("+t.values.length+"). Please check length first. Out of bound indices will not be tracked by MobX")}},set:function(e,t){var r=this[$mobx],n=r.values;if(e<n.length){checkIfStateModificationsAreAllowed(r.atom);var o=n[e];if(hasInterceptors(r)){var a=interceptChange(r,{type:"update",object:r.proxy,index:e,newValue:t});if(!a)return;t=a.newValue}(t=r.enhancer(t,o))!==o&&(n[e]=t,r.notifyArrayChildUpdate(e,t,o))}else{if(e!==n.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+n.length);r.spliceWithArray(e,0,[t])}}};["concat","every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some","toString","toLocaleString"].forEach(function(e){arrayExtensions[e]=function(){var t=this[$mobx];t.atom.reportObserved();var r=t.dehanceValues(t.values);return r[e].apply(r,arguments)}});var _a,isObservableArrayAdministration=createInstanceofPredicate("ObservableArrayAdministration",ObservableArrayAdministration);function isObservableArray(e){return isObject(e)&&isObservableArrayAdministration(e[$mobx])}var _a$1,ObservableMapMarker={},ObservableMap=function(){function e(e,t,r){if(void 0===t&&(t=deepEnhancer),void 0===r&&(r="ObservableMap@"+getNextId()),this.enhancer=t,this.name=r,this[_a]=ObservableMapMarker,this._keysAtom=createAtom(this.name+".keys()"),this[Symbol.toStringTag]="Map","function"!=typeof Map)throw new Error("mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js");this._data=new Map,this._hasMap=new Map,this.merge(e)}return e.prototype._has=function(e){return this._data.has(e)},e.prototype.has=function(e){var t=this;if(!globalState.trackingDerivation)return this._has(e);var r=this._hasMap.get(e);if(!r){var n=r=new ObservableValue(this._has(e),referenceEnhancer,this.name+"."+stringifyKey(e)+"?",!1);this._hasMap.set(e,n),onBecomeUnobserved(n,function(){return t._hasMap.delete(e)})}return r.get()},e.prototype.set=function(e,t){var r=this._has(e);if(hasInterceptors(this)){var n=interceptChange(this,{type:r?"update":"add",object:this,newValue:t,name:e});if(!n)return this;t=n.newValue}return r?this._updateValue(e,t):this._addValue(e,t),this},e.prototype.delete=function(e){var t=this;if(hasInterceptors(this)&&!(o=interceptChange(this,{type:"delete",object:this,name:e})))return!1;if(this._has(e)){var r=isSpyEnabled(),n=hasListeners(this),o=n||r?{type:"delete",object:this,oldValue:this._data.get(e).value,name:e}:null;return transaction(function(){t._keysAtom.reportChanged(),t._updateHasMapEntry(e,!1),t._data.get(e).setNewValue(void 0),t._data.delete(e)}),n&&notifyListeners(this,o),!0}return!1},e.prototype._updateHasMapEntry=function(e,t){var r=this._hasMap.get(e);r&&r.setNewValue(t)},e.prototype._updateValue=function(e,t){var r=this._data.get(e);if((t=r.prepareNewValue(t))!==globalState.UNCHANGED){var n=isSpyEnabled(),o=hasListeners(this),a=o||n?{type:"update",object:this,oldValue:r.value,name:e,newValue:t}:null;0,r.setNewValue(t),o&&notifyListeners(this,a)}},e.prototype._addValue=function(e,t){var r=this;checkIfStateModificationsAreAllowed(this._keysAtom),transaction(function(){var n=new ObservableValue(t,r.enhancer,r.name+"."+stringifyKey(e),!1);r._data.set(e,n),t=n.value,r._updateHasMapEntry(e,!0),r._keysAtom.reportChanged()});var n=isSpyEnabled(),o=hasListeners(this);o&&notifyListeners(this,o||n?{type:"add",object:this,name:e,newValue:t}:null)},e.prototype.get=function(e){return this.has(e)?this.dehanceValue(this._data.get(e).get()):this.dehanceValue(void 0)},e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.keys=function(){return this._keysAtom.reportObserved(),this._data.keys()},e.prototype.values=function(){var e=this,t=0,r=Array.from(this.keys());return makeIterable({next:function(){return t<r.length?{value:e.get(r[t++]),done:!1}:{done:!0}}})},e.prototype.entries=function(){var e=this,t=0,r=Array.from(this.keys());return makeIterable({next:function(){if(t<r.length){var n=r[t++];return{value:[n,e.get(n)],done:!1}}return{done:!0}}})},e.prototype[(_a=$mobx,Symbol.iterator)]=function(){return this.entries()},e.prototype.forEach=function(e,t){var r,n;try{for(var o=__values(this),a=o.next();!a.done;a=o.next()){var i=__read(a.value,2),s=i[0],c=i[1];e.call(t,c,s,this)}}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}},e.prototype.merge=function(e){var t=this;return isObservableMap(e)&&(e=e.toJS()),transaction(function(){isPlainObject(e)?getPlainObjectKeys(e).forEach(function(r){return t.set(r,e[r])}):Array.isArray(e)?e.forEach(function(e){var r=__read(e,2),n=r[0],o=r[1];return t.set(n,o)}):isES6Map(e)?(e.constructor!==Map&&fail("Cannot initialize from classes that inherit from Map: "+e.constructor.name),e.forEach(function(e,r){return t.set(r,e)})):null!=e&&fail("Cannot initialize map from "+e)}),this},e.prototype.clear=function(){var e=this;transaction(function(){untracked(function(){var t,r;try{for(var n=__values(e.keys()),o=n.next();!o.done;o=n.next()){var a=o.value;e.delete(a)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})})},e.prototype.replace=function(e){var t=this;return transaction(function(){var r=getMapLikeKeys(e);Array.from(t.keys()).filter(function(e){return-1===r.indexOf(e)}).forEach(function(e){return t.delete(e)}),t.merge(e)}),this},Object.defineProperty(e.prototype,"size",{get:function(){return this._keysAtom.reportObserved(),this._data.size},enumerable:!0,configurable:!0}),e.prototype.toPOJO=function(){var e,t,r={};try{for(var n=__values(this),o=n.next();!o.done;o=n.next()){var a=__read(o.value,2),i=a[0],s=a[1];r["symbol"==typeof i?i:stringifyKey(i)]=s}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return r},e.prototype.toJS=function(){return new Map(this)},e.prototype.toJSON=function(){return this.toPOJO()},e.prototype.toString=function(){var e=this;return this.name+"[{ "+Array.from(this.keys()).map(function(t){return stringifyKey(t)+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e,t){return registerListener(this,e)},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e}(),isObservableMap=createInstanceofPredicate("ObservableMap",ObservableMap),ObservableSetMarker={},ObservableSet=function(){function e(e,t,r){if(void 0===t&&(t=deepEnhancer),void 0===r&&(r="ObservableSet@"+getNextId()),this.name=r,this[_a$1]=ObservableSetMarker,this._data=new Set,this._atom=createAtom(this.name),this[Symbol.toStringTag]="Set","function"!=typeof Set)throw new Error("mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js");this.enhancer=function(e,n){return t(e,n,r)},e&&this.replace(e)}return e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.clear=function(){var e=this;transaction(function(){untracked(function(){var t,r;try{for(var n=__values(e._data.values()),o=n.next();!o.done;o=n.next()){var a=o.value;e.delete(a)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})})},e.prototype.forEach=function(e,t){var r,n;try{for(var o=__values(this),a=o.next();!a.done;a=o.next()){var i=a.value;e.call(t,i,i,this)}}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}},Object.defineProperty(e.prototype,"size",{get:function(){return this._atom.reportObserved(),this._data.size},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=this;if((checkIfStateModificationsAreAllowed(this._atom),hasInterceptors(this))&&!(o=interceptChange(this,{type:"add",object:this,newValue:e})))return this;if(!this.has(e)){transaction(function(){t._data.add(t.enhancer(e,void 0)),t._atom.reportChanged()});var r=isSpyEnabled(),n=hasListeners(this),o=n||r?{type:"add",object:this,newValue:e}:null;0,n&&notifyListeners(this,o)}return this},e.prototype.delete=function(e){var t=this;if(hasInterceptors(this)&&!(o=interceptChange(this,{type:"delete",object:this,oldValue:e})))return!1;if(this.has(e)){var r=isSpyEnabled(),n=hasListeners(this),o=n||r?{type:"delete",object:this,oldValue:e}:null;return transaction(function(){t._atom.reportChanged(),t._data.delete(e)}),n&&notifyListeners(this,o),!0}return!1},e.prototype.has=function(e){return this._atom.reportObserved(),this._data.has(this.dehanceValue(e))},e.prototype.entries=function(){var e=0,t=Array.from(this.keys()),r=Array.from(this.values());return makeIterable({next:function(){var n=e;return e+=1,n<r.length?{value:[t[n],r[n]],done:!1}:{done:!0}}})},e.prototype.keys=function(){return this.values()},e.prototype.values=function(){this._atom.reportObserved();var e=this,t=0,r=Array.from(this._data.values());return makeIterable({next:function(){return t<r.length?{value:e.dehanceValue(r[t++]),done:!1}:{done:!0}}})},e.prototype.replace=function(e){var t=this;return isObservableSet(e)&&(e=e.toJS()),transaction(function(){Array.isArray(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):isES6Set(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):null!=e&&fail("Cannot initialize set from "+e)}),this},e.prototype.observe=function(e,t){return registerListener(this,e)},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e.prototype.toJS=function(){return new Set(this)},e.prototype.toString=function(){return this.name+"[ "+Array.from(this).join(", ")+" ]"},e.prototype[(_a$1=$mobx,Symbol.iterator)]=function(){return this.values()},e}(),isObservableSet=createInstanceofPredicate("ObservableSet",ObservableSet),ObservableObjectAdministration=function(){function e(e,t,r,n){void 0===t&&(t=new Map),this.target=e,this.values=t,this.name=r,this.defaultEnhancer=n,this.keysAtom=new Atom(r+".keys")}return e.prototype.read=function(e){return this.values.get(e).get()},e.prototype.write=function(e,t){var r=this.target,n=this.values.get(e);if(n instanceof ComputedValue)n.set(t);else{if(hasInterceptors(this)){if(!(i=interceptChange(this,{type:"update",object:this.proxy||r,name:e,newValue:t})))return;t=i.newValue}if((t=n.prepareNewValue(t))!==globalState.UNCHANGED){var o=hasListeners(this),a=isSpyEnabled(),i=o||a?{type:"update",object:this.proxy||r,oldValue:n.value,name:e,newValue:t}:null;0,n.setNewValue(t),o&&notifyListeners(this,i)}}},e.prototype.has=function(e){var t=this.pendingKeys||(this.pendingKeys=new Map),r=t.get(e);if(r)return r.get();var n=!!this.values.get(e);return r=new ObservableValue(n,referenceEnhancer,this.name+"."+stringifyKey(e)+"?",!1),t.set(e,r),r.get()},e.prototype.addObservableProp=function(e,t,r){void 0===r&&(r=this.defaultEnhancer);var n=this.target;if(hasInterceptors(this)){var o=interceptChange(this,{object:this.proxy||n,name:e,type:"add",newValue:t});if(!o)return;t=o.newValue}var a=new ObservableValue(t,r,this.name+"."+stringifyKey(e),!1);this.values.set(e,a),t=a.value,Object.defineProperty(n,e,generateObservablePropConfig(e)),this.notifyPropertyAddition(e,t)},e.prototype.addComputedProp=function(e,t,r){var n=this.target;r.name=r.name||this.name+"."+stringifyKey(t),this.values.set(t,new ComputedValue(r)),(e===n||isPropertyConfigurable(e,t))&&Object.defineProperty(e,t,generateComputedPropConfig(t))},e.prototype.remove=function(e){if(this.values.has(e)){var t=this.target;if(hasInterceptors(this))if(!(s=interceptChange(this,{object:this.proxy||t,name:e,type:"remove"})))return;try{startBatch();var r=hasListeners(this),n=isSpyEnabled(),o=this.values.get(e),a=o&&o.get();if(o&&o.set(void 0),this.keysAtom.reportChanged(),this.values.delete(e),this.pendingKeys){var i=this.pendingKeys.get(e);i&&i.set(!1)}delete this.target[e];var s=r||n?{type:"remove",object:this.proxy||t,oldValue:a,name:e}:null;0,r&&notifyListeners(this,s)}finally{endBatch()}}},e.prototype.illegalAccess=function(e,t){console.warn("Property '"+t+"' of '"+e+"' was accessed through the prototype chain. Use 'decorate' instead to declare the prop or access it statically through it's owner")},e.prototype.observe=function(e,t){return registerListener(this,e)},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e.prototype.notifyPropertyAddition=function(e,t){var r=hasListeners(this),n=isSpyEnabled(),o=r||n?{type:"add",object:this.proxy||this.target,name:e,newValue:t}:null;if(r&&notifyListeners(this,o),this.pendingKeys){var a=this.pendingKeys.get(e);a&&a.set(!0)}this.keysAtom.reportChanged()},e.prototype.getKeys=function(){var e,t;this.keysAtom.reportObserved();var r=[];try{for(var n=__values(this.values),o=n.next();!o.done;o=n.next()){var a=__read(o.value,2),i=a[0];a[1]instanceof ObservableValue&&r.push(i)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return r},e}();function asObservableObject(e,t,r){if(void 0===t&&(t=""),void 0===r&&(r=deepEnhancer),Object.prototype.hasOwnProperty.call(e,$mobx))return e[$mobx];isPlainObject(e)||(t=(e.constructor.name||"ObservableObject")+"@"+getNextId()),t||(t="ObservableObject@"+getNextId());var n=new ObservableObjectAdministration(e,new Map,stringifyKey(t),r);return addHiddenProp(e,$mobx,n),n}var observablePropertyConfigs=Object.create(null),computedPropertyConfigs=Object.create(null);function generateObservablePropConfig(e){return observablePropertyConfigs[e]||(observablePropertyConfigs[e]={configurable:!0,enumerable:!0,get:function(){return this[$mobx].read(e)},set:function(t){this[$mobx].write(e,t)}})}function getAdministrationForComputedPropOwner(e){var t=e[$mobx];return t||(initializeInstance(e),e[$mobx])}function generateComputedPropConfig(e){return computedPropertyConfigs[e]||(computedPropertyConfigs[e]={configurable:globalState.computedConfigurable,enumerable:!1,get:function(){return getAdministrationForComputedPropOwner(this).read(e)},set:function(t){getAdministrationForComputedPropOwner(this).write(e,t)}})}var isObservableObjectAdministration=createInstanceofPredicate("ObservableObjectAdministration",ObservableObjectAdministration);function isObservableObject(e){return!!isObject(e)&&(initializeInstance(e),isObservableObjectAdministration(e[$mobx]))}function getAtom(e,t){if("object"==typeof e&&null!==e){if(isObservableArray(e))return void 0!==t&&fail(!1),e[$mobx].atom;if(isObservableSet(e))return e[$mobx];if(isObservableMap(e)){var r=e;return void 0===t?r._keysAtom:((n=r._data.get(t)||r._hasMap.get(t))||fail(!1),n)}var n;if(initializeInstance(e),t&&!e[$mobx]&&e[t],isObservableObject(e))return t?((n=e[$mobx].values.get(t))||fail(!1),n):fail(!1);if(isAtom(e)||isComputedValue(e)||isReaction(e))return e}else if("function"==typeof e&&isReaction(e[$mobx]))return e[$mobx];return fail(!1)}function getAdministration(e,t){return e||fail("Expecting some object"),void 0!==t?getAdministration(getAtom(e,t)):isAtom(e)||isComputedValue(e)||isReaction(e)?e:isObservableMap(e)||isObservableSet(e)?e:(initializeInstance(e),e[$mobx]?e[$mobx]:void fail(!1))}function getDebugName(e,t){return(void 0!==t?getAtom(e,t):isObservableObject(e)||isObservableMap(e)||isObservableSet(e)?getAdministration(e):getAtom(e)).name}var g,toString=Object.prototype.toString;function deepEqual(e,t,r){return void 0===r&&(r=-1),eq(e,t,r)}function eq(e,t,r,n,o){if(e===t)return 0!==e||1/e==1/t;if(null==e||null==t)return!1;if(e!=e)return t!=t;var a=typeof e;if("function"!==a&&"object"!==a&&"object"!=typeof t)return!1;e=unwrap(e),t=unwrap(t);var i=toString.call(e);if(i!==toString.call(t))return!1;switch(i){case"[object RegExp]":case"[object String]":return""+e==""+t;case"[object Number]":return+e!=+e?+t!=+t:0==+e?1/+e==1/t:+e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object Symbol]":return"undefined"!=typeof Symbol&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t)}var s="[object Array]"===i;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var c=e.constructor,u=t.constructor;if(c!==u&&!("function"==typeof c&&c instanceof c&&"function"==typeof u&&u instanceof u)&&"constructor"in e&&"constructor"in t)return!1}if(0===r)return!1;r<0&&(r=-1),o=o||[];for(var l=(n=n||[]).length;l--;)if(n[l]===e)return o[l]===t;if(n.push(e),o.push(t),s){if((l=e.length)!==t.length)return!1;for(;l--;)if(!eq(e[l],t[l],r-1,n,o))return!1}else{var p=Object.keys(e),d=void 0;if(l=p.length,Object.keys(t).length!==l)return!1;for(;l--;)if(!has$1(t,d=p[l])||!eq(e[d],t[d],r-1,n,o))return!1}return n.pop(),o.pop(),!0}function unwrap(e){return isObservableArray(e)?e.slice():isES6Map(e)||isObservableMap(e)?Array.from(e.entries()):isES6Set(e)||isObservableSet(e)?Array.from(e.entries()):e}function has$1(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function makeIterable(e){return e[Symbol.iterator]=getSelf,e}function getSelf(){return this}if("undefined"==typeof Proxy||"undefined"==typeof Symbol)throw new Error("[mobx] MobX 5+ requires Proxy and Symbol objects. If your environment doesn't support Symbol or Proxy objects, please downgrade to MobX 4. For React Native Android, consider upgrading JSCore.");"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:spy,extras:{getDebugName:getDebugName},$mobx:$mobx}),exports.$mobx=$mobx,exports.ObservableMap=ObservableMap,exports.ObservableSet=ObservableSet,exports.Reaction=Reaction,exports._allowStateChanges=allowStateChanges,exports._allowStateChangesInsideComputed=allowStateChangesInsideComputed,exports._endAction=_endAction,exports._getAdministration=getAdministration,exports._getGlobalState=getGlobalState,exports._interceptReads=interceptReads,exports._isComputingDerivation=isComputingDerivation,exports._resetGlobalState=resetGlobalState,exports._startAction=_startAction,exports.action=action,exports.autorun=autorun,exports.comparer=comparer,exports.computed=computed,exports.configure=configure,exports.createAtom=createAtom,exports.decorate=decorate,exports.entries=entries,exports.extendObservable=extendObservable,exports.flow=flow,exports.get=get,exports.getAtom=getAtom,exports.getDebugName=getDebugName,exports.getDependencyTree=getDependencyTree,exports.getObserverTree=getObserverTree,exports.has=has,exports.intercept=intercept,exports.isAction=isAction,exports.isArrayLike=isArrayLike,exports.isBoxedObservable=isObservableValue,exports.isComputed=isComputed,exports.isComputedProp=isComputedProp,exports.isObservable=isObservable,exports.isObservableArray=isObservableArray,exports.isObservableMap=isObservableMap,exports.isObservableObject=isObservableObject,exports.isObservableProp=isObservableProp,exports.isObservableSet=isObservableSet,exports.keys=keys,exports.observable=observable,exports.observe=observe,exports.onBecomeObserved=onBecomeObserved,exports.onBecomeUnobserved=onBecomeUnobserved,exports.onReactionError=onReactionError,exports.reaction=reaction,exports.remove=remove,exports.runInAction=runInAction,exports.set=set,exports.spy=spy,exports.toJS=toJS,exports.trace=trace,exports.transaction=transaction,exports.untracked=untracked,exports.values=values,exports.when=when;
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(function(){var define,module,exports;return 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(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.9.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,new Position]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=7){isKeyword=isEcma7Keyword}else if(options.ecmaVersion===6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc;this.startLoc=tokStartLoc;this.endLoc=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(forceRegexp){lastEnd=tokEnd;readToken(forceRegexp);return new Token}getToken.jumpTo=function(pos,reAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokRegexpAllowed=reAllowed;skipSpace()};getToken.noRegexp=function(){tokRegexpAllowed=false};getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokRegexpAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inXJSChildExpression;var metParenL;var inTemplate;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=new Position;inFunction=inGenerator=inAsync=strict=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _async={keyword:"async"},_await={keyword:"await",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield,await:_await,async:_async};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_bquote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _ltSlash={type:"</"};var _ellipsis={type:"...",prefix:true,beforeExpr:true};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _lt={binop:7,beforeExpr:true},_gt={binop:7,beforeExpr:true};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,arrow:_arrow,bquote:_bquote,dollarBraceL:_dollarBraceL,star:_star,assign:_assign,xjsName:_xjsName,xjsText:_xjsText};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];function makePredicate(words){words=words.split(" ");var f="",cats=[];out:for(var i=0;i<words.length;++i){for(var j=0;j<cats.length;++j)if(cats[j][0].length==words[i].length){cats[j].push(words[i]);continue out}cats.push([words[i]])}function compareTo(arr){if(arr.length==1)return f+="return str === "+JSON.stringify(arr[0])+";";f+="switch(str){";for(var i=0;i<arr.length;++i)f+="case "+JSON.stringify(arr[i])+":";f+="return true}return false;"}if(cats.length>3){cats.sort(function(a,b){return b.length-a.length});f+="switch(str.length){";for(var i=0;i<cats.length;++i){var cat=cats[i];f+="case "+cat[0].length+":";compareTo(cat)}f+="}"}else{compareTo(words)}return new Function("str",f)}var isReservedWord3=makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");var isReservedWord5=makePredicate("class enum extends super const export import");var isStrictReservedWord=makePredicate("implements interface let package private protected public static yield");var isStrictBadIdWord=makePredicate("eval arguments");var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=makePredicate(ecma5AndLessKeywords);var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=makePredicate(ecma6AndLessKeywords);var isEcma7Keyword=makePredicate(ecma6AndLessKeywords+" async await");var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var newline=/[\n\r\u2028\u2029]/;var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(){this.line=tokCurLine;this.column=tokPos-tokLineStart}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokRegexpAllowed=true;metParenL=0;inTemplate=inXJSChild=inXJSTag=false}function finishToken(type,val,shouldSkipSpace){tokEnd=tokPos;if(options.locations)tokEndLoc=new Position;tokType=type;if(shouldSkipSpace!==false&&!(inXJSChild&&tokType!==_braceL)){skipSpace()}tokVal=val;tokRegexpAllowed=type.beforeExpr;if(options.onToken){options.onToken(new Token)}}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&new Position;var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&new Position)}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&new Position;var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&new Position)}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokRegexpAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_mult_modulo(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(code===42?_star:_modulo,1)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code)return finishOp(code===124?_logicalOR:_logicalAND,2);if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(next===61){size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}if(next===47){size=2;return finishOp(_ltSlash,size)}return code===60?finishOp(_lt,size):finishOp(_gt,size,!inXJSTag)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}if(code===125){++tokPos;return finishToken(_braceR,undefined,false)}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR,undefined,!inXJSChildExpression);case 58:++tokPos;return finishToken(_colon);case 63:++tokPos;return finishToken(_question);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_bquote,undefined,false)}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:case 42:return readToken_mult_modulo(code);case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(forceRegexp){if(!forceRegexp)tokStart=tokPos;else tokPos=tokStart+1;if(options.locations)tokStartLoc=new Position;if(forceRegexp)return readRegexp();if(tokPos>=inputLen)return finishToken(_eof);var code=input.charCodeAt(tokPos);if(inXJSChild&&tokType!==_braceL&&code!==60&&code!==123&&code!==125){return readXJSText(["<","{"])}if(inTemplate)return getTemplateToken(code);if(isIdentifierStart(code)||code===92)return readWord();var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("￿","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){++tokPos;var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote){++tokPos;return finishToken(_string,out)}if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){raise(tokStart,"Unterminated string constant")}out+=String.fromCharCode(ch)}}}function readTmplString(){var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123)return finishToken(_string,out);if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return" ";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");tokPos++;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){break}str+=ch}if(str[0]==="#"&&str[1]==="x"){entity=String.fromCharCode(parseInt(str.substr(2),16))}else if(str[0]==="#"){entity=String.fromCharCode(parseInt(str.substr(1),10))}else{entity=XHTMLEntities[str]}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&&quote!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word,first=true,start=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)||inXJSTag&&ch===45){if(containsEsc)word+=nextChar();++tokPos}else if(ch===92&&!inXJSTag){if(!containsEsc)word=input.slice(start,tokPos);containsEsc=true;if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr}else{break}first=false}return containsEsc?word:input.slice(start,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function next(){lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node,allowSpread,checkType){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.kind!=="init")unexpected(prop.key.start);toAssignable(prop.value,false,checkType)}break;case"ArrayExpression":node.type="ArrayPattern";for(var i=0,lastI=node.elements.length-1;i<=lastI;i++){toAssignable(node.elements[i],i===lastI,checkType)}break;case"SpreadElement":if(allowSpread){toAssignable(node.argument,false,checkType);checkSpreadAssign(node.argument)}else{unexpected(node.start)}break;default:if(checkType)unexpected(node.start)}}return node}function checkSpreadAssign(node){if(node.type!=="Identifier"&&node.type!=="ArrayPattern")unexpected(node.start)}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return;var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,isBinding?"Binding "+expr.name+" in strict mode":"Assigning to "+expr.name+" in strict mode"); break;case"MemberExpression":if(!isBinding)break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++)checkLVal(expr.properties[i].value,isBinding);break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"SpreadElement":break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement();node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(){if(tokType===_slash||tokType===_assign&&tokVal=="/=")readToken(true);var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _async:return parseAsync(node,true);case _function:return parseFunctionStatement(node);case _class:return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _var:case _let:case _const:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:return parseExport(node);case _import:return parseImport(node);default:var maybeName=tokVal,expr=parseExpression();if(starttype===_name&&expr.type==="Identifier"&&eat(_colon))return parseLabeledStatement(node,maybeName,expr);else return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement();labels.pop();expect(_while);node.test=parseParenExpression();semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of")&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var init=parseExpression(false,true);if(tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of"){checkLVal(init);return parseForIn(node,init)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseAsync(node,isStatement){if(options.ecmaVersion<7){unexpected()}next();switch(tokType){case _function:next();return parseFunction(node,isStatement,true);if(!isStatement)unexpected();case _name:var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(node,[id],true)}case _parenL:var oldParenL=++metParenL;var exprList=[];next();if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){return parseArrowExpression(node,exprList,true)}default:unexpected()}}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement();node.alternate=eat(_else)?parseStatement():null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement())}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseIdent();if(strict&&isStrictBadIdWord(clause.param.name))raise(clause.param.start,"Binding "+clause.param.name+" in strict mode");expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement();labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement();return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement();labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement();node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=options.ecmaVersion>=6?toAssignable(parseExprAtom()):parseIdent();checkLVal(decl.id,true);decl.init=eat(_eq)?parseExpression(true,noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noComma,noIn){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn);if(!noComma&&tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn){var start=storeCurrentPos();var left=parseMaybeConditional(noIn);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}return left}function parseMaybeConditional(noIn){var start=storeCurrentPos();var expr=parseExprOps(noIn);if(eat(_question)){var node=startNodeAt(start);node.test=expr;node.consequent=parseExpression(true);expect(_colon);node.alternate=parseExpression(true,noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn){var start=storeCurrentPos();return parseExprOp(parseMaybeUnary(),start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate,nodeType;if(tokType===_ellipsis){nodeType="SpreadElement"}else{nodeType=update?"UpdateExpression":"UnaryExpression";node.operator=tokVal;node.prefix=true}tokRegexpAllowed=true;next();node.argument=parseMaybeUnary();if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,nodeType)}var start=storeCurrentPos();var expr=parseExprSubscripts();while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(){var start=storeCurrentPos();return parseSubscripts(parseExprAtom(),start)}function parseSubscripts(base,start,noCalls){if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_bquote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _yield:if(inGenerator)return parseYield();case _await:if(inAsync)return parseAwait();case _name:var start=storeCurrentPos();var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(startNodeAt(start),[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _xjsText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:var start=storeCurrentPos();var val,exprList;next();if(options.ecmaVersion>=7&&tokType===_for){val=parseComprehension(startNodeAt(start),true)}else{var oldParenL=++metParenL;if(tokType!==_parenR){val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){val=parseArrowExpression(startNodeAt(start),exprList)}else{if(!val)unexpected(lastStart);if(options.ecmaVersion>=6){for(var i=0;i<exprList.length;i++){if(exprList[i].type==="SpreadElement")unexpected()}}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;val=finishNode(par,"ParenthesizedExpression")}}}return val;case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true);return finishNode(node,"ArrayExpression");case _braceL:return parseObj();case _async:return parseAsync(startNode(),false);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _bquote:return parseTemplate();case _lt:return parseXJSElement();default:unexpected()}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplate(){var node=startNode();node.expressions=[];node.quasis=[];inTemplate=true;next();for(;;){var elem=startNode();elem.value={cooked:tokVal,raw:input.slice(tokStart,tokEnd)};elem.tail=false;next();node.quasis.push(finishNode(elem,"TemplateElement"));if(tokType===_bquote){elem.tail=true;break}inTemplate=false;expect(_dollarBraceL);node.expressions.push(parseExpression());inTemplate=true;tokPos=tokEnd;expect(_braceR)}inTemplate=false;next();return finishNode(node,"TemplateLiteral")}function parseObj(){var node=startNode(),first=true,propHash={};node.properties=[];next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),isGenerator,isAsync;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;isGenerator=eat(_star)}parsePropertyName(prop);if(eat(_colon)){prop.value=parseExpression(true);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")){if(isGenerator||isAsync)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";prop.value=prop.key;prop.shorthand=true}else unexpected();checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}return finishNode(node,"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;node.params=[];if(options.ecmaVersion>=6){node.defaults=[];node.rest=null;node.generator=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){if(isAsync&&tokType===_star)unexpected();node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);var defaults=node.defaults,hasDefaults=false;for(var i=0,lastI=params.length-1;i<=lastI;i++){var param=params[i];if(param.type==="AssignmentExpression"&&param.operator==="="){hasDefaults=true;params[i]=param.left;defaults.push(param.right)}else{toAssignable(param,i===lastI,true);defaults.push(null);if(param.type==="SpreadElement"){params.length--;node.rest=param.argument;break}}}node.params=params;if(!hasDefaults)node.defaults=[];parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionParams(node){var defaults=[],hasDefaults=false;expect(_parenL);for(;;){if(eat(_parenR)){break}else if(options.ecmaVersion>=6&&eat(_ellipsis)){node.rest=toAssignable(parseExprAtom(),false,true);checkSpreadAssign(node.rest);expect(_parenR);defaults.push(null);break}else{node.params.push(options.ecmaVersion>=6?toAssignable(parseExprAtom(),false,true):parseIdent());if(options.ecmaVersion>=6){if(eat(_eq)){hasDefaults=true;defaults.push(parseExpression(true))}else{defaults.push(null)}}if(!eat(_comma)){expect(_parenR);break}}}if(hasDefaults)node.defaults=defaults}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseExpression(true);node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash);if(node.rest)checkFunctionParam(node.rest,nameHash)}}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;node.superClass=eat(_extends)?parseExpression():null;var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){var method=startNode();if(tokType===_name&&tokVal==="static"){next();method["static"]=true}else{method["static"]=false}var isAsync=false;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}var isGenerator=eat(_star);parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}method.value=parseMethod(isGenerator,isAsync);classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseExprList(close,allowTrailingComma,allowEmpty){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma)elts.push(null);else elts.push(parseExpression(true))}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||tokType===_async){node.declaration=parseStatement();node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){node.declaration=parseExpression(true);node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(tokType===_name&&tokVal==="from"){next();node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent(true)}else{node.name=null}nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom();node.kind=""}else{node.specifiers=parseImportSpecifiers();if(tokType!==_name||tokVal!=="from")unexpected();next();node.source=tokType===_string?parseExprAtom():unexpected();node.kind=node.specifiers[0]["default"]?"default":"named"}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();if(tokType!==_name||tokVal!=="as")unexpected();next();node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent()}else{node.name=null}checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseExpression(true)}return finishNode(node,"YieldExpression")}function parseAwait(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseExpression(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=toAssignable(parseExprAtom());checkLVal(block.left,true);if(tokType!==_name||tokVal!=="of")unexpected();next();block.of=true;block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedXJSName(object){if(object.type==="XJSIdentifier"){return object.name}if(object.type==="XJSNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="XJSMemberExpression"){return getQualifiedXJSName(object.object)+"."+getQualifiedXJSName(object.property)}}function parseXJSIdentifier(){var node=startNode();if(tokType===_xjsName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"XJSIdentifier")}function parseXJSNamespacedName(){var node=startNode();node.namespace=parseXJSIdentifier();expect(_colon);node.name=parseXJSIdentifier();return finishNode(node,"XJSNamespacedName")}function parseXJSMemberExpression(){var start=storeCurrentPos();var node=parseXJSIdentifier();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseXJSIdentifier();node=finishNode(newNode,"XJSMemberExpression")}return node}function parseXJSElementName(){switch(nextChar()){case":":return parseXJSNamespacedName();case".":return parseXJSMemberExpression();default:return parseXJSIdentifier()}}function parseXJSAttributeName(){if(nextChar()===":"){return parseXJSNamespacedName()}return parseXJSIdentifier()}function parseXJSAttributeValue(){switch(tokType){case _braceL:var node=parseXJSExpressionContainer();if(node.expression.type==="XJSEmptyExpression"){raise(node.start,"XJS attributes must only be assigned a non-empty "+"expression")}return node;case _lt:return parseXJSElement();case _xjsText:return parseExprAtom();default:raise(tokStart,"XJS value should be either an expression or a quoted XJS text")}}function parseXJSEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"XJSEmptyExpression")}function parseXJSExpressionContainer(){var node=startNode();var origInXJSTag=inXJSTag,origInXJSChild=inXJSChild;inXJSTag=false;inXJSChild=false;inXJSChildExpression=origInXJSChild;next();node.expression=tokType===_braceR?parseXJSEmptyExpression():parseExpression();inXJSTag=origInXJSTag;inXJSChild=origInXJSChild;inXJSChildExpression=false;expect(_braceR);return finishNode(node,"XJSExpressionContainer")}function parseXJSAttribute(){if(tokType===_braceL){var tokStart1=tokStart,tokStartLoc1=tokStartLoc;var origInXJSTag=inXJSTag;inXJSTag=false;next();if(tokType!==_ellipsis)unexpected();var node=parseMaybeUnary();inXJSTag=origInXJSTag;expect(_braceR);node.type="XJSSpreadAttribute";node.start=tokStart1;node.end=lastEnd;if(options.locations){node.loc.start=tokStartLoc1;node.loc.end=lastEndLoc}if(options.ranges){node.range=[tokStart1,lastEnd]}return node}var node=startNode();node.name=parseXJSAttributeName();if(tokType===_eq){next();node.value=parseXJSAttributeValue()}else{node.value=null}return finishNode(node,"XJSAttribute")}function parseXJSChild(){switch(tokType){case _braceL:return parseXJSExpressionContainer();case _xjsText:return parseExprAtom();default:return parseXJSElement()}}function parseXJSOpeningElement(){var node=startNode(),attributes=node.attributes=[];var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;next();node.name=parseXJSElementName();while(tokType!==_eof&&tokType!==_slash&&tokType!==_gt){attributes.push(parseXJSAttribute())}inXJSTag=false;if(node.selfClosing=!!eat(_slash)){inXJSTag=origInXJSTag;inXJSChild=origInXJSChild}else{inXJSChild=true}expect(_gt);return finishNode(node,"XJSOpeningElement")}function parseXJSClosingElement(){var node=startNode();var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;tokRegexpAllowed=false;expect(_ltSlash);node.name=parseXJSElementName();skipSpace();inXJSChild=origInXJSChild;inXJSTag=origInXJSTag;tokRegexpAllowed=false;if(inXJSChild){tokPos=tokEnd}expect(_gt);return finishNode(node,"XJSClosingElement")}function parseXJSElement(){var node=startNode();var children=[];var origInXJSChild=inXJSChild;var openingElement=parseXJSOpeningElement();var closingElement=null;if(!openingElement.selfClosing){while(tokType!==_eof&&tokType!==_ltSlash){inXJSChild=true;children.push(parseXJSChild())}inXJSChild=origInXJSChild;closingElement=parseXJSClosingElement();if(getQualifiedXJSName(closingElement.name)!==getQualifiedXJSName(openingElement.name)){raise(closingElement.start,"Expected corresponding XJS closing tag for '"+getQualifiedXJSName(openingElement.name)+"'")}}if(!origInXJSChild&&tokType===_lt){raise(tokStart,"Adjacent XJS elements must be wrapped in an enclosing tag")}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"XJSElement")}})},{}],2:[function(require,module,exports){(function(global){var transform=module.exports=require("./transformation/transform");transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i in _scripts){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transform":27}],3:[function(require,module,exports){module.exports=File;var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation/transform");var generate=require("./generation/generator");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var _=require("lodash");function File(opts){this.opts=File.normaliseOptions(opts);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);this.declarations={};this.uids={};this.ast={}}File.declarations=["extends","class-props","slice","apply-constructor","tagged-template-literal"];File.normaliseOptions=function(opts){opts=_.cloneDeep(opts||{});_.defaults(opts,{whitespace:true,blacklist:[],whitelist:[],sourceMap:false,comments:true,filename:"unknown",modules:"common",runtime:false,code:true});opts.filename=opts.filename.replace(/\\/g,"/");_.defaults(opts,{filenameRelative:opts.filename});_.defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.runtime===true){opts.runtime="to5Runtime"}transform._ensureTransformerNames("blacklist",opts.blacklist);transform._ensureTransformerNames("whitelist",opts.whitelist);return opts};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("unknown module formatter type "+type) }return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.addDeclaration=function(name){if(!_.contains(File.declarations,name)){throw new ReferenceError("unknown declaration "+name)}var declar=this.declarations[name];if(declar)return declar.uid;var ref;var runtimeNamespace=this.opts.runtime;if(runtimeNamespace){name=t.identifier(t.toIdentifier(name));return t.memberExpression(t.identifier(runtimeNamespace),name)}else{ref=util.template(name)}var uid=t.identifier(this.generateUid(name));this.declarations[name]={uid:uid,node:ref};return uid};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.parse=function(code){code=(code||"")+"";var self=this;this.code=code;code=this.parseShebang(code);return util.parse(this.opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){this.ast=ast;this.scope=new Scope(null,ast.program);var self=this;_.each(transform.transformers,function(transformer){transformer.transform(self)})};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;if(!opts.code){return{code:"",map:null,ast:ast}}var result=generate(ast,opts,this.code);if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}result.ast=result;return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name);scope=scope||this.scope;var uid;do{uid=this._generateUid(name)}while(scope.has(uid));return uid};File.prototype._generateUid=function(name){var uids=this.uids;var i=uids[name]||1;var id=name;if(i>1)id+=i;uids[name]=i+1;return"_"+id}},{"./generation/generator":5,"./transformation/transform":27,"./traverse/scope":62,"./types":65,"./util":67,lodash:98}],4:[function(require,module,exports){module.exports=Buffer;var util=require("../util");var _=require("lodash");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){if(this.format.semicolons)this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.slice(0,-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(!this.buf)return;if(this.format.compact)return;if(this.endsWith("{\n"))return;if(_.isBoolean(i)){removeLast=i;i=null}if(_.isNumber(i)){if(this.endsWith(util.repeat(i,"\n")))return;var self=this;_.times(i,function(){self.newline(null,removeLast)});return}if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this.buf=this.buf.replace(/\n +$/,"\n");this._push("\n")};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){return this.buf.slice(-str.length)===str};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var chars=[].concat(cha);return _.contains(chars,_.last(buf))}},{"../util":67,lodash:98}],5:[function(require,module,exports){module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var _=require("lodash");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}_.each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(opts){return _.merge({parentheses:true,semicolons:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:" ",base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),base:require("./generators/base"),jsx:require("./generators/jsx")};_.each(CodeGenerator.generators,function(generator){_.extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent)}self.newline(lines)};if(this[node.type]){this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");var needsParens=parent!==node._parent&&n.needsParens(node,parent);if(needsParens)this.push("(");this[node.type](node,this.buildPrint(node),parent);if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node "+node.type+" "+JSON.stringify(node))}};CodeGenerator.prototype.printJoin=function(print,nodes,opts){opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();_.each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}_.each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;_.each(comments,function(comment){self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":65,"../util":67,"./buffer":4,"./generators/base":6,"./generators/classes":7,"./generators/comprehensions":8,"./generators/expressions":9,"./generators/jsx":10,"./generators/methods":11,"./generators/modules":12,"./generators/statements":13,"./generators/template-literals":14,"./generators/types":15,"./node":16,"./position":19,"./source-map":20,"./whitespace":21,lodash:98}],6:[function(require,module,exports){exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],7:[function(require,module,exports){exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],8:[function(require,module,exports){exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],9:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.ParenthesizedExpression=function(node,print){this.push("(");print(node.expression);this.push(")")};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");print.join(node.arguments,{separator:", "});this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate)this.push("*");if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentExpression=function(node,print){print(node.left);this.push(" "+node.operator+" ");print(node.right)};exports.MemberExpression=function(node,print){print(node.object);if(node.computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(node.object)&&util.isInteger(node.object.value)){this.push(".")}this.push(".");print(node.property)}}},{"../../types":65,"../../util":67}],10:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.XJSAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.XJSIdentifier=function(node){this.push(node.name)};exports.XJSNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.XJSMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.XJSSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.XJSExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.XJSElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();_.each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.XJSOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.space();print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.XJSClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.XJSEmptyExpression=function(){}},{"../../types":65,lodash:98}],11:[function(require,module,exports){var t=require("../../types");exports._params=function(node,print){var self=this;this.push("(");print.join(node.params,{separator:", ",iterator:function(param,i){var def=node.defaults&&node.defaults[i];if(def){self.push(" = ");print(def)}}});if(node.rest){if(node.params.length){this.push(", ")}this.push("...");print(node.rest)}this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.space();print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.space();if(node.id)print(node.id);this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&!node.defaults.length&&!node.rest&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":65}],12:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;_.each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}if(!spec.default&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":65,lodash:98}],13:[function(require,module,exports){var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(") ");print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.space();this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.space();print(node.test)}this.push(";");if(node.update){this.space();print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.space();print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();print(node.handler);if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(") {");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.space();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");print.join(node.declarations,{separator:", "});if(!t.isFor(parent)){this.semicolon()}};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.push(" = ");print(node.init)}else{print(node.id)}}},{"../../types":65}],14:[function(require,module,exports){var _=require("lodash");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;_.each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{lodash:98}],15:[function(require,module,exports){var _=require("lodash");exports.Identifier=function(node){this.push(node.name)};exports.SpreadElement=function(node,print){this.push("...");print(node.argument)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");_.each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u007f-\uffff]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{lodash:98}],16:[function(require,module,exports){module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var _=require("lodash");var find=function(obj,node,parent){var result;_.each(obj,function(fn,type){if(t["is"+type](node)){result=fn(node,parent);if(result!=null)return false}});return result};function Node(node,parent){this.parent=parent;this.node=node}Node.prototype.isUserWhitespacable=function(){var parent=this.parent;var node=this.node;if(t.isUserWhitespacable(node)||t.isSequenceExpression(parent)){return true}return false};Node.prototype.needsWhitespace=function(type){var parent=this.parent;var node=this.node;if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;_.each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.prototype.needsWhitespaceBefore=function(){return this.needsWhitespace("before")};Node.prototype.needsWhitespaceAfter=function(){return this.needsWhitespace("after")};Node.prototype.needsParens=function(){var parent=this.parent;var node=this.node;if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){return t.isCallExpression(node)||_.some(node,function(val){return t.isCallExpression(val)})}return find(parens,node,parent)};_.each(Node.prototype,function(fn,key){Node[key]=function(node,parent){var n=new Node(node,parent);var args=_.toArray(arguments).slice(2);return n[key].apply(n,args)}})},{"../../types":65,"./parentheses":17,"./whitespace":18,lodash:98}],17:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var PRECEDENCE={};_.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],function(tier,i){_.each(tier,function(op){PRECEDENCE[op]=i})});exports.Binary=function(node,parent){if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.Literal=function(node,parent){if(_.isNumber(node.value)&&t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":65,lodash:98}],18:[function(require,module,exports){var _=require("lodash");var t=require("../../types");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{},list:{VariableDeclaration:function(node){return _.map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};_.each({Function:1,Class:1,For:1,SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(_.isNumber(amounts))amounts={after:amounts,before:amounts};_.each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})},{"../../types":65,lodash:98}],19:[function(require,module,exports){module.exports=Position;var _=require("lodash");function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line++;self.column=0}else{self.column++}})};Position.prototype.unshift=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line--}else{self.column--}})}},{lodash:98}],20:[function(require,module,exports){module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];if(generated.line===original.line&&generated.column===original.column)return;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":65,"source-map":106}],21:[function(require,module,exports){module.exports=Whitespace;var _=require("lodash");function Whitespace(tokens,comments){this.tokens=_.sortBy(tokens.concat(comments),"start");this.used=[]}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.start===token.start){startToken=tokens[i-1];endToken=token;return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.end===token.end){startToken=token;endToken=tokens[i+1];return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(!_.contains(this.used,line)){this.used.push(line);lines++}}return lines}},{lodash:98}],22:[function(require,module,exports){var t=require("./types");var _=require("lodash");var types=require("ast-types");var def=types.Type.def;def("File").bases("Node").build("program").field("program",def("Program"));def("ParenthesizedExpression").bases("Expression").build("expression").field("expression",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));types.finalize();var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS)},{"./types":65,"ast-types":81,estraverse:93,lodash:98}],23:[function(require,module,exports){module.exports=AMDFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(file){this.file=file;this.ids={}}util.inherits(AMDFormatter,CommonJSFormatter);AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];_.each(this.ids,function(id,name){names.push(t.literal(name))});names=t.arrayExpression(names);var params=_.values(this.ids);params.unshift(t.identifier("exports"));var moduleName=this.getModuleName();var container=t.functionExpression(null,params,t.blockStatement(body));var call=t.callExpression(t.identifier("define"),[t.literal(moduleName),names,container]);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}filenameRelative=filenameRelative.replace(/\.(.*?)$/,"");moduleName+=filenameRelative;return moduleName};AMDFormatter.prototype._push=function(node){var id=node.source.value;var ids=this.ids;if(ids[id]){return ids[id]}else{return this.ids[id]=t.identifier(this.file.generateUid(id))}};AMDFormatter.prototype.import=function(node){this._push(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier); var id=specifier.id;if(specifier.default){id=t.identifier("default")}var ref;if(t.isImportBatchSpecifier(specifier)){ref=this._push(node)}else{ref=t.memberExpression(this._push(node),id,false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var self=this;return this._exportSpecifier(function(){return self._push(node)},specifier,node,nodes)}},{"../../types":65,"../../util":67,"./common":24,lodash:98}],24:[function(require,module,exports){module.exports=CommonJSFormatter;var util=require("../../util");var t=require("../../types");function CommonJSFormatter(file){this.file=file}CommonJSFormatter.prototype.import=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source.raw},true))};CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=t.identifier("default")}var templateName="require-assign";if(specifier.type!=="ImportBatchSpecifier")templateName+="-key";nodes.push(util.template(templateName,{VARIABLE_NAME:variableName,MODULE_NAME:node.source.raw,KEY:specifier.id}))};CommonJSFormatter.prototype.export=function(node,nodes){var declar=node.declaration;if(node.default){var ref=declar;if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}nodes.push(util.template("exports-default",{VALUE:ref},true))}else{var assign;if(t.isVariableDeclaration(declar)){var decl=declar.declarations[0];if(decl.init){decl.init=util.template("exports-assign",{VALUE:decl.init,KEY:decl.id})}nodes.push(declar)}else{assign=util.template("exports-assign",{VALUE:declar.id,KEY:declar.id},true);nodes.push(t.toStatement(declar));nodes.push(assign);if(t.isFunctionDeclaration(declar)){assign._blockHoist=true}}}};CommonJSFormatter.prototype._exportSpecifier=function(getRef,specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){if(t.isExportBatchSpecifier(specifier)){nodes.push(util.template("exports-wildcard",{OBJECT:getRef()},true))}else{nodes.push(util.template("exports-assign-key",{VARIABLE_NAME:variableName.name,OBJECT:getRef(),KEY:specifier.id},true))}}else{nodes.push(util.template("exports-assign",{VALUE:specifier.id,KEY:variableName},true))}};CommonJSFormatter.prototype.exportSpecifier=function(specifier,node,nodes){return this._exportSpecifier(function(){return t.callExpression(t.identifier("require"),[node.source])},specifier,node,nodes)}},{"../../types":65,"../../util":67}],25:[function(require,module,exports){module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.import=function(){};IgnoreFormatter.prototype.importSpecifier=function(){};IgnoreFormatter.prototype.export=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":65}],26:[function(require,module,exports){module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function UMDFormatter(file){this.file=file;this.ids={}}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];_.each(this.ids,function(id,name){names.push(t.literal(name))});var ids=_.values(this.ids);var args=[t.identifier("exports")].concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var moduleName=this.getModuleName();var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:[t.literal(moduleName),t.arrayExpression([t.literal("exports")].concat(names))],COMMON_ARGUMENTS:names.map(function(name){return t.callExpression(t.identifier("require"),[name])})});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":65,"../../util":67,"./amd":23,lodash:98}],27:[function(require,module,exports){module.exports=transform;var Transformer=require("./transformer");var File=require("../file");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform._ensureTransformerNames=function(type,keys){_.each(keys,function(key){if(!_.has(transform.transformers,key)){throw new ReferenceError("unknown transformer "+key+" specified in "+type)}})};transform.transformers={};transform.moduleFormatters={common:require("./modules/common"),ignore:require("./modules/ignore"),amd:require("./modules/amd"),umd:require("./modules/umd")};_.each({modules:require("./transformers/modules"),propertyNameShorthand:require("./transformers/property-name-shorthand"),arrayComprehension:require("./transformers/array-comprehension"),generatorComprehension:require("./transformers/generator-comprehension"),arrowFunctions:require("./transformers/arrow-functions"),classes:require("./transformers/classes"),_propertyLiterals:require("./transformers/_property-literals"),computedPropertyNames:require("./transformers/computed-property-names"),spread:require("./transformers/spread"),templateLiterals:require("./transformers/template-literals"),propertyMethodAssignment:require("./transformers/property-method-assignment"),defaultParameters:require("./transformers/default-parameters"),restParameters:require("./transformers/rest-parameters"),destructuring:require("./transformers/destructuring"),forOf:require("./transformers/for-of"),unicodeRegex:require("./transformers/unicode-regex"),react:require("./transformers/react"),constants:require("./transformers/constants"),letScoping:require("./transformers/let-scoping"),generators:require("./transformers/generators"),_blockHoist:require("./transformers/_block-hoist"),_declarations:require("./transformers/_declarations"),_aliasFunctions:require("./transformers/_alias-functions"),useStrict:require("./transformers/use-strict"),_memberExpressionKeywords:require("./transformers/_member-expression-keywords"),_moduleFormatter:require("./transformers/_module-formatter")},function(transformer,key){transform.transformers[key]=new Transformer(key,transformer)})},{"../file":3,"./modules/amd":23,"./modules/common":24,"./modules/ignore":25,"./modules/umd":26,"./transformer":28,"./transformers/_alias-functions":29,"./transformers/_block-hoist":30,"./transformers/_declarations":31,"./transformers/_member-expression-keywords":32,"./transformers/_module-formatter":33,"./transformers/_property-literals":34,"./transformers/array-comprehension":35,"./transformers/arrow-functions":36,"./transformers/classes":37,"./transformers/computed-property-names":38,"./transformers/constants":39,"./transformers/default-parameters":40,"./transformers/destructuring":41,"./transformers/for-of":42,"./transformers/generator-comprehension":43,"./transformers/generators":46,"./transformers/let-scoping":51,"./transformers/modules":52,"./transformers/property-method-assignment":53,"./transformers/property-name-shorthand":54,"./transformers/react":55,"./transformers/rest-parameters":56,"./transformers/spread":57,"./transformers/template-literals":58,"./transformers/unicode-regex":59,"./transformers/use-strict":60,lodash:98}],28:[function(require,module,exports){module.exports=Transformer;var traverse=require("../traverse");var t=require("../types");var _=require("lodash");function Transformer(key,transformer){this.transformer=Transformer.normalise(transformer);this.key=key}Transformer.normalise=function(transformer){if(_.isFunction(transformer)){transformer={ast:transformer}}_.each(transformer,function(fns,type){if(type[0]==="_")return;if(_.isFunction(fns))fns={enter:fns};transformer[type]=fns});return transformer};Transformer.prototype.transform=function(file){if(!this.canRun(file))return;var transformer=this.transformer;var ast=file.ast;var astRun=function(key){if(transformer.ast&&transformer.ast[key]){transformer.ast[key](ast,file)}};astRun("enter");var build=function(exit){return function(node,parent,scope){var types=[node.type].concat(t.ALIAS_KEYS[node.type]||[]);var fns=transformer.all;_.each(types,function(type){fns=transformer[type]||fns});if(!fns)return;var fn=fns.enter;if(exit)fn=fns.exit;if(!fn)return;return fn(node,parent,file,scope)}};traverse(ast,{enter:build(),exit:build(true)});astRun("exit")};Transformer.prototype.canRun=function(file){var opts=file.opts;var key=this.key;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;if(key[0]!=="_"){var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false}return true}},{"../traverse":61,"../types":65,lodash:98}],29:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var go=function(getBody,node,file,scope){var argumentsId;var thisId;var getArgumentsId=function(){return argumentsId=argumentsId||t.identifier(file.generateUid("arguments",scope))};var getThisId=function(){return thisId=thisId||t.identifier(file.generateUid("this",scope))};traverse(node,function(node){if(!node._aliasFunction){if(t.isFunction(node)){return false}else{return}}traverse(node,function(node,parent){if(t.isFunction(node)&&!node._aliasFunction){return false}if(node._ignoreAliasFunctions)return;var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=getArgumentsId}else if(t.isThisExpression(node)){getId=getThisId}else{return}if(t.isReferenced(node,parent))return getId()});return false});var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.identifier("this"))}};exports.Program=function(node,parent,file,scope){go(function(){return node.body},node,file,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,file,scope){go(function(){t.ensureBlock(node);return node.body.body},node,file,scope)}},{"../../traverse":61,"../../types":65}],30:[function(require,module,exports){exports.BlockStatement=exports.Program={exit:function(node){var unshift=[];node.body=node.body.filter(function(bodyNode){if(bodyNode._blockHoist){unshift.push(bodyNode);return false}else{return true}});node.body=unshift.concat(node.body)}}},{}],31:[function(require,module,exports){var t=require("../../types");var _=require("lodash");module.exports=function(ast,file){var body=ast.program.body;_.each(file.declarations,function(declar){body.unshift(t.variableDeclaration("var",[t.variableDeclarator(declar.uid,declar.node)]))})}},{"../../types":65,lodash:98}],32:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");exports.MemberExpression=function(node){var prop=node.property;if(t.isIdentifier(prop)&&esutils.keyword.isKeywordES6(prop.name,true)){node.property=t.literal(prop.name);node.computed=true}}},{"../../types":65,esutils:97}],33:[function(require,module,exports){var transform=require("../transform");exports.ast={exit:function(ast,file){if(!transform.transformers.modules.canRun(file))return;if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../transform":27}],34:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&_.isString(key.value)&&esutils.keyword.isIdentifierName(key.value)){key.type="Identifier";key.name=key.value;delete key.value;node.computed=false}}},{"../../types":65,esutils:97,lodash:98}],35:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");var singleArrayExpression=function(node){var block=node.blocks[0];var templateName="array-expression-comprehension-map";if(node.filter)templateName="array-expression-comprehension-filter";var result=util.template(templateName,{STATEMENT:node.body,FILTER:node.filter,ARRAY:block.right,KEY:block.left});_.each([result.callee.object,result],function(call){if(t.isCallExpression(call)){call.arguments[0]._aliasFunction=true}});return result};var multiple=function(node,file){var uid=file.generateUid("arr");var container=util.template("array-comprehension-container",{KEY:uid});container.callee.expression._aliasFunction=true;var block=container.callee.expression.body;var body=block.body;var returnStatement=body.pop();body.push(exports._build(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container};exports._build=function(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=exports._build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("var",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))};exports.ComprehensionExpression=function(node,parent,file){if(node.generator)return;if(node.blocks.length===1&&t.isArrayExpression(node.blocks[0].right)){return singleArrayExpression(node)}else{return multiple(node,file)}}},{"../../types":65,"../../util":67,lodash:98}],36:[function(require,module,exports){var t=require("../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction=true;node.expression=false;node.type="FunctionExpression";return node}},{"../../types":65}],37:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ClassDeclaration=function(node,parent,file,scope){return t.variableDeclaration("let",[t.variableDeclarator(node.id,new Class(node,file,scope).run())])};exports.ClassExpression=function(node,parent,file,scope){return new Class(node,file,scope).run()};var getMemberExpressionObject=function(node){while(t.isMemberExpression(node)){node=node.object}return node};function Class(node,file,scope){this.scope=scope;this.node=node;this.file=file;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||t.identifier(file.generateUid("class",scope));this.superName=node.superClass}Class.prototype.run=function(){var superClassArgument=this.superName;var superClassCallee=this.superName;var superName=this.superName;var className=this.className;var file=this.file;if(superName){if(t.isMemberExpression(superName)){superClassArgument=superClassCallee=getMemberExpressionObject(superName)}else if(!t.isIdentifier(superName)){superClassArgument=superName;superClassCallee=superName=t.identifier(file.generateUid("ref",this.scope))}}this.superName=superName;var container=util.template("class",{CLASS_NAME:className});var block=container.callee.expression.body;var body=this.body=block.body;var constructor=this.constructor=body[0].declarations[0].init;if(this.node.id)constructor.id=className;var returnStatement=body.pop();if(superName){body.push(t.expressionStatement(t.callExpression(file.addDeclaration("extends"),[className,superName])));container.arguments.push(superClassArgument);container.callee.expression.params.push(superClassCallee)}this.buildBody();if(body.length===1){return constructor}else{body.push(returnStatement);return container}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;var self=this;_.each(classBody,function(node){self.replaceInstanceSuperReferences(node);if(node.key.name==="constructor"){self.pushConstructor(node)}else{self.pushMethod(node)}});if(!this.hasConstructor&&superName){constructor.body.body.push(util.template("class-super-constructor-call",{SUPER_NAME:superName},true))}var instanceProps;var staticProps;if(!_.isEmpty(this.instanceMutatorMap)){var protoId=util.template("prototype-identifier",{CLASS_NAME:className});instanceProps=util.buildDefineProperties(this.instanceMutatorMap,protoId)}if(!_.isEmpty(this.staticMutatorMap)){staticProps=util.buildDefineProperties(this.staticMutatorMap,className)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addDeclaration("class-props"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var mutatorMap=this.instanceMutatorMap;if(node.static)mutatorMap=this.staticMutatorMap;var kind=node.kind;if(kind===""){kind="value";util.pushMutatorMap(mutatorMap,methodName,"writable",t.identifier("true"))}util.pushMutatorMap(mutatorMap,methodName,kind,node)};Class.prototype.superIdentifier=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};Class.prototype.replaceInstanceSuperReferences=function(methodNode){var method=methodNode.value;var self=this;traverse(method,function(node,parent){if(t.isIdentifier(node,{name:"super"})){return self.superIdentifier(methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;callee.property=t.memberExpression(callee.property,t.identifier("call"));node.arguments.unshift(t.thisExpression())}})};Class.prototype.pushConstructor=function(method){if(method.kind!==""){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct.defaults=fn.defaults;construct.params=fn.params;construct.body=fn.body;construct.rest=fn.rest}},{"../../traverse":61,"../../types":65,"../../util":67,lodash:98}],38:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node,parent,file){var hasComputed=false;var computed=[];node.properties=node.properties.filter(function(prop){if(prop.computed){hasComputed=true;computed.unshift(prop);return false}else{return true}});if(!hasComputed)return;var objId=util.getUid(parent,file);var container=util.template("function-return-obj",{KEY:objId,OBJECT:node});var containerCallee=container.callee.expression;var containerBody=containerCallee.body.body;containerCallee._aliasFunction=true;_.each(computed,function(prop){containerBody.unshift(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,true),prop.value)))});return container}},{"../../types":65,"../../util":67,lodash:98}],39:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var _=require("lodash");exports.Program=exports.BlockStatement=exports.ForInStatement=exports.ForOfStatement=exports.ForStatement=function(node,parent,file){var constants={};var check=function(parent,names){_.each(names,function(nameNode,name){if(!_.has(constants,name))return;if(parent&&t.isBlockStatement(parent)&&parent!==constants[name])return;throw file.errorWithNode(nameNode,name+" is read-only")})};var getIds=function(node){return t.getIds(node,true,["MemberExpression"])};_.each(node.body,function(child,parent){if(child&&t.isVariableDeclaration(child,{kind:"const"})){_.each(child.declarations,function(declar){_.each(getIds(declar),function(nameNode,name){var names={};names[name]=nameNode;check(parent,names);constants[name]=parent});declar._ignoreConstant=true});child._ignoreConstant=true;child.kind="let"}});if(_.isEmpty(constants))return;traverse(node,function(child,parent){if(child._ignoreConstant)return;if(t.isVariableDeclaration(child))return;if(t.isVariableDeclarator(child)||t.isDeclaration(child)||t.isAssignmentExpression(child)){check(parent,getIds(child))}})}},{"../../traverse":61,"../../types":65,lodash:98}],40:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.Function=function(node,parent,file,scope){if(!node.defaults||!node.defaults.length)return;t.ensureBlock(node);var ids=node.params.map(function(param){return t.getIds(param)});var closure=false;_.each(node.defaults,function(def,i){if(!def)return;var param=node.params[i];_.each(ids.slice(i),function(ids){var check=function(node,parent){if(!t.isIdentifier(node)||!t.isReferenced(node,parent))return;if(_.contains(ids,node.name)){throw file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}if(scope.has(node.name)){closure=true}};check(def,node);traverse(def,check)});var has=scope.get(param.name);if(has&&!_.contains(node.params,has)){closure=true}});var body=[];_.each(node.defaults,function(def,i){if(!def)return;body.push(util.template("if-undefined-set-to",{VARIABLE:node.params[i],DEFAULT:def},true))});if(closure){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}node.defaults=[]}},{"../../traverse":61,"../../types":65,"../../util":67,lodash:98}],41:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildVariableAssign=function(kind,id,init){if(kind===false){return t.expressionStatement(t.assignmentExpression("=",id,init))}else{return t.variableDeclaration(kind,[t.variableDeclarator(id,init)])}};var push=function(kind,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(kind,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(kind,nodes,elem,parentId)}else if(t.isMemberExpression(elem)){nodes.push(buildVariableAssign(false,elem,parentId))}else{nodes.push(buildVariableAssign(kind,elem,parentId))}};var pushObjectPattern=function(kind,nodes,pattern,parentId){_.each(pattern.properties,function(prop){var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key);if(t.isPattern(pattern2)){push(kind,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(kind,pattern2,patternId2))}})};var pushArrayPattern=function(kind,nodes,pattern,parentId){_.each(pattern.elements,function(elem,i){if(!elem)return;var newPatternId;if(t.isSpreadElement(elem)){newPatternId=t.callExpression(t.memberExpression(parentId,t.identifier("slice")),[t.literal(i)]);elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}push(kind,nodes,elem,newPatternId)})};var pushPattern=function(opts){var kind=opts.kind;var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var file=opts.file;var scope=opts.scope;if(!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=t.identifier(file.generateUid("ref",scope));nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,parentId)]));parentId=key}push(kind,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,file,scope){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=t.identifier(file.generateUid("ref",scope));node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push(declar.kind,nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,file,scope){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=t.identifier(file.generateUid("ref",scope));pushPattern({kind:"var",nodes:nodes,pattern:pattern,id:parentId,file:file,scope:scope});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.ExpressionStatement=function(node,parent,file,scope){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;var nodes=[];var ref=t.identifier(file.generateUid("ref",scope));nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push(false,nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,file){if(parent.type==="ExpressionStatement")return;if(!t.isPattern(node.left))return;throw file.errorWithNode(node,"AssignmentExpression destructuring outside of a ExpressionStatement is forbidden due to current 6to5 limitations")};exports.VariableDeclaration=function(node,parent,file,scope){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var hasPattern=false;_.each(node.declarations,function(declar){if(t.isPattern(declar.id)){hasPattern=true;return false}});if(!hasPattern)return;_.each(node.declarations,function(declar){var patternId=declar.init;var pattern=declar.id;if(t.isPattern(pattern)&&patternId){pushPattern({kind:node.kind,nodes:nodes,pattern:pattern,id:patternId,file:file,scope:scope})}else{nodes.push(buildVariableAssign(node.kind,declar.id,declar.init))}});if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){var declar;_.each(nodes,function(node){declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)});return declar}return nodes}},{"../../types":65,lodash:98}],42:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.ForOfStatement=function(node,parent,file,scope){var left=node.left;var declar;var stepKey=t.identifier(file.generateUid("step",scope));var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var node2=util.template("for-of",{ITERATOR_KEY:file.generateUid("iterator",scope),STEP_KEY:stepKey,OBJECT:node.right});t.ensureBlock(node);var block=node2.body;block.body.push(declar);block.body=block.body.concat(node.body.body);return node2}},{"../../types":65,"../../util":67}],43:[function(require,module,exports){var arrayComprehension=require("./array-comprehension");var t=require("../../types");exports.ComprehensionExpression=function(node){if(!node.generator)return;var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);body.push(arrayComprehension._build(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])}},{"../../types":65,"./array-comprehension":35}],44:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var b=types.builders;var n=types.namedTypes;var leap=require("./leap");var meta=require("./meta");var runtimeProperty=require("./util").runtimeProperty;var runtimeKeysMethod=runtimeProperty("keys");var hasOwn=Object.prototype.hasOwnProperty;function Emitter(contextId){assert.ok(this instanceof Emitter);n.Identifier.assert(contextId);Object.defineProperties(this,{contextId:{value:contextId},listing:{value:[]},marked:{value:[true]},finalLoc:{value:loc()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new leap.LeapManager(this)}})}var Ep=Emitter.prototype;exports.Emitter=Emitter;function loc(){return b.literal(-1)}Ep.mark=function(loc){n.Literal.assert(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Ep.emit=function(node){if(n.Expression.check(node))node=b.expressionStatement(node);n.Statement.assert(node);this.listing.push(node)};Ep.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Ep.assign=function(lhs,rhs){return b.expressionStatement(b.assignmentExpression("=",lhs,rhs))};Ep.contextProperty=function(name,computed){return b.memberExpression(this.contextId,computed?b.literal(name):b.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Ep.isVolatileContextProperty=function(expr){if(n.MemberExpression.check(expr)){if(expr.computed){return true}if(n.Identifier.check(expr.object)&&n.Identifier.check(expr.property)&&expr.object.name===this.contextId.name&&hasOwn.call(volatileContextPropertyNames,expr.property.name)){return true}}return false};Ep.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Ep.setReturnValue=function(valuePath){n.Expression.assert(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Ep.clearPendingException=function(tryLoc,assignee){n.Literal.assert(tryLoc);var catchCall=b.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Ep.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(b.breakStatement())};Ep.jumpIf=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);this.emit(b.ifStatement(test,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};Ep.jumpIfNot=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);var negatedTest;if(n.UnaryExpression.check(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=b.unaryExpression("!",test)}this.emit(b.ifStatement(negatedTest,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};var nextTempId=0;Ep.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Ep.getContextFunction=function(id){var node=b.functionExpression(id||null,[this.contextId],b.blockStatement([this.getDispatchLoop()]),false,false);node._aliasFunction=true;return node};Ep.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(b.switchCase(b.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(b.switchCase(this.finalLoc,[]),b.switchCase(b.literal("end"),[b.returnStatement(b.callExpression(this.contextProperty("stop"),[]))]));return b.whileStatement(b.literal(true),b.switchStatement(b.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return n.BreakStatement.check(stmt)||n.ContinueStatement.check(stmt)||n.ReturnStatement.check(stmt)||n.ThrowStatement.check(stmt)}Ep.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return b.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc }return b.arrayExpression(triple)}))};Ep.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.assert(node);if(n.Statement.check(node))return self.explodeStatement(path);if(n.Expression.check(node))return self.explodeExpression(path,ignoreResult);if(n.Declaration.check(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Ep.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;var after,head;n.Statement.assert(stmt);if(labelId){n.Identifier.assert(labelId)}else{labelId=null}if(n.BlockStatement.check(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}switch(stmt.type){case"ExpressionStatement":self.explodeExpression(path.get("expression"),true);break;case"LabeledStatement":self.explodeStatement(path.get("body"),stmt.label);break;case"WhileStatement":var before=loc();after=loc();self.mark(before);self.jumpIfNot(self.explodeExpression(path.get("test")),after);self.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(before);self.mark(after);break;case"DoWhileStatement":var first=loc();var test=loc();after=loc();self.mark(first);self.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){self.explode(path.get("body"))});self.mark(test);self.jumpIf(self.explodeExpression(path.get("test")),first);self.mark(after);break;case"ForStatement":head=loc();var update=loc();after=loc();if(stmt.init){self.explode(path.get("init"),true)}self.mark(head);if(stmt.test){self.jumpIfNot(self.explodeExpression(path.get("test")),after)}else{}self.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){self.explodeStatement(path.get("body"))});self.mark(update);if(stmt.update){self.explode(path.get("update"),true)}self.jump(head);self.mark(after);break;case"ForInStatement":n.Identifier.assert(stmt.left);head=loc();after=loc();var keyIterNextFn=self.makeTempVar();self.emitAssign(keyIterNextFn,b.callExpression(runtimeKeysMethod,[self.explodeExpression(path.get("right"))]));self.mark(head);var keyInfoTmpVar=self.makeTempVar();self.jumpIf(b.memberExpression(b.assignmentExpression("=",keyInfoTmpVar,b.callExpression(keyIterNextFn,[])),b.identifier("done"),false),after);self.emitAssign(stmt.left,b.memberExpression(keyInfoTmpVar,b.identifier("value"),false));self.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(head);self.mark(after);break;case"BreakStatement":self.emitAbruptCompletion({type:"break",target:self.leapManager.getBreakLoc(stmt.label)});break;case"ContinueStatement":self.emitAbruptCompletion({type:"continue",target:self.leapManager.getContinueLoc(stmt.label)});break;case"SwitchStatement":var disc=self.emitAssign(self.makeTempVar(),self.explodeExpression(path.get("discriminant")));after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];n.SwitchCase.assert(c);if(c.test){condition=b.conditionalExpression(b.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}self.jump(self.explodeExpression(new types.NodePath(condition,path,"discriminant")));self.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});self.mark(after);if(defaultLoc.value===-1){self.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}break;case"IfStatement":var elseLoc=stmt.alternate&&loc();after=loc();self.jumpIfNot(self.explodeExpression(path.get("test")),elseLoc||after);self.explodeStatement(path.get("consequent"));if(elseLoc){self.jump(after);self.mark(elseLoc);self.explodeStatement(path.get("alternate"))}self.mark(after);break;case"ReturnStatement":self.emitAbruptCompletion({type:"return",value:self.explodeExpression(path.get("argument"))});break;case"TryStatement":after=loc();var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(self.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);self.tryEntries.push(tryEntry);self.updateContextPrevLoc(tryEntry.firstLoc);self.leapManager.withEntry(tryEntry,function(){self.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){self.jump(finallyLoc)}else{self.jump(after)}self.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=self.makeTempVar();self.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;n.CatchClause.assert(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(path.value.name===catchParamName&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)}});self.leapManager.withEntry(catchEntry,function(){self.explodeStatement(bodyPath)})}if(finallyLoc){self.updateContextPrevLoc(self.mark(finallyLoc));self.leapManager.withEntry(finallyEntry,function(){self.explodeStatement(path.get("finalizer"))});self.emit(b.callExpression(self.contextProperty("finish"),[finallyEntry.firstLoc]))}});self.mark(after);break;case"ThrowStatement":self.emit(b.throwStatement(self.explodeExpression(path.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Ep.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[b.literal(record.type)];if(record.type==="break"||record.type==="continue"){n.Literal.assert(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){n.Expression.assert(record.value);abruptArgs[1]=record.value}}this.emit(b.returnStatement(b.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!hasOwn.call(record,"target")}if(type==="break"||type==="continue"){return!hasOwn.call(record,"value")&&n.Literal.check(record.target)}if(type==="return"||type==="throw"){return hasOwn.call(record,"value")&&!hasOwn.call(record,"target")}return false}Ep.getUnmarkedCurrentLoc=function(){return b.literal(this.listing.length)};Ep.updateContextPrevLoc=function(loc){if(loc){n.Literal.assert(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Ep.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){n.Expression.assert(expr)}else{return expr}var self=this;var result,after;function finish(expr){n.Expression.assert(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}switch(expr.type){case"ParenthesizedExpression":return finish(self.explodeExpression(path.get("expression")));case"MemberExpression":return finish(b.memberExpression(self.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed));case"CallExpression":var oldCalleePath=path.get("callee");var newCallee=self.explodeExpression(oldCalleePath);if(!n.MemberExpression.check(oldCalleePath.node)&&n.MemberExpression.check(newCallee)){newCallee=b.sequenceExpression([b.literal(0),newCallee])}return finish(b.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"NewExpression":return finish(b.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"ObjectExpression":return finish(b.objectExpression(path.get("properties").map(function(propPath){return b.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})));case"ArrayExpression":return finish(b.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})));case"SequenceExpression":var lastIndex=expr.expressions.length-1;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result;case"LogicalExpression":after=loc();if(!ignoreResult){result=self.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){self.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");self.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);self.mark(after);return result;case"ConditionalExpression":var elseLoc=loc();after=loc();var test=self.explodeExpression(path.get("test"));self.jumpIfNot(test,elseLoc);if(!ignoreResult){result=self.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);self.jump(after);self.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);self.mark(after);return result;case"UnaryExpression":return finish(b.unaryExpression(expr.operator,self.explodeExpression(path.get("argument")),!!expr.prefix));case"BinaryExpression":return finish(b.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))));case"AssignmentExpression":return finish(b.assignmentExpression(expr.operator,self.explodeExpression(path.get("left")),self.explodeExpression(path.get("right"))));case"UpdateExpression":return finish(b.updateExpression(expr.operator,self.explodeExpression(path.get("argument")),expr.prefix));case"YieldExpression":after=loc();var arg=expr.argument&&self.explodeExpression(path.get("argument"));if(arg&&expr.delegate){result=self.makeTempVar();self.emit(b.returnStatement(b.callExpression(self.contextProperty("delegateYield"),[arg,b.literal(result.property.name),after])));self.mark(after);return result}self.emitAssign(self.contextProperty("next"),after);self.emit(b.returnStatement(arg||null));self.mark(after);return self.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"./leap":47,"./meta":48,"./util":49,assert:83,"ast-types":81}],45:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);n.Function.assert(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){n.VariableDeclaration.assert(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(b.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return b.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return b.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(n.VariableDeclaration.check(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(n.VariableDeclaration.check(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var assignment=b.expressionStatement(b.assignmentExpression("=",node.id,b.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(n.BlockStatement.check(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(n.Identifier.check(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!hasOwn.call(paramNames,name)){declarations.push(b.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return b.variableDeclaration("var",declarations)}},{assert:83,"ast-types":81}],46:[function(require,module,exports){module.exports=require("./visit").transform},{"./visit":50}],47:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var inherits=require("util").inherits;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);n.Literal.assert(returnLoc);Object.defineProperties(this,{returnLoc:{value:returnLoc}})}inherits(FunctionEntry,Entry);exports.FunctionEntry=FunctionEntry;function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Literal.assert(continueLoc);if(label){n.Identifier.assert(label)}else{label=null}Object.defineProperties(this,{breakLoc:{value:breakLoc},continueLoc:{value:continueLoc},label:{value:label}})}inherits(LoopEntry,Entry);exports.LoopEntry=LoopEntry;function SwitchEntry(breakLoc){Entry.call(this);n.Literal.assert(breakLoc);Object.defineProperties(this,{breakLoc:{value:breakLoc}})}inherits(SwitchEntry,Entry);exports.SwitchEntry=SwitchEntry;function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);n.Literal.assert(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);Object.defineProperties(this,{firstLoc:{value:firstLoc},catchEntry:{value:catchEntry},finallyEntry:{value:finallyEntry}})}inherits(TryEntry,Entry);exports.TryEntry=TryEntry;function CatchEntry(firstLoc,paramId){Entry.call(this);n.Literal.assert(firstLoc);n.Identifier.assert(paramId);Object.defineProperties(this,{firstLoc:{value:firstLoc},paramId:{value:paramId}})}inherits(CatchEntry,Entry);exports.CatchEntry=CatchEntry;function FinallyEntry(firstLoc){Entry.call(this);n.Literal.assert(firstLoc);Object.defineProperties(this,{firstLoc:{value:firstLoc}})}inherits(FinallyEntry,Entry);exports.FinallyEntry=FinallyEntry;function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);Object.defineProperties(this,{emitter:{value:emitter},entryStack:{value:[new FunctionEntry(emitter.finalLoc)]}})}var LMp=LeapManager.prototype;exports.LeapManager=LeapManager;LMp.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LMp._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else{return loc}}}return null};LMp.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LMp.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"./emit":44,assert:83,"ast-types":81,util:92}],48:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var m=require("private").makeAccessor();var isArray=types.builtInTypes.array;var n=types.namedTypes;var hasOwn=Object.prototype.hasOwnProperty;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.assert(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.assert(node);var meta=m(node);if(hasOwn.call(meta,propertyName))return meta[propertyName];if(hasOwn.call(opaqueTypes,node.type))return meta[propertyName]=false;if(hasOwn.call(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(hasOwn.call(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:83,"ast-types":81,"private":99}],49:[function(require,module,exports){var b=require("ast-types").builders;var hasOwn=Object.prototype.hasOwnProperty;exports.defaults=function(obj){var len=arguments.length;var extension;for(var i=1;i<len;++i){if(extension=arguments[i]){for(var key in extension){if(hasOwn.call(extension,key)&&!hasOwn.call(obj,key)){obj[key]=extension[key]}}}}return obj};exports.runtimeProperty=function(name){return b.memberExpression(b.identifier("regeneratorRuntime"),b.identifier(name),false)}},{"ast-types":81}],50:[function(require,module,exports){var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hoist=require("./hoist").hoist;var Emitter=require("./emit").Emitter;var runtimeProperty=require("./util").runtimeProperty;var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");var runtimeAsyncMethod=runtimeProperty("async");exports.transform=function transform(node){return types.visit(node,visitor)};var visitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){this.traverse(path);var node=path.value;if(!node.generator&&!node.async){return}node.generator=false;if(node.expression){node.expression=false;node.body=b.blockStatement([b.returnStatement(node.body)])}if(node.async){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=path.scope.parent.declareTemporary("callee$"));var innerFnId=b.identifier(node.id.name+"$");var contextId=path.scope.declareTemporary("context$");var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));var outerBody=[];if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),node.async?b.literal(null):outerFnId,b.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=b.callExpression(node.async?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(b.returnStatement(wrapCall));node.body=b.blockStatement(outerBody);if(node.async){node.async=false;return}if(n.FunctionDeclaration.check(node)){var pp=path.parent;while(pp&&!(n.BlockStatement.check(pp.value)||n.Program.check(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=b.variableDeclaration("var",[b.variableDeclarator(node.id,b.callExpression(runtimeMarkMethod,[node]))]);if(node.comments){varDecl.comments=node.comments;node.comments=null}var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;for(var i=0;i<bodyLen;++i){var firstStmtPath=bodyPath.get(i);if(!shouldNotHoistAbove(firstStmtPath)){firstStmtPath.insertBefore(varDecl);return}}bodyPath.push(varDecl)}else{n.FunctionExpression.assert(node);return b.callExpression(runtimeMarkMethod,[node])}}});function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;n.Statement.assert(value);if(n.ExpressionStatement.check(value)&&n.Literal.check(value.expression)&&value.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(n.CallExpression.check(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(){return false},visitAwaitExpression:function(path){return b.yieldExpression(path.value.argument,false)}})},{"./emit":44,"./hoist":45,"./util":49,"ast-types":81}],51:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");var isLet=function(node){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;node._let=true;node.kind="var";return true};var isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node)};var standardiseLets=function(declars){_.each(declars,function(declar){delete declar._let})};exports.VariableDeclaration=function(node){isLet(node)};exports.For=function(node,parent,file,scope){var init=node.left||node.init;if(isLet(init)){t.ensureBlock(node);node.body._letDeclars=[init]}if(t.isLabeledStatement(parent)){node.label=parent.label}var letScoping=new LetScoping(node,node.body,parent,file,scope);letScoping.run();if(node.label&&!t.isLabeledStatement(parent)){return t.labeledStatement(node.label,node)}};exports.BlockStatement=function(block,parent,file,scope){if(!t.isFor(parent)){var letScoping=new LetScoping(false,block,parent,file,scope);letScoping.run()}};function LetScoping(forParent,block,parent,file,scope){this.forParent=forParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.letReferences={};this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;this.info=this.getInfo();if(t.isFunction(this.parent))return this.noClosure();if(!this.info.keys.length)return this.noClosure();var referencesInClosure=this.getLetReferences();if(!referencesInClosure)return this.noClosure();this.has=this.checkFor();this.hoistVarDeclarations();standardiseLets(this.info.declarators);var letReferences=_.values(this.letReferences);var fn=t.functionExpression(null,letReferences,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var params=this.getParams(letReferences);var call=t.callExpression(fn,params);var ret=t.identifier(this.file.generateUid("ret",this.scope));var hasYield=traverse.hasType(fn.body,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}this.build(ret,call)};LetScoping.prototype.noClosure=function(){var replacements=this.info.duplicates;var declarators=this.info.declarators;var block=this.block;standardiseLets(declarators);if(_.isEmpty(replacements))return;var replace=function(node,parent){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;node.name=replacements[node.name]||node.name};var traverseReplace=function(node,parent){replace(node,parent);traverse(node,replace)};var forParent=this.forParent;if(forParent){traverseReplace(forParent.right,forParent);traverseReplace(forParent.test,forParent);traverseReplace(forParent.update,forParent)}traverse(block,replace)};LetScoping.prototype.getInfo=function(){var block=this.block;var scope=this.scope;var file=this.file;var opts={outsideKeys:[],declarators:block._letDeclars||[],duplicates:{},keys:[]};var duplicates=function(id,key){var has=scope.parentGet(key);if(has&&has!==id){opts.duplicates[key]=id.name=file.generateUid(key,scope)}};_.each(opts.declarators,function(declar){opts.declarators.push(declar);var keys=t.getIds(declar,true);_.each(keys,duplicates);keys=_.keys(keys);opts.outsideKeys=opts.outsideKeys.concat(keys);opts.keys=opts.keys.concat(keys)});_.each(block.body,function(declar){if(!isLet(declar))return;_.each(t.getIds(declar,true),function(id,key){duplicates(id,key);opts.keys.push(key)})});return opts};LetScoping.prototype.checkFor=function(){var has={hasContinue:false,hasReturn:false,hasBreak:false};var forParent=this.forParent;traverse(this.block,function(node){var replace;if(t.isFunction(node)||t.isFor(node)){return false}if(forParent&&!node.label){if(t.isBreakStatement(node)){has.hasBreak=true;replace=t.returnStatement(t.literal("break"))}else if(t.isContinueStatement(node)){has.hasContinue=true;replace=t.returnStatement(t.literal("continue"))}}if(t.isReturnStatement(node)){has.hasReturn=true;replace=t.returnStatement(t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))]))}if(replace)return t.inherits(replace,node)});return has};LetScoping.prototype.hoistVarDeclarations=function(){var self=this;traverse(this.block,function(node){if(t.isForStatement(node)){if(isVar(node.init)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left)){node.left=node.left.declarations[0].id}}else if(isVar(node)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return false}})};LetScoping.prototype.getParams=function(params){var info=this.info;params=_.cloneDeep(params);_.each(params,function(param){param.name=info.duplicates[param.name]||param.name});return params};LetScoping.prototype.getLetReferences=function(){var closurify=false;var self=this;traverse(this.block,function(node,parent,scope){if(t.isFunction(node)){traverse(node,function(node,parent){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope.hasOwn(node.name))return;closurify=true;if(!_.contains(self.info.outsideKeys,node.name))return;self.letReferences[node.name]=node});return false}else if(t.isFor(node)){return false}});return closurify};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];_.each(node.declarations,function(declar){if(!declar.init)return;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))});return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreak||has.hasContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var forParent=this.forParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreak||has.hasContinue){var label=forParent.label=forParent.label||t.identifier(this.file.generateUid("loop",this.scope));if(has.hasBreak){cases.push(t.switchCase(t.literal("break"),[t.breakStatement(label)]))}if(has.hasContinue){cases.push(t.switchCase(t.literal("continue"),[t.continueStatement(label)]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../traverse":61,"../../types":65,"../../util":67,lodash:98}],52:[function(require,module,exports){var _=require("lodash");exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){_.each(node.specifiers,function(specifier){file.moduleFormatter.importSpecifier(specifier,node,nodes)})}else{file.moduleFormatter.import(node,nodes)}return nodes};exports.ExportDeclaration=function(node,parent,file){var nodes=[];if(node.declaration){file.moduleFormatter.export(node,nodes)}else{_.each(node.specifiers,function(specifier){file.moduleFormatter.exportSpecifier(specifier,node,nodes)})}return nodes}},{lodash:98}],53:[function(require,module,exports){var util=require("../../util");var _=require("lodash");exports.Property=function(node){if(node.method)node.method=false};exports.ObjectExpression=function(node,parent,file){var mutatorMap={};node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.value);return false}else{return true}});if(_.isEmpty(mutatorMap))return;var objId=util.getUid(parent,file);return util.template("object-define-properties-closure",{KEY:objId,OBJECT:node,CONTENT:util.template("object-define-properties",{OBJECT:objId,PROPS:util.buildDefineProperties(mutatorMap)})})}},{"../../util":67,lodash:98}],54:[function(require,module,exports){exports.Property=function(node){if(node.shorthand)node.shorthand=false}},{}],55:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.XJSIdentifier=function(node){if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.XJSNamespacedName=function(node,parent,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.XJSMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.XJSExpressionContainer=function(node){return node.expression};exports.XJSAttribute={exit:function(node){var value=node.value||t.literal(true);return t.property("init",node.name,value)}};exports.XJSOpeningElement={exit:function(node){var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(tagName&&(/[a-z]/.exec(tagName[0])||_.contains(tagName,"-"))){args.push(t.literal(tagName))}else{args.push(tagExpr)}var props=node.attributes;if(props.length){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(props.length){var prop=props.shift();if(t.isXJSSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){props=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}props=t.callExpression(t.memberExpression(t.identifier("React"),t.identifier("__spread")),objs)}}else{props=t.literal(null)}args.push(props);tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"));return t.callExpression(tagExpr,args)}};exports.XJSElement={exit:function(node){var callExpr=node.openingElement;_.each(node.children,function(child){if(t.isLiteral(child)){var lines=child.value.split(/\r\n|\n|\r/); _.each(lines,function(line,i){var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){callExpr.arguments.push(t.literal(trimmedLine))}});return}callExpr.arguments.push(child)});return t.inherits(callExpr,node)}};var addDisplayName=function(id,call){if(!call||!t.isCallExpression(call))return;var callee=call.callee;if(!t.isMemberExpression(callee))return;var obj=callee.object;if(!t.isIdentifier(obj,{name:"React"}))return;var prop=callee.property;if(!t.isIdentifier(prop,{name:"createClass"}))return;var args=call.arguments;if(args.length!==1)return;var first=args[0];if(!t.isObjectExpression(first))return;var props=first.properties;var safe=true;_.each(props,function(prop){if(t.isIdentifier(prop.key,{name:"displayName"})){return safe=false}});if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../types":65,esutils:97,lodash:98}],56:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.Function=function(node,parent,file){if(!node.rest)return;var rest=node.rest;delete node.rest;var templateName="arguments-slice-assign";if(node.params.length)templateName+="-arg";t.ensureBlock(node);var template=util.template(templateName,{SLICE_KEY:file.addDeclaration("slice"),VARIABLE_NAME:rest,SLICE_ARG:t.literal(node.params.length)});template.declarations[0].init.arguments[0]._ignoreAliasFunctions=true;node.body.body.unshift(template)}},{"../../types":65,"../../util":67}],57:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var getSpreadLiteral=function(spread){var literal=spread.argument;if(!t.isArrayExpression(literal)){literal=t.callExpression(t.memberExpression(t.identifier("Array"),t.identifier("from")),[literal])}return literal};var hasSpread=function(nodes){var has=false;_.each(nodes,function(node){if(t.isSpreadElement(node)){has=true;return false}});return has};var build=function(props){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};_.each(props,function(prop){if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop))}else{_props.push(prop)}});push();return nodes};exports.ArrayExpression=function(node){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements);var first=nodes.shift();if(!nodes.length)return first;return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.literal(null);node.arguments=[];var nodes=build(args);var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){contextLiteral=callee.object;if(callee.computed){callee.object=t.memberExpression(callee.object,callee.property,true);callee.property=t.identifier("apply");callee.computed=false}else{callee.property=t.memberExpression(callee.property,t.identifier("apply"))}}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var nodes=build(args);var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}return t.callExpression(file.addDeclaration("apply-constructor"),[node.callee,args])}},{"../../types":65,lodash:98}],58:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];_.each(quasi.quasis,function(elem){strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))});args.push(t.callExpression(file.addDeclaration("tagged-template-literal"),[t.arrayExpression(strings),t.arrayExpression(raw)]));_.each(quasi.expressions,function(expr){args.push(expr)});return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];_.each(node.quasis,function(elem){nodes.push(t.literal(elem.value.raw));var expr=node.expressions.shift();if(expr){if(t.isBinary(expr))expr=t.parenthesizedExpression(expr);nodes.push(expr)}});if(nodes.length>1){var last=_.last(nodes);if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());_.each(nodes,function(node){root=buildBinaryExpression(root,node)});return root}else{return nodes[0]}}},{"../../types":65,lodash:98}],59:[function(require,module,exports){var rewritePattern=require("regexpu/rewrite-pattern");var _=require("lodash");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(!_.contains(regex.flags,"u"))return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:98,"regexpu/rewrite-pattern":105}],60:[function(require,module,exports){var t=require("../../types");module.exports=function(ast){var body=ast.program.body;var first=body[0];var noStrict=!first||!t.isExpressionStatement(first)||!t.isLiteral(first.expression)||first.expression.value!=="use strict";if(noStrict){body.unshift(t.expressionStatement(t.literal("use strict")))}}},{"../../types":65}],61:[function(require,module,exports){module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function traverse(parent,callbacks,opts){if(!parent)return;if(_.isArray(parent)){_.each(parent,function(node){traverse(node,callbacks,opts)});return}var keys=t.VISITOR_KEYS[parent.type];if(!keys)return;opts=opts||{};if(_.isArray(opts))opts={blacklist:opts};var blacklistTypes=opts.blacklist||[];if(_.isFunction(callbacks))callbacks={enter:callbacks};for(var i in keys){var key=keys[i];var nodes=parent[key];if(!nodes)continue;var updated=false;var handle=function(obj,key){var node=obj[key];if(!node)return;if(blacklistTypes.indexOf(node.type)>-1)return;var maybeReplace=function(result){if(result===false)return;if(result!=null){updated=true;node=obj[key]=result}};var opts2={scope:opts.scope,blacklist:opts.blacklist};if(t.isScope(node))opts2.scope=new Scope(opts.scope,node);if(callbacks.enter){var result=callbacks.enter(node,parent,opts2.scope);maybeReplace(result);if(result===false)return}traverse(node,callbacks,opts2);if(callbacks.exit){maybeReplace(callbacks.exit(node,parent,opts2.scope))}};if(_.isArray(nodes)){for(i in nodes){handle(nodes,i)}if(updated)parent[key]=_.flatten(parent[key])}else{handle(parent,key)}}}traverse.removeProperties=function(tree){var clear=function(node){delete node.extendedRange;delete node._scopeIds;delete node._parent;delete node.tokens;delete node.range;delete node.start;delete node.end;delete node.loc;delete node.raw;clearComments(node.trailingComments);clearComments(node.leadingComments)};var clearComments=function(comments){_.each(comments,clear)};clear(tree);traverse(tree,clear);return tree};traverse.hasType=function(tree,type,blacklistTypes){blacklistTypes=[].concat(blacklistTypes||[]);var has=false;if(_.contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;traverse(tree,function(node){if(node.type===type){has=true;return false}},{blacklist:blacklistTypes});return has}},{"../types":65,"./scope":62,lodash:98}],62:[function(require,module,exports){module.exports=Scope;var traverse=require("./index");var t=require("../types");var _=require("lodash");var FOR_KEYS=["left","init"];function Scope(parent,block){this.parent=parent;this.block=block;this.info=this.getInfo();this.declarations=this.info.declarations}Scope.prototype.getInfo=function(){var block=this.block;if(block._scope)return block._scope;var self=this;var info=block._scope={declarations:{}};var add=function(node){self.addDeclaration(node,info.declarations)};if(t.isFor(block)){_.each(FOR_KEYS,function(key){var node=block[key];if(t.isLet(node))add(node)});block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){_.each(block.body,function(node){if(t.isLet(node))add(node)})}if(t.isCatchClause(block)){add(block.param)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,function(node){if(t.isFor(node)){_.each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))add(declar)})}if(t.isFunction(node))return false;if(t.isDeclaration(node)&&!t.isLet(node)){add(node)}})}if(t.isFunction(block)){add(block.rest);_.each(block.params,function(param){add(param)})}return info};Scope.prototype.addDeclaration=function(node,declarations){if(!node)return;_.merge(declarations||this.declarations,t.getIds(node,true))};Scope.prototype.get=function(id){return id&&(this.getOwn(id)||this.parentGet(id))};Scope.prototype.getOwn=function(id){return _.has(this.declarations,id)&&this.declarations[id]};Scope.prototype.parentGet=function(id){return this.parent&&this.parent.get(id)};Scope.prototype.has=function(id){return id&&(this.hasOwn(id)||this.parentHas(id))};Scope.prototype.hasOwn=function(id){return!!this.getOwn(id)};Scope.prototype.parentHas=function(id){return this.parent&&this.parent.has(id)}},{"../types":65,"./index":61,lodash:98}],63:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary"],BinaryExpression:["Binary"],UnaryExpression:["UnaryLike"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class"],ForOfStatement:["Statement","For","Scope"],ForInStatement:["Statement","For","Scope"],ForStatement:["Statement","For","Scope"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable"]}},{}],64:[function(require,module,exports){module.exports={ArrayExpression:["elements"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],Literal:["value"],MemberExpression:["object","property","computed"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],YieldExpression:["argument","delegate"]}},{}],65:[function(require,module,exports){var _=require("lodash");var t=exports;t.VISITOR_KEYS=require("./visitor-keys");_.each(t.VISITOR_KEYS,function(keys,type){t["is"+type]=function(node,opts){return node&&node.type===type&&t.shallowEqual(node,opts)}});t.BUILDER_KEYS=_.defaults(require("./builder-keys"),t.VISITOR_KEYS);_.each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node={type:type};_.each(keys,function(key,i){node[key]=args[i]});return node}});t.ALIAS_KEYS=require("./alias-keys");var _aliases={};_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=_aliases[alias]=_aliases[alias]||[];types.push(type)})});_.each(_aliases,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;t["is"+type]=function(node,opts){return node&&_.contains(types,node.type)&&t.shallowEqual(node,opts)}});t.shallowEqual=function(actual,expected){var same=true;if(expected){_.each(expected,function(val,key){if(actual[key]!==val){return same=false}})}return same};t.isReferenced=function(node,parent){if(t.isProperty(parent)&&parent.key===node)return false;if(t.isVariableDeclarator(parent)&&parent.id===node)return false;var isMemberExpression=t.isMemberExpression(parent);var isComputedProperty=isMemberExpression&&parent.property===node&&parent.computed;var isObject=isMemberExpression&&parent.object===node;if(!isMemberExpression||isComputedProperty||isObject)return true;return false};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name.replace(/[^a-zA-Z0-9]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-_\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});return name};t.ensureBlock=function(node){node.body=t.toBlock(node.body,node)};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(!_.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getIds=function(node,map,ignoreTypes){ignoreTypes=ignoreTypes||[];var search=[].concat(node);var ids={};while(search.length){var id=search.shift();if(!id)continue;if(_.contains(ignoreTypes,id.type))continue;var nodeKey=t.getIds.nodes[id.type];var arrKey=t.getIds.arrays[id.type];if(t.isIdentifier(id)){ids[id.name]=id}else if(nodeKey){if(id[nodeKey])search.push(id[nodeKey])}else if(arrKey){search=search.concat(id[arrKey]||[])}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:"left",ImportSpecifier:"id",ExportSpecifier:"id",VariableDeclarator:"id",FunctionDeclaration:"id",ClassDeclaration:"id",ParenthesizedExpression:"expression",MemeberExpression:"object",SpreadElement:"argument",Property:"value"};t.getIds.arrays={ExportDeclaration:"specifiers",ImportDeclaration:"specifiers",VariableDeclaration:"declarations",ArrayPattern:"elements",ObjectPattern:"properties"};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.removeComments=function(child){delete child.leadingComments;delete child.trailingComments;return child};t.inheritsComments=function(child,parent){child.leadingComments=_.compact([].concat(child.leadingComments,parent.leadingComments));child.trailingComments=_.compact([].concat(child.trailingComments,parent.trailingComments));return child};t.inherits=function(child,parent){child.loc=parent.loc;child.end=parent.end;child.range=parent.range;child.start=parent.start;t.inheritsComments(child,parent);return child};t.getSpecifierName=function(specifier){return specifier.name||specifier.id}},{"./alias-keys":63,"./builder-keys":64,"./visitor-keys":66,lodash:98}],66:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],XJSAttribute:["name","value"],XJSClosingElement:["name"],XJSElement:["openingElement","closingElement","children"],XJSEmptyExpression:[],XJSExpressionContainer:["expression"],XJSIdentifier:[],XJSMemberExpression:["object","property"],XJSNamespacedName:["namespace","name"],XJSOpeningElement:["name","attributes"],XJSSpreadAttribute:["argument"],YieldExpression:["argument"]}},{}],67:[function(require,module,exports){(function(Buffer,__dirname){require("./patch");var estraverse=require("estraverse");var traverse=require("./traverse");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var _=require("lodash");exports.inherits=util.inherits;exports.canCompile=function(filename,altExts){var exts=altExts||[".js",".jsx",".es6"];var ext=path.extname(filename);return _.contains(exts,ext)};exports.isInteger=function(i){return _.isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.getUid=function(parent,file){var node;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}var id="ref";if(t.isIdentifier(node))id=node.name;return t.identifier(file.generateUid(id))};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,method){var alias;if(t.isIdentifier(key)){alias=key.name;if(method.computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(_.cloneDeep(key)))}var map;if(_.has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(method.computed){map._computed=true}map[kind]=method};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);_.each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);_.each(map,function(node,key){if(key[0]==="_")return;node=_.clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=_.cloneDeep(template);if(!_.isEmpty(nodes)){traverse(template,function(node){if(t.isIdentifier(node)&&_.has(nodes,node.name)){var newNode=nodes[node.name];if(_.isString(newNode)){node.name=newNode}else{return newNode}}})}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){node=node.expression;if(t.isParenthesizedExpression(node))node=node.expression}return node};exports.codeFrame=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);lines=lines.split("\n");var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+exports.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=exports.repeat(gutter.length-2);str+="|"+exports.repeat(colNumber)+"^"}return str}).join("\n")};exports.repeat=function(width,cha){cha=cha||" ";return new Array(width+1).join(cha)};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowReturnOutsideFunction:true,preserveParens:true,ecmaVersion:Infinity,strictMode:true,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=t.file(ast,comments,tokens);traverse(ast,function(node,parent){node._parent=parent});if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=exports.codeFrame(code,loc.line,loc.column);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://githut.com/6to5/6to5/issues")}_.each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":116,"./patch":22,"./traverse":61,"./types":65,"acorn-6to5":1,buffer:84,estraverse:93,fs:82,lodash:98,path:89,util:92}],68:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Node").field("type",isString).field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp))},{"../lib/shared":79,"../lib/types":80}],69:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def; var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":80,"./core":68}],70:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Function"));def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("id").field("id",def("Identifier"));def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":79,"../lib/types":80,"./core":68}],71:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":79,"../lib/types":80,"./core":68}],72:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("TypeAnnotatedIdentifier").bases("Pattern").build("annotation","identifier").field("annotation",def("TypeAnnotation")).field("identifier",def("Identifier"));def("TypeAnnotation").bases("Pattern").build("annotatedType","templateTypes","paramTypes","returnType","unionType","nullable").field("annotatedType",def("Identifier")).field("templateTypes",or([def("TypeAnnotation")],null)).field("paramTypes",or([def("TypeAnnotation")],null)).field("returnType",or(def("TypeAnnotation"),null)).field("unionType",or(def("TypeAnnotation"),null)).field("nullable",isBoolean);def("Identifier").field("annotation",or(def("TypeAnnotation"),null),defaults["null"]);def("Function").field("returnType",or(def("TypeAnnotation"),null),defaults["null"]);def("ClassProperty").field("id",or(def("Identifier"),def("TypeAnnotatedIdentifier")))},{"../lib/shared":79,"../lib/types":80,"./core":68}],73:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":79,"../lib/types":80,"./core":68}],74:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":81,assert:83}],75:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}return remainingNodePath};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){if(!this.parent)return false;var node=this.node;if(node!==this.value)return false;var parent=this.parent.node;assert.notStrictEqual(node,parent);if(!n.Expression.check(node))return false;if(isUnaryLike(node))return n.MemberExpression.check(parent)&&this.name==="object"&&parent.object===node;if(isBinary(node)){if(n.CallExpression.check(parent)&&this.name==="callee"){assert.strictEqual(parent.callee,node);return true}if(isUnaryLike(parent))return true;if(n.MemberExpression.check(parent)&&this.name==="object"){assert.strictEqual(parent.object,node);return true}if(isBinary(parent)){var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}}}if(n.SequenceExpression.check(node)){if(n.ForStatement.check(parent)){return false}if(n.ExpressionStatement.check(parent)&&this.name==="expression"){return false}return true}if(n.YieldExpression.check(node))return isBinary(parent)||n.CallExpression.check(parent)||n.MemberExpression.check(parent)||n.NewExpression.check(parent)||n.ConditionalExpression.check(parent)||isUnaryLike(parent)||n.YieldExpression.check(parent);if(n.NewExpression.check(parent)&&this.name==="callee"){assert.strictEqual(parent.callee,node);return containsCallExpression(node)}if(n.Literal.check(node)&&isNumber.check(node.value)&&n.MemberExpression.check(parent)&&this.name==="object"){assert.strictEqual(parent.object,node);return true}if(n.AssignmentExpression.check(node)||n.ConditionalExpression.check(node)){if(isUnaryLike(parent))return true;if(isBinary(parent))return true;if(n.CallExpression.check(parent)&&this.name==="callee"){assert.strictEqual(parent.callee,node);return true}if(n.ConditionalExpression.check(parent)&&this.name==="test"){assert.strictEqual(parent.test,node);return true}if(n.MemberExpression.check(parent)&&this.name==="object"){assert.strictEqual(parent.object,node);return true}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}module.exports=NodePath},{"./path":77,"./scope":78,"./types":80,assert:83,util:92}],76:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this)}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);for(var typeName in supertypeTable){if(hasOwn.call(supertypeTable,typeName)){methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){var visitor=PathVisitor.fromMethodsObject(methods);if(node instanceof NodePath){visitor.visit(node);return node.value}var rootPath=new NodePath({root:node});visitor.visit(rootPath.get("root"));return rootPath.value.root};var PVp=PathVisitor.prototype;PVp.visit=function(path){if(this instanceof this.Context){return this.visitor.visit(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visit,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visit(childPaths[i])}}}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName)};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};module.exports=PathVisitor},{"./node-path":75,"./types":80,assert:83}],77:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":80,assert:83}],78:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name) };Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(Scope.isEstablishedBy(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":75,"./types":80,assert:83}],79:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":80}],80:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};for(var typeName in defCache){if(hasOwn.call(defCache,typeName)){var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var i=0;i<d.supertypeList.length;++i){var superTypeName=d.supertypeList[i];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}assert.ok(type.check(value),shallowStringify(value)+" does not match field "+field+" of type "+self.typeName);built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}assert.strictEqual("type"in object,false,"did not recognize object of type "+JSON.stringify(object.type));return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:83}],81:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":68,"./def/e4x":69,"./def/es6":70,"./def/es7":71,"./def/fb-harmony":72,"./def/mozilla":73,"./lib/equiv":74,"./lib/node-path":75,"./lib/path-visitor":76,"./lib/types":80}],82:[function(require,module,exports){},{}],83:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&(isNaN(value)||!isFinite(value))){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(isArguments(a)){if(!isArguments(b)){return false}a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}try{var ka=objectKeys(a),kb=objectKeys(b),key,i}catch(e){return false}if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":92}],84:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(this.length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(Buffer.TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8) };Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;if(end<start)throw new TypeError("sourceEnd < sourceStart");if(target_start<0||target_start>=target.length)throw new TypeError("targetStart out of bounds");if(start<0||start>=source.length)throw new TypeError("sourceStart out of bounds");if(end<0||end>source.length)throw new TypeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new TypeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new TypeError("start out of bounds");if(end<0||end>this.length)throw new TypeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":85,ieee754:86,"is-array":87}],85:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],86:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.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)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],87:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],88:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],89:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:90}],90:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){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")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],91:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],92:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":91,_process:90,inherits:88}],93:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]}; BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(){var i,nextElem,parent;if(element.ref.remove()){parent=element.ref.parent;for(i=1;i<worklist.length;i++){nextElem=worklist[i];if(nextElem===sentinel||nextElem.ref.parent!==parent){break}nextElem.path[nextElem.path.length-1]=--nextElem.ref.key}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem()}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem();element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.5.1-dev";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller})},{}],94:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],95:[function(require,module,exports){(function(){"use strict";var Regex;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],96:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":95}],97:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":94,"./code":95,"./keyword":96}],98:[function(require,module,exports){(function(global){(function(){var undefined;var arrayPool=[],objectPool=[];var idCounter=0;var keyPrefix=+new Date+"";var largeArraySize=75;var maxPoolSize=40;var whitespace=" \f "+"\n\r\u2028\u2029"+" ᠎              ";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reFuncName=/^\s*function[ \n\r\t]+\w/;var reInterpolate=/<%=([\s\S]+?)%>/g;var reLeadingSpacesAndZeros=RegExp("^["+whitespace+"]*0+(?=.$)");var reNoMatch=/($^)/;var reThis=/\bthis\b/;var reUnescapedString=/['\n\r\t\u2028\u2029\\]/g;var contextProps=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"];var templateCounter=0;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var cloneableClasses={};cloneableClasses[funcClass]=false;cloneableClasses[argsClass]=cloneableClasses[arrayClass]=cloneableClasses[boolClass]=cloneableClasses[dateClass]=cloneableClasses[numberClass]=cloneableClasses[objectClass]=cloneableClasses[regexpClass]=cloneableClasses[stringClass]=true;var debounceOptions={leading:false,maxWait:0,trailing:false};var descriptor={configurable:false,enumerable:false,value:null,writable:false};var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};var root=objectTypes[typeof window]&&window||this;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports;var freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}function baseIndexOf(array,value,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0;while(++index<length){if(array[index]===value){return index}}return-1}function cacheIndexOf(cache,value){var type=typeof value;cache=cache.cache;if(type=="boolean"||value==null){return cache[value]?0:-1}if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value;cache=(cache=cache[type])&&cache[key];return type=="object"?cache&&baseIndexOf(cache,value)>-1?0:-1:cache?0:-1}function cachePush(value){var cache=this.cache,type=typeof value;if(type=="boolean"||value==null){cache[value]=true}else{if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value,typeCache=cache[type]||(cache[type]={});if(type=="object"){(typeCache[key]||(typeCache[key]=[])).push(value)}else{typeCache[key]=true}}}function charAtCallback(value){return value.charCodeAt(0)}function compareAscending(a,b){var ac=a.criteria,bc=b.criteria,index=-1,length=ac.length;while(++index<length){var value=ac[index],other=bc[index];if(value!==other){if(value>other||typeof value=="undefined"){return 1}if(value<other||typeof other=="undefined"){return-1}}}return a.index-b.index}function createCache(array){var index=-1,length=array.length,first=array[0],mid=array[length/2|0],last=array[length-1];if(first&&typeof first=="object"&&mid&&typeof mid=="object"&&last&&typeof last=="object"){return false}var cache=getObject();cache["false"]=cache["null"]=cache["true"]=cache["undefined"]=false;var result=getObject();result.array=array;result.cache=cache;result.push=cachePush;while(++index<length){result.push(array[index])}return result}function escapeStringChar(match){return"\\"+stringEscapes[match]}function getArray(){return arrayPool.pop()||[]}function getObject(){return objectPool.pop()||{array:null,cache:null,criteria:null,"false":false,index:0,"null":false,number:null,object:null,push:null,string:null,"true":false,undefined:false,value:null}}function releaseArray(array){array.length=0;if(arrayPool.length<maxPoolSize){arrayPool.push(array)}}function releaseObject(object){var cache=object.cache;if(cache){releaseObject(cache)}object.array=object.cache=object.criteria=object.object=object.number=object.string=object.value=null;if(objectPool.length<maxPoolSize){objectPool.push(object)}}function slice(array,start,end){start||(start=0);if(typeof end=="undefined"){end=array?array.length:0}var index=-1,length=end-start||0,result=Array(length<0?0:length);while(++index<length){result[index]=array[start+index]}return result}function runInContext(context){context=context?_.defaults(root.Object(),context,_.pick(root,contextProps)):root;var Array=context.Array,Boolean=context.Boolean,Date=context.Date,Function=context.Function,Math=context.Math,Number=context.Number,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;var arrayRef=[];var objectProto=Object.prototype;var oldDash=context._;var toString=objectProto.toString;var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var ceil=Math.ceil,clearTimeout=context.clearTimeout,floor=Math.floor,fnToString=Function.prototype.toString,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,hasOwnProperty=objectProto.hasOwnProperty,push=arrayRef.push,setTimeout=context.setTimeout,splice=arrayRef.splice,unshift=arrayRef.unshift;var defineProperty=function(){try{var o={},func=isNative(func=Object.defineProperty)&&func,result=func(o,o,o)&&func}catch(e){}return result}();var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate,nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeIsFinite=context.isFinite,nativeIsNaN=context.isNaN,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,nativeParseInt=context.parseInt,nativeRandom=Math.random;var ctorByClass={};ctorByClass[arrayClass]=Array;ctorByClass[boolClass]=Boolean;ctorByClass[dateClass]=Date;ctorByClass[funcClass]=Function;ctorByClass[objectClass]=Object;ctorByClass[numberClass]=Number;ctorByClass[regexpClass]=RegExp;ctorByClass[stringClass]=String;function lodash(value){return value&&typeof value=="object"&&!isArray(value)&&hasOwnProperty.call(value,"__wrapped__")?value:new lodashWrapper(value)}function lodashWrapper(value,chainAll){this.__chain__=!!chainAll;this.__wrapped__=value}lodashWrapper.prototype=lodash.prototype;var support=lodash.support={};support.funcDecomp=!isNative(context.WinRTError)&&reThis.test(runInContext);support.funcNames=typeof Function.name=="string";lodash.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function baseBind(bindData){var func=bindData[0],partialArgs=bindData[2],thisArg=bindData[4];function bound(){if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(this instanceof bound){var thisBinding=baseCreate(func.prototype),result=func.apply(thisBinding,args||arguments);return isObject(result)?result:thisBinding}return func.apply(thisArg,args||arguments)}setBindData(bound,bindData);return bound}function baseClone(value,isDeep,callback,stackA,stackB){if(callback){var result=callback(value);if(typeof result!="undefined"){return result}}var isObj=isObject(value);if(isObj){var className=toString.call(value);if(!cloneableClasses[className]){return value}var ctor=ctorByClass[className];switch(className){case boolClass:case dateClass:return new ctor(+value);case numberClass:case stringClass:return new ctor(value);case regexpClass:result=ctor(value.source,reFlags.exec(value));result.lastIndex=value.lastIndex;return result}}else{return value}var isArr=isArray(value);if(isDeep){var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}result=isArr?ctor(value.length):{}}else{result=isArr?slice(value):assign({},value)}if(isArr){if(hasOwnProperty.call(value,"index")){result.index=value.index}if(hasOwnProperty.call(value,"input")){result.input=value.input}}if(!isDeep){return result}stackA.push(value);stackB.push(result);(isArr?forEach:forOwn)(value,function(objValue,key){result[key]=baseClone(objValue,isDeep,callback,stackA,stackB)});if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseCreate(prototype,properties){return isObject(prototype)?nativeCreate(prototype):{}}if(!nativeCreate){baseCreate=function(){function Object(){}return function(prototype){if(isObject(prototype)){Object.prototype=prototype;var result=new Object;Object.prototype=null}return result||context.Object()}}()}function baseCreateCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"||!("prototype"in func)){return func}var bindData=func.__bindData__;if(typeof bindData=="undefined"){if(support.funcNames){bindData=!func.name}bindData=bindData||!support.funcDecomp;if(!bindData){var source=fnToString.call(func);if(!support.funcNames){bindData=!reFuncName.test(source)}if(!bindData){bindData=reThis.test(source);setBindData(func,bindData)}}}if(bindData===false||bindData!==true&&bindData[1]&1){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 2:return function(a,b){return func.call(thisArg,a,b)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)}}return bind(func,thisArg)}function baseCreateWrapper(bindData){var func=bindData[0],bitmask=bindData[1],partialArgs=bindData[2],partialRightArgs=bindData[3],thisArg=bindData[4],arity=bindData[5];var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,key=func;function bound(){var thisBinding=isBind?thisArg:this;if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(partialRightArgs||isCurry){args||(args=slice(arguments));if(partialRightArgs){push.apply(args,partialRightArgs)}if(isCurry&&args.length<arity){bitmask|=16&~32;return baseCreateWrapper([func,isCurryBound?bitmask:bitmask&~3,args,null,thisArg,arity])}}args||(args=arguments);if(isBindKey){func=thisBinding[key]}if(this instanceof bound){thisBinding=baseCreate(func.prototype);var result=func.apply(thisBinding,args);return isObject(result)?result:thisBinding}return func.apply(thisBinding,args)}setBindData(bound,bindData);return bound}function baseDifference(array,values){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,isLarge=length>=largeArraySize&&indexOf===baseIndexOf,result=[];if(isLarge){var cache=createCache(values);if(cache){indexOf=cacheIndexOf;values=cache}else{isLarge=false}}while(++index<length){var value=array[index];if(indexOf(values,value)<0){result.push(value)}}if(isLarge){releaseObject(values)}return result}function baseFlatten(array,isShallow,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value&&typeof value=="object"&&typeof value.length=="number"&&(isArray(value)||isArguments(value))){if(!isShallow){value=baseFlatten(value,isShallow,isStrict)}var valIndex=-1,valLength=value.length,resIndex=result.length;result.length+=valLength;while(++valIndex<valLength){result[resIndex++]=value[valIndex]}}else if(!isStrict){result.push(value)}}return result}function baseIsEqual(a,b,callback,isWhere,stackA,stackB){if(callback){var result=callback(a,b);if(typeof result!="undefined"){return!!result}}if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&!(a&&objectTypes[type])&&!(b&&objectTypes[otherType])){return false}if(a==null||b==null){return a===b}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:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){var aWrapped=hasOwnProperty.call(a,"__wrapped__"),bWrapped=hasOwnProperty.call(b,"__wrapped__");if(aWrapped||bWrapped){return baseIsEqual(aWrapped?a.__wrapped__:a,bWrapped?b.__wrapped__:b,callback,isWhere,stackA,stackB)}if(className!=objectClass){return false}var ctorA=a.constructor,ctorB=b.constructor;if(ctorA!=ctorB&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result||isWhere){while(size--){var index=length,value=b[size];if(isWhere){while(index--){if(result=baseIsEqual(a[index],value,callback,isWhere,stackA,stackB)){break}}}else if(!(result=baseIsEqual(a[size],value,callback,isWhere,stackA,stackB))){break}}}}else{forIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&baseIsEqual(a[key],value,callback,isWhere,stackA,stackB)}});if(result&&!isWhere){forIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseMerge(object,source,callback,stackA,stackB){(isArray(source)?forEach:forOwn)(source,function(source,key){var found,isArr,result=source,value=object[key];if(source&&((isArr=isArray(source))||isPlainObject(source))){var stackLength=stackA.length;while(stackLength--){if(found=stackA[stackLength]==source){value=stackB[stackLength];break}}if(!found){var isShallow;if(callback){result=callback(value,source);if(isShallow=typeof result!="undefined"){value=result}}if(!isShallow){value=isArr?isArray(value)?value:[]:isPlainObject(value)?value:{}}stackA.push(source);stackB.push(value);if(!isShallow){baseMerge(value,source,callback,stackA,stackB)}}}else{if(callback){result=callback(value,source);if(typeof result=="undefined"){result=source}}if(typeof result!="undefined"){value=result}}object[key]=value})}function baseRandom(min,max){return min+floor(nativeRandom()*(max-min+1))}function baseUniq(array,isSorted,callback){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,result=[];var isLarge=!isSorted&&length>=largeArraySize&&indexOf===baseIndexOf,seen=callback||isLarge?getArray():result;if(isLarge){var cache=createCache(seen);indexOf=cacheIndexOf;seen=cache}while(++index<length){var value=array[index],computed=callback?callback(value,index,array):value;if(isSorted?!index||seen[seen.length-1]!==computed:indexOf(seen,computed)<0){if(callback||isLarge){seen.push(computed)}result.push(value)}}if(isLarge){releaseArray(seen.array);releaseObject(seen)}else if(callback){releaseArray(seen)}return result}function createAggregator(setter){return function(collection,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];setter(result,value,callback(value,index,collection),collection)}}else{forOwn(collection,function(value,key,collection){setter(result,value,callback(value,key,collection),collection)})}return result}}function createWrapper(func,bitmask,partialArgs,partialRightArgs,thisArg,arity){var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,isPartial=bitmask&16,isPartialRight=bitmask&32; if(!isBindKey&&!isFunction(func)){throw new TypeError}if(isPartial&&!partialArgs.length){bitmask&=~16;isPartial=partialArgs=false}if(isPartialRight&&!partialRightArgs.length){bitmask&=~32;isPartialRight=partialRightArgs=false}var bindData=func&&func.__bindData__;if(bindData&&bindData!==true){bindData=slice(bindData);if(bindData[2]){bindData[2]=slice(bindData[2])}if(bindData[3]){bindData[3]=slice(bindData[3])}if(isBind&&!(bindData[1]&1)){bindData[4]=thisArg}if(!isBind&&bindData[1]&1){bitmask|=8}if(isCurry&&!(bindData[1]&4)){bindData[5]=arity}if(isPartial){push.apply(bindData[2]||(bindData[2]=[]),partialArgs)}if(isPartialRight){unshift.apply(bindData[3]||(bindData[3]=[]),partialRightArgs)}bindData[1]|=bitmask;return createWrapper.apply(null,bindData)}var creater=bitmask==1||bitmask===17?baseBind:baseCreateWrapper;return creater([func,bitmask,partialArgs,partialRightArgs,thisArg,arity])}function escapeHtmlChar(match){return htmlEscapes[match]}function getIndexOf(){var result=(result=lodash.indexOf)===indexOf?baseIndexOf:result;return result}function isNative(value){return typeof value=="function"&&reNative.test(value)}var setBindData=!defineProperty?noop:function(func,value){descriptor.value=value;defineProperty(func,"__bindData__",descriptor)};function shimIsPlainObject(value){var ctor,result;if(!(value&&toString.call(value)==objectClass)||(ctor=value.constructor,isFunction(ctor)&&!(ctor instanceof ctor))){return false}forIn(value,function(value,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}function unescapeHtmlChar(match){return htmlUnescapes[match]}function isArguments(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==argsClass||false}var isArray=nativeIsArray||function(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==arrayClass||false};var shimKeys=function(object){var index,iterable=object,result=[];if(!iterable)return result;if(!objectTypes[typeof object])return result;for(index in iterable){if(hasOwnProperty.call(iterable,index)){result.push(index)}}return result};var keys=!nativeKeys?shimKeys:function(object){if(!isObject(object)){return[]}return nativeKeys(object)};var htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};var htmlUnescapes=invert(htmlEscapes);var reEscapedHtml=RegExp("("+keys(htmlUnescapes).join("|")+")","g"),reUnescapedHtml=RegExp("["+keys(htmlEscapes).join("")+"]","g");var assign=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;if(argsLength>3&&typeof args[argsLength-2]=="function"){var callback=baseCreateCallback(args[--argsLength-1],args[argsLength--],2)}else if(argsLength>2&&typeof args[argsLength-1]=="function"){callback=args[--argsLength]}while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];result[index]=callback?callback(result[index],iterable[index]):iterable[index]}}}return result};function clone(value,isDeep,callback,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=callback;callback=isDeep;isDeep=false}return baseClone(value,isDeep,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function cloneDeep(value,callback,thisArg){return baseClone(value,true,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function create(prototype,properties){var result=baseCreate(prototype);return properties?assign(result,properties):result}var defaults=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(typeof result[index]=="undefined")result[index]=iterable[index]}}}return result};function findKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}function findLastKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwnRight(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}var forIn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);for(index in iterable){if(callback(iterable[index],index,collection)===false)return result}return result};function forInRight(object,callback,thisArg){var pairs=[];forIn(object,function(value,key){pairs.push(key,value)});var length=pairs.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){if(callback(pairs[length--],pairs[length],object)===false){break}}return object}var forOwn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(callback(iterable[index],index,collection)===false)return result}return result};function forOwnRight(object,callback,thisArg){var props=keys(object),length=props.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){var key=props[length];if(callback(object[key],key,object)===false){break}}return object}function functions(object){var result=[];forIn(object,function(value,key){if(isFunction(value)){result.push(key)}});return result.sort()}function has(object,key){return object?hasOwnProperty.call(object,key):false}function invert(object){var index=-1,props=keys(object),length=props.length,result={};while(++index<length){var key=props[index];result[object[key]]=key}return result}function isBoolean(value){return value===true||value===false||value&&typeof value=="object"&&toString.call(value)==boolClass||false}function isDate(value){return value&&typeof value=="object"&&toString.call(value)==dateClass||false}function isElement(value){return value&&value.nodeType===1||false}function isEmpty(value){var result=true;if(!value){return result}var className=toString.call(value),length=value.length;if(className==arrayClass||className==stringClass||className==argsClass||className==objectClass&&typeof length=="number"&&isFunction(value.splice)){return!length}forOwn(value,function(){return result=false});return result}function isEqual(a,b,callback,thisArg){return baseIsEqual(a,b,typeof callback=="function"&&baseCreateCallback(callback,thisArg,2))}function isFinite(value){return nativeIsFinite(value)&&!nativeIsNaN(parseFloat(value))}function isFunction(value){return typeof value=="function"}function isObject(value){return!!(value&&objectTypes[typeof value])}function isNaN(value){return isNumber(value)&&value!=+value}function isNull(value){return value===null}function isNumber(value){return typeof value=="number"||value&&typeof value=="object"&&toString.call(value)==numberClass||false}var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&toString.call(value)==objectClass)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};function isRegExp(value){return value&&typeof value=="object"&&toString.call(value)==regexpClass||false}function isString(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)==stringClass||false}function isUndefined(value){return typeof value=="undefined"}function mapValues(object,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){result[key]=callback(value,key,object)});return result}function merge(object){var args=arguments,length=2;if(!isObject(object)){return object}if(typeof args[2]!="number"){length=args.length}if(length>3&&typeof args[length-2]=="function"){var callback=baseCreateCallback(args[--length-1],args[length--],2)}else if(length>2&&typeof args[length-1]=="function"){callback=args[--length]}var sources=slice(arguments,1,length),index=-1,stackA=getArray(),stackB=getArray();while(++index<length){baseMerge(object,sources[index],callback,stackA,stackB)}releaseArray(stackA);releaseArray(stackB);return object}function omit(object,callback,thisArg){var result={};if(typeof callback!="function"){var props=[];forIn(object,function(value,key){props.push(key)});props=baseDifference(props,baseFlatten(arguments,true,false,1));var index=-1,length=props.length;while(++index<length){var key=props[index];result[key]=object[key]}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(!callback(value,key,object)){result[key]=value}})}return result}function pairs(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){var key=props[index];result[index]=[key,object[key]]}return result}function pick(object,callback,thisArg){var result={};if(typeof callback!="function"){var index=-1,props=baseFlatten(arguments,true,false,1),length=isObject(object)?props.length:0;while(++index<length){var key=props[index];if(key in object){result[key]=object[key]}}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(callback(value,key,object)){result[key]=value}})}return result}function transform(object,callback,accumulator,thisArg){var isArr=isArray(object);if(accumulator==null){if(isArr){accumulator=[]}else{var ctor=object&&object.constructor,proto=ctor&&ctor.prototype;accumulator=baseCreate(proto)}}if(callback){callback=lodash.createCallback(callback,thisArg,4);(isArr?forEach:forOwn)(object,function(value,index,object){return callback(accumulator,value,index,object)})}return accumulator}function values(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}function at(collection){var args=arguments,index=-1,props=baseFlatten(args,true,false,1),length=args[2]&&args[2][args[1]]===collection?1:props.length,result=Array(length);while(++index<length){result[index]=collection[props[index]]}return result}function contains(collection,target,fromIndex){var index=-1,indexOf=getIndexOf(),length=collection?collection.length:0,result=false;fromIndex=(fromIndex<0?nativeMax(0,length+fromIndex):fromIndex)||0;if(isArray(collection)){result=indexOf(collection,target,fromIndex)>-1}else if(typeof length=="number"){result=(isString(collection)?collection.indexOf(target,fromIndex):indexOf(collection,target,fromIndex))>-1}else{forOwn(collection,function(value){if(++index>=fromIndex){return!(result=value===target)}})}return result}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key]++:result[key]=1});function every(collection,callback,thisArg){var result=true;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(!(result=!!callback(collection[index],index,collection))){break}}}else{forOwn(collection,function(value,index,collection){return result=!!callback(value,index,collection)})}return result}function filter(collection,callback,thisArg){var result=[];callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){result.push(value)}}}else{forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result.push(value)}})}return result}function find(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){return value}}}else{var result;forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}}function findLast(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forEachRight(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}function forEach(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(++index<length){if(callback(collection[index],index,collection)===false){break}}}else{forOwn(collection,callback)}return collection}function forEachRight(collection,callback,thisArg){var length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(length--){if(callback(collection[length],length,collection)===false){break}}}else{var props=keys(collection);length=props.length;forOwn(collection,function(value,key,collection){key=props?props[--length]:--length;return callback(collection[key],key,collection)})}return collection}var groupBy=createAggregator(function(result,value,key){(hasOwnProperty.call(result,key)?result[key]:result[key]=[]).push(value)});var indexBy=createAggregator(function(result,value,key){result[key]=value});function invoke(collection,methodName){var args=slice(arguments,2),index=-1,isFunc=typeof methodName=="function",length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){result[++index]=(isFunc?methodName:value[methodName]).apply(value,args)});return result}function map(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=lodash.createCallback(callback,thisArg,3);if(typeof length=="number"){var result=Array(length);while(++index<length){result[index]=callback(collection[index],index,collection)}}else{result=[];forOwn(collection,function(value,key,collection){result[++index]=callback(value,key,collection)})}return result}function max(collection,callback,thisArg){var computed=-Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value>result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current>computed){computed=current;result=value}})}return result}function min(collection,callback,thisArg){var computed=Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value<result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current<computed){computed=current;result=value}})}return result}var pluck=map;function reduce(collection,callback,accumulator,thisArg){if(!collection)return accumulator;var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);var index=-1,length=collection.length;if(typeof length=="number"){if(noaccum){accumulator=collection[++index]}while(++index<length){accumulator=callback(accumulator,collection[index],index,collection)}}else{forOwn(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)})}return accumulator}function reduceRight(collection,callback,accumulator,thisArg){var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);forEachRight(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)});return accumulator}function reject(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);return filter(collection,function(value,index,collection){return!callback(value,index,collection)})}function sample(collection,n,guard){if(collection&&typeof collection.length!="number"){collection=values(collection)}if(n==null||guard){return collection?collection[baseRandom(0,collection.length-1)]:undefined}var result=shuffle(collection);result.length=nativeMin(nativeMax(0,n),result.length);return result}function shuffle(collection){var index=-1,length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){var rand=baseRandom(0,++index);result[index]=result[rand];result[rand]=value});return result}function size(collection){var length=collection?collection.length:0;return typeof length=="number"?length:keys(collection).length}function some(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(result=callback(collection[index],index,collection)){break}}}else{forOwn(collection,function(value,index,collection){return!(result=callback(value,index,collection))})}return!!result}function sortBy(collection,callback,thisArg){var index=-1,isArr=isArray(callback),length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);if(!isArr){callback=lodash.createCallback(callback,thisArg,3)}forEach(collection,function(value,key,collection){var object=result[++index]=getObject();if(isArr){object.criteria=map(callback,function(key){return value[key]})}else{(object.criteria=getArray())[0]=callback(value,key,collection)}object.index=index;object.value=value});length=result.length;result.sort(compareAscending);while(length--){var object=result[length];result[length]=object.value;if(!isArr){releaseArray(object.criteria)}releaseObject(object)}return result}function toArray(collection){if(collection&&typeof collection.length=="number"){return slice(collection)}return values(collection)}var where=filter;function compact(array){var index=-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value){result.push(value)}}return result}function difference(array){return baseDifference(array,baseFlatten(arguments,true,true,1))}function findIndex(array,callback,thisArg){var index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length){if(callback(array[index],index,array)){return index}}return-1}function findLastIndex(array,callback,thisArg){var length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(length--){if(callback(array[length],length,array)){return length}}return-1}function first(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=-1;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[0]:undefined}}return slice(array,0,nativeMin(nativeMax(0,n),length))}function flatten(array,isShallow,callback,thisArg){if(typeof isShallow!="boolean"&&isShallow!=null){thisArg=callback;callback=typeof isShallow!="function"&&thisArg&&thisArg[isShallow]===array?null:isShallow;isShallow=false}if(callback!=null){array=map(array,callback,thisArg)}return baseFlatten(array,isShallow)}function indexOf(array,value,fromIndex){if(typeof fromIndex=="number"){var length=array?array.length:0;fromIndex=fromIndex<0?nativeMax(0,length+fromIndex):fromIndex||0}else if(fromIndex){var index=sortedIndex(array,value);return array[index]===value?index:-1}return baseIndexOf(array,value,fromIndex)}function initial(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:callback||n}return slice(array,0,nativeMin(nativeMax(0,length-n),length))}function intersection(){var args=[],argsIndex=-1,argsLength=arguments.length,caches=getArray(),indexOf=getIndexOf(),trustIndexOf=indexOf===baseIndexOf,seen=getArray();while(++argsIndex<argsLength){var value=arguments[argsIndex];if(isArray(value)||isArguments(value)){args.push(value);caches.push(trustIndexOf&&value.length>=largeArraySize&&createCache(argsIndex?args[argsIndex]:seen))}}var array=args[0],index=-1,length=array?array.length:0,result=[];outer:while(++index<length){var cache=caches[0];value=array[index];if((cache?cacheIndexOf(cache,value):indexOf(seen,value))<0){argsIndex=argsLength;(cache||seen).push(value);while(--argsIndex){cache=caches[argsIndex];if((cache?cacheIndexOf(cache,value):indexOf(args[argsIndex],value))<0){continue outer}}result.push(value)}}while(argsLength--){cache=caches[argsLength];if(cache){releaseObject(cache)}}releaseArray(caches);releaseArray(seen);return result}function last(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[length-1]:undefined}}return slice(array,nativeMax(0,length-n))}function lastIndexOf(array,value,fromIndex){var index=array?array.length:0;if(typeof fromIndex=="number"){index=(fromIndex<0?nativeMax(0,index+fromIndex):nativeMin(fromIndex,index-1))+1}while(index--){if(array[index]===value){return index}}return-1}function pull(array){var args=arguments,argsIndex=0,argsLength=args.length,length=array?array.length:0;while(++argsIndex<argsLength){var index=-1,value=args[argsIndex];while(++index<length){if(array[index]===value){splice.call(array,index--,1);length--}}}return array}function range(start,end,step){start=+start||0;step=typeof step=="number"?step:+step||1;if(end==null){end=start;start=0}var index=-1,length=nativeMax(0,ceil((end-start)/(step||1))),result=Array(length);while(++index<length){result[index]=start;start+=step}return result}function remove(array,callback,thisArg){var index=-1,length=array?array.length:0,result=[];callback=lodash.createCallback(callback,thisArg,3);while(++index<length){var value=array[index];if(callback(value,index,array)){result.push(value);splice.call(array,index--,1);length--}}return result}function rest(array,callback,thisArg){if(typeof callback!="number"&&callback!=null){var n=0,index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:nativeMax(0,callback)}return slice(array,n)}function sortedIndex(array,value,callback,thisArg){var low=0,high=array?array.length:low;callback=callback?lodash.createCallback(callback,thisArg,1):identity;value=callback(value);while(low<high){var mid=low+high>>>1;callback(array[mid])<value?low=mid+1:high=mid}return low}function union(){return baseUniq(baseFlatten(arguments,true,true))}function uniq(array,isSorted,callback,thisArg){if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=callback;callback=typeof isSorted!="function"&&thisArg&&thisArg[isSorted]===array?null:isSorted;isSorted=false}if(callback!=null){callback=lodash.createCallback(callback,thisArg,3)}return baseUniq(array,isSorted,callback)}function without(array){return baseDifference(array,slice(arguments,1))}function xor(){var index=-1,length=arguments.length;while(++index<length){var array=arguments[index];if(isArray(array)||isArguments(array)){var result=result?baseUniq(baseDifference(result,array).concat(baseDifference(array,result))):array}}return result||[]}function zip(){var array=arguments.length>1?arguments:arguments[0],index=-1,length=array?max(pluck(array,"length")):0,result=Array(length<0?0:length);while(++index<length){result[index]=pluck(array,index)}return result}function zipObject(keys,values){var index=-1,length=keys?keys.length:0,result={};if(!values&&length&&!isArray(keys[0])){values=[]}while(++index<length){var key=keys[index];if(values){result[key]=values[index]}else if(key){result[key[0]]=key[1]}}return result}function after(n,func){if(!isFunction(func)){throw new TypeError}return function(){if(--n<1){return func.apply(this,arguments)}}}function bind(func,thisArg){return arguments.length>2?createWrapper(func,17,slice(arguments,2),null,thisArg):createWrapper(func,1,null,null,thisArg)}function bindAll(object){var funcs=arguments.length>1?baseFlatten(arguments,true,false,1):functions(object),index=-1,length=funcs.length;while(++index<length){var key=funcs[index];object[key]=createWrapper(object[key],1,null,null,object)}return object}function bindKey(object,key){return arguments.length>2?createWrapper(key,19,slice(arguments,2),null,object):createWrapper(key,3,null,null,object)}function compose(){var funcs=arguments,length=funcs.length;while(length--){if(!isFunction(funcs[length])){throw new TypeError}}return function(){var args=arguments,length=funcs.length;while(length--){args=[funcs[length].apply(this,args)]}return args[0]}}function curry(func,arity){arity=typeof arity=="number"?arity:+arity||func.length;return createWrapper(func,4,null,null,null,arity)}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,maxWait=false,trailing=true;if(!isFunction(func)){throw new TypeError}wait=nativeMax(0,wait)||0;if(options===true){var leading=true;trailing=false}else if(isObject(options)){leading=options.leading;maxWait="maxWait"in options&&(nativeMax(wait,options.maxWait)||0);trailing="trailing"in options?options.trailing:trailing}var delayed=function(){var remaining=wait-(now()-stamp);if(remaining<=0){if(maxTimeoutId){clearTimeout(maxTimeoutId)}var isCalled=trailingCall;maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}else{timeoutId=setTimeout(delayed,remaining)}};var maxDelayed=function(){if(timeoutId){clearTimeout(timeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined;if(trailing||maxWait!==wait){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}};return function(){args=arguments;stamp=now();thisArg=this;trailingCall=trailing&&(timeoutId||!leading);if(maxWait===false){var leadingCall=leading&&!timeoutId}else{if(!maxTimeoutId&&!leading){lastCalled=stamp}var remaining=maxWait-(stamp-lastCalled),isCalled=remaining<=0;if(isCalled){if(maxTimeoutId){maxTimeoutId=clearTimeout(maxTimeoutId)}lastCalled=stamp;result=func.apply(thisArg,args)}else if(!maxTimeoutId){maxTimeoutId=setTimeout(maxDelayed,remaining)}}if(isCalled&&timeoutId){timeoutId=clearTimeout(timeoutId)}else if(!timeoutId&&wait!==maxWait){timeoutId=setTimeout(delayed,wait)}if(leadingCall){isCalled=true;result=func.apply(thisArg,args)}if(isCalled&&!timeoutId&&!maxTimeoutId){args=thisArg=null}return result}}function defer(func){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,1);return setTimeout(function(){func.apply(undefined,args)},1)}function delay(func,wait){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,2);return setTimeout(function(){func.apply(undefined,args)},wait)}function memoize(func,resolver){if(!isFunction(func)){throw new TypeError}var memoized=function(){var cache=memoized.cache,key=resolver?resolver.apply(this,arguments):keyPrefix+arguments[0];return hasOwnProperty.call(cache,key)?cache[key]:cache[key]=func.apply(this,arguments)};memoized.cache={};return memoized}function once(func){var ran,result;if(!isFunction(func)){throw new TypeError}return function(){if(ran){return result}ran=true;result=func.apply(this,arguments);func=null;return result}}function partial(func){return createWrapper(func,16,slice(arguments,1))}function partialRight(func){return createWrapper(func,32,null,slice(arguments,1))}function throttle(func,wait,options){var leading=true,trailing=true;if(!isFunction(func)){throw new TypeError}if(options===false){leading=false}else if(isObject(options)){leading="leading"in options?options.leading:leading;trailing="trailing"in options?options.trailing:trailing}debounceOptions.leading=leading;debounceOptions.maxWait=wait;debounceOptions.trailing=trailing;return debounce(func,wait,debounceOptions)}function wrap(value,wrapper){return createWrapper(wrapper,16,[value])}function constant(value){return function(){return value}}function createCallback(func,thisArg,argCount){var type=typeof func;if(func==null||type=="function"){return baseCreateCallback(func,thisArg,argCount)}if(type!="object"){return property(func)}var props=keys(func),key=props[0],a=func[key];if(props.length==1&&a===a&&!isObject(a)){return function(object){var b=object[key];return a===b&&(a!==0||1/a==1/b)}}return function(object){var length=props.length,result=false;while(length--){if(!(result=baseIsEqual(object[props[length]],func[props[length]],null,true))){break}}return result}}function escape(string){return string==null?"":String(string).replace(reUnescapedHtml,escapeHtmlChar)}function identity(value){return value}function mixin(object,source,options){var chain=true,methodNames=source&&functions(source);if(!source||!options&&!methodNames.length){if(options==null){options=source}ctor=lodashWrapper;source=object;object=lodash;methodNames=functions(source)}if(options===false){chain=false}else if(isObject(options)&&"chain"in options){chain=options.chain}var ctor=object,isFunc=isFunction(ctor);forEach(methodNames,function(methodName){var func=object[methodName]=source[methodName];if(isFunc){ctor.prototype[methodName]=function(){var chainAll=this.__chain__,value=this.__wrapped__,args=[value];push.apply(args,arguments);var result=func.apply(object,args);if(chain||chainAll){if(value===result&&isObject(result)){return this}result=new ctor(result);result.__chain__=chainAll}return result}}})}function noConflict(){context._=oldDash;return this}function noop(){}var now=isNative(now=Date.now)&&now||function(){return(new Date).getTime()};var parseInt=nativeParseInt(whitespace+"08")==8?nativeParseInt:function(value,radix){return nativeParseInt(isString(value)?value.replace(reLeadingSpacesAndZeros,""):value,radix||0)};function property(key){return function(object){return object[key]}}function random(min,max,floating){var noMin=min==null,noMax=max==null;if(floating==null){if(typeof min=="boolean"&&noMax){floating=min;min=1}else if(!noMax&&typeof max=="boolean"){floating=max;noMax=true}}if(noMin&&noMax){max=1}min=+min||0;if(noMax){max=min;min=0}else{max=+max||0}if(floating||min%1||max%1){var rand=nativeRandom();return nativeMin(min+rand*(max-min+parseFloat("1e-"+((rand+"").length-1))),max)}return baseRandom(min,max)}function result(object,key){if(object){var value=object[key];return isFunction(value)?object[key]():value}}function template(text,data,options){var settings=lodash.templateSettings; text=String(text||"");options=defaults({},options,settings);var imports=defaults({},options.imports,settings.imports),importsKeys=keys(imports),importsValues=values(imports);var isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");text.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=text.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable,hasVariable=variable;if(!hasVariable){variable="obj";source="with ("+variable+") {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+variable+") {\n"+(hasVariable?"":variable+" || ("+variable+" = {});\n")+"var __t, __p = '', __e = _.escape"+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var sourceURL="\n/*\n//# sourceURL="+(options.sourceURL||"/lodash/template/source["+templateCounter++ +"]")+"\n*/";try{var result=Function(importsKeys,"return "+source+sourceURL).apply(undefined,importsValues)}catch(e){e.source=source;throw e}if(data){return result(data)}result.source=source;return result}function times(n,callback,thisArg){n=(n=+n)>-1?n:0;var index=-1,result=Array(n);callback=baseCreateCallback(callback,thisArg,1);while(++index<n){result[index]=callback(index)}return result}function unescape(string){return string==null?"":String(string).replace(reEscapedHtml,unescapeHtmlChar)}function uniqueId(prefix){var id=++idCounter;return String(prefix==null?"":prefix)+id}function chain(value){value=new lodashWrapper(value);value.__chain__=true;return value}function tap(value,interceptor){interceptor(value);return value}function wrapperChain(){this.__chain__=true;return this}function wrapperToString(){return String(this.__wrapped__)}function wrapperValueOf(){return this.__wrapped__}lodash.after=after;lodash.assign=assign;lodash.at=at;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.chain=chain;lodash.compact=compact;lodash.compose=compose;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.createCallback=createCallback;lodash.curry=curry;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.filter=filter;lodash.flatten=flatten;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.functions=functions;lodash.groupBy=groupBy;lodash.indexBy=indexBy;lodash.initial=initial;lodash.intersection=intersection;lodash.invert=invert;lodash.invoke=invoke;lodash.keys=keys;lodash.map=map;lodash.mapValues=mapValues;lodash.max=max;lodash.memoize=memoize;lodash.merge=merge;lodash.min=min;lodash.omit=omit;lodash.once=once;lodash.pairs=pairs;lodash.partial=partial;lodash.partialRight=partialRight;lodash.pick=pick;lodash.pluck=pluck;lodash.property=property;lodash.pull=pull;lodash.range=range;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.shuffle=shuffle;lodash.sortBy=sortBy;lodash.tap=tap;lodash.throttle=throttle;lodash.times=times;lodash.toArray=toArray;lodash.transform=transform;lodash.union=union;lodash.uniq=uniq;lodash.values=values;lodash.where=where;lodash.without=without;lodash.wrap=wrap;lodash.xor=xor;lodash.zip=zip;lodash.zipObject=zipObject;lodash.collect=map;lodash.drop=rest;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assign;lodash.methods=functions;lodash.object=zipObject;lodash.select=filter;lodash.tail=rest;lodash.unique=uniq;lodash.unzip=zip;mixin(lodash);lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.contains=contains;lodash.escape=escape;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.has=has;lodash.identity=identity;lodash.indexOf=indexOf;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isNaN=isNaN;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isString=isString;lodash.isUndefined=isUndefined;lodash.lastIndexOf=lastIndexOf;lodash.mixin=mixin;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.result=result;lodash.runInContext=runInContext;lodash.size=size;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.template=template;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.all=every;lodash.any=some;lodash.detect=find;lodash.findWhere=find;lodash.foldl=reduce;lodash.foldr=reduceRight;lodash.include=contains;lodash.inject=reduce;mixin(function(){var source={};forOwn(lodash,function(func,methodName){if(!lodash.prototype[methodName]){source[methodName]=func}});return source}(),false);lodash.first=first;lodash.last=last;lodash.sample=sample;lodash.take=first;lodash.head=first;forOwn(lodash,function(func,methodName){var callbackable=methodName!=="sample";if(!lodash.prototype[methodName]){lodash.prototype[methodName]=function(n,guard){var chainAll=this.__chain__,result=func(this.__wrapped__,n,guard);return!chainAll&&(n==null||guard&&!(callbackable&&typeof n=="function"))?result:new lodashWrapper(result,chainAll)}}});lodash.VERSION="2.4.1";lodash.prototype.chain=wrapperChain;lodash.prototype.toString=wrapperToString;lodash.prototype.value=wrapperValueOf;lodash.prototype.valueOf=wrapperValueOf;forEach(["join","pop","shift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){var chainAll=this.__chain__,result=func.apply(this.__wrapped__,arguments);return chainAll?new lodashWrapper(result,chainAll):result}});forEach(["push","reverse","sort","unshift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){func.apply(this.__wrapped__,arguments);return this}});forEach(["concat","slice","splice"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){return new lodashWrapper(func.apply(this.__wrapped__,arguments),this.__chain__)}});return lodash}var _=runInContext();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root._=_;define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}else{freeExports._=_}}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],99:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],100:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:102}],101:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],102:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<=65535&&end<=65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}else{loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,end+1)}}else if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}else if(start<HIGH_SURROGATE_MIN&&end>HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,end+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,end+1)}}else if(start<=65535&&end>65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,65535+1)}else if(start<HIGH_SURROGATE_MIN){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,65535+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,65535+1)}astral.push(65535+1,end+1)}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneSurrogates=!dataIsEmpty(loneHighSurrogates);var surrogateMappings=surrogateSet(astral);if(!hasAstral&&hasLoneSurrogates){bmp=dataAddData(bmp,loneHighSurrogates)}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasAstral&&hasLoneSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.0.1";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(){var result=createCharacterClassesFromData(this.data);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],103:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass"); var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],104:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&&current("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,6})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="‌";var ZWNJ="‍";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],105:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":100,"./data/iu-mappings.json":101,regenerate:102,regjsgen:103,regjsparser:104}],106:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":111,"./source-map/source-map-generator":112,"./source-map/source-node":113}],107:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":114,amdefine:115}],108:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":109,amdefine:115}],109:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:115}],110:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return aHaystack[mid]}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return aHaystack[mid]}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?null:aHaystack[aLow]}}exports.search=function search(aNeedle,aHaystack,aCompare){return aHaystack.length>0?recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare):null}})},{amdefine:115}],111:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.slice().sort(util.compareByGeneratedPositions);smc.__originalMappings=aSourceMap._mappings.slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var mapping=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(mapping&&mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mapping=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(mapping){return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null)}}return{line:null,column:null}};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":107,"./base64-vlq":108,"./binary-search":110,"./util":114,amdefine:115}],112:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=[];this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source) }newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);this._validateMapping(generated,original,source,name);if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.push({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.forEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;this._mappings.sort(util.compareByGeneratedPositions);for(var i=0,len=this._mappings.length;i<len;i++){mapping=this._mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,this._mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":107,"./base64-vlq":108,"./util":114,amdefine:115}],113:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var REGEX_CHARACTER=/\r\n|[\s\S]/g;function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk instanceof SourceNode){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild instanceof SourceNode){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i]instanceof SourceNode){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}chunk.match(REGEX_CHARACTER).forEach(function(ch,idx,array){if(REGEX_NEWLINE.test(ch)){generated.line++;generated.column=0;if(idx+1===array.length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column+=ch.length}})});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":112,"./util":114,amdefine:115}],114:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:115}],115:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps)})}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:90,path:89}],116:[function(require,module,exports){module.exports={"apply-constructor":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"bindArgs"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"ArrayExpression",elements:[{type:"Literal",value:null}]},property:{type:"Identifier",name:"concat"},computed:false},arguments:[{type:"Identifier",name:"args"}]}}],kind:"var"},{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"Factory"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"bind"},computed:false},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"bindArgs"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"Factory"},arguments:[]}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{bindArgs:{type:"Identifier",name:"bindArgs"},Factory:{type:"Identifier",name:"Factory"},Constructor:{type:"Identifier",name:"Constructor"},args:{type:"Identifier",name:"args"}}}}}}],_scope:{declarations:{}}},"arguments-slice-assign-arg":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SLICE_KEY"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"arguments"},{type:"Identifier",name:"SLICE_ARG"}]}}],kind:"var"}],_scope:{declarations:{VARIABLE_NAME:{type:"Identifier",name:"VARIABLE_NAME"}}}},"arguments-slice-assign":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SLICE_KEY"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"arguments"}]}}],kind:"var"}],_scope:{declarations:{VARIABLE_NAME:{type:"Identifier",name:"VARIABLE_NAME"}}}},"arguments-slice":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SLICE_KEY"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"arguments"}]}}],_scope:{declarations:{}}},"array-comprehension-container":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{KEY:{type:"Identifier",name:"KEY"}}}}},arguments:[]}}],_scope:{declarations:{}}},"array-comprehension-for-each":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"forEach"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[],_scope:{declarations:{}}},expression:false,_scope:{declarations:{KEY:{type:"Identifier",name:"KEY"}}}}]}}],_scope:{declarations:{}}},"array-expression-comprehension-filter":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"filter"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"FILTER"}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{KEY:{type:"Identifier",name:"KEY"}}}}]},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{KEY:{type:"Identifier",name:"KEY"}}}}]}}],_scope:{declarations:{}}},"array-expression-comprehension-map":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{KEY:{type:"Identifier",name:"KEY"}}}}]}}],_scope:{declarations:{}}},"array-push":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"KEY"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"Identifier",name:"STATEMENT"}]}}],_scope:{declarations:{}}},call:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"CONTEXT"}]}}],_scope:{declarations:{}}},"class-props":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"},{type:"Identifier",name:"instanceProps"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"staticProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"}]}},alternate:null},{type:"IfStatement",test:{type:"Identifier",name:"instanceProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"Identifier",name:"instanceProps"}]}},alternate:null}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{child:{type:"Identifier",name:"child"},staticProps:{type:"Identifier",name:"staticProps"},instanceProps:{type:"Identifier",name:"instanceProps"}}}}}}],_scope:{declarations:{}}},"class-super-constructor-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SUPER_NAME"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}],_scope:{declarations:{}}},"class":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"CLASS_NAME"},init:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[],_scope:{declarations:{}}},expression:false,_scope:{declarations:{}}}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"CLASS_NAME"}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{CLASS_NAME:{type:"Identifier",name:"CLASS_NAME"}}}}},arguments:[]}}],_scope:{declarations:{}}},"exports-assign-key":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"VARIABLE_NAME"},computed:false},right:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"KEY"},computed:false}}}],_scope:{declarations:{}}},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}],_scope:{declarations:{}}},"exports-default":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"default"},computed:false},right:{type:"Identifier",name:"VALUE"}}}],_scope:{declarations:{}}},"exports-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}],_scope:{declarations:{}}},_scope:{declarations:{}}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{i:{type:"Identifier",name:"i"},obj:{type:"Identifier",name:"obj"}}}}},arguments:[{type:"Identifier",name:"OBJECT"}]}}],_scope:{declarations:{}}},"extends":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"parent"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"parent"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"constructor"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"child"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:false},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"}]},kind:"init"}]}]}}},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"__proto__"},computed:false},right:{type:"Identifier",name:"parent"}}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{child:{type:"Identifier",name:"child"},parent:{type:"Identifier",name:"parent"}}}}}}],_scope:{declarations:{}}},"for-of":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"ITERATOR_KEY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"STEP_KEY"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"ParenthesizedExpression",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"STEP_KEY"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ITERATOR_KEY"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[],_scope:{declarations:{}}},_scope:{declarations:{}}}],_scope:{declarations:{ITERATOR_KEY:{type:"Identifier",name:"ITERATOR_KEY"},STEP_KEY:{type:"Identifier",name:"STEP_KEY"}}}},"function-return-obj":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{KEY:{type:"Identifier",name:"KEY"}}}}},arguments:[{type:"Identifier",name:"OBJECT"}]}}],_scope:{declarations:{}}},"if-undefined-set-to":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"VARIABLE"},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"VARIABLE"},right:{type:"Identifier",name:"DEFAULT"}}},alternate:null}],_scope:{declarations:{}}},"let-scoping-return":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"RETURN"}},operator:"===",right:{type:"Literal",value:"object"}},consequent:{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"RETURN"},property:{type:"Identifier",name:"v"},computed:false}},alternate:null}],_scope:{declarations:{}}},"object-define-properties-closure":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"Identifier",name:"CONTENT"}},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{KEY:{type:"Identifier",name:"KEY"}}}}},arguments:[{type:"Identifier",name:"OBJECT"}]}}],_scope:{declarations:{}}},"object-define-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"PROPS"}]}}],_scope:{declarations:{}}},"prototype-identifier":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"Identifier",name:"CLASS_NAME"},property:{type:"Identifier",name:"prototype"},computed:false}}],_scope:{declarations:{}}},"require-assign-key":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]},property:{type:"Identifier",name:"KEY"},computed:false}}],kind:"var"}],_scope:{declarations:{VARIABLE_NAME:{type:"Identifier",name:"VARIABLE_NAME"}}}},"require-assign":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}],kind:"var"}],_scope:{declarations:{VARIABLE_NAME:{type:"Identifier",name:"VARIABLE_NAME"}}}},require:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}],_scope:{declarations:{}}},"self-global":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"self"},init:{type:"ConditionalExpression",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"global"}},operator:"===",right:{type:"Literal",value:"undefined"}},consequent:{type:"Identifier",name:"window"},alternate:{type:"Identifier",name:"global"}}}],kind:"var"}],_scope:{declarations:{self:{type:"Identifier",name:"self"}}}},slice:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"slice"},computed:false}}],_scope:{declarations:{}}},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"strings"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"raw"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"raw"},kind:"init"}]},kind:"init"}]}]}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{strings:{type:"Identifier",name:"strings"},raw:{type:"Identifier",name:"raw"}}}}}}],_scope:{declarations:{}}},"umd-runner-body":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"factory"}],defaults:[],rest:null,generator:false,async:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"define"}},operator:"===",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"define"},property:{type:"Identifier",name:"amd"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"define"},arguments:[{type:"Identifier",name:"AMD_ARGUMENTS"},{type:"Identifier",name:"factory"}]}}],_scope:{declarations:{}}},alternate:{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"exports"}},operator:"!==",right:{type:"Literal",value:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"factory"},arguments:[{type:"Identifier",name:"exports"},{type:"Identifier",name:"COMMON_ARGUMENTS"}]}}],_scope:{declarations:{}}},alternate:null}}],_scope:{declarations:{}}},expression:false,_scope:{declarations:{factory:{type:"Identifier",name:"factory"}}}}}}],_scope:{declarations:{}}}} },{}]},{},[2])(2)});
// @flow weak /* eslint-env mocha */ import React from 'react'; import { assert } from 'chai'; import { createShallowWithContext } from 'test/utils'; import Paper, { styleSheet } from './Paper'; describe('<Paper />', () => { let shallow; let classes; before(() => { shallow = createShallowWithContext(); classes = shallow.context.styleManager.render(styleSheet); }); it('should render a div', () => { const wrapper = shallow( <Paper>Hello World</Paper>, ); assert.strictEqual(wrapper.is('div'), true, 'should be a div'); }); it('should render with the paper class, default depth class, and rounded', () => { const wrapper = shallow(<Paper>Hello World</Paper>); assert.strictEqual(wrapper.hasClass(classes.paper), true, 'should have the paper class'); assert.strictEqual(wrapper.hasClass(classes.rounded), true, 'should be rounded by default'); }); it('should disable the rounded class', () => { const wrapper = shallow(<Paper rounded={false}>Hello World</Paper>); assert.strictEqual(wrapper.hasClass(classes.rounded), false, 'should not be rounded'); }); it('should set the zDepth shadow class', () => { const wrapper = shallow(<Paper zDepth={16}>Hello World</Paper>); assert.strictEqual(wrapper.hasClass(classes.dp16), true, 'should have the dp16 shadow class'); wrapper.setProps({ zDepth: 24 }); assert.strictEqual(wrapper.hasClass(classes.dp24), true, 'should have the dp24 shadow class'); wrapper.setProps({ zDepth: 2 }); assert.strictEqual(wrapper.hasClass(classes.dp2), true, 'should have the dp2 shadow class'); }); });
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){ (function (global){ //! moment.js //! version : 2.8.3 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = '2.8.3', // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, hasOwnProperty = Object.prototype.hasOwnProperty, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for locale config files locales = {}, // extra moment internal properties (plugins register props here) momentProperties = [], // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 parseTokenOrdinal = /\d{1,2}/, //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-15', '30'] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.localeData().monthsShort(this, format); }, MMMM : function (format) { return this.localeData().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.localeData().weekdaysMin(this, format); }, ddd : function (format) { return this.localeData().weekdaysShort(this, format); }, dddd : function (format) { return this.localeData().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.localeData().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.localeData().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, deprecations = {}, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error('Implement me'); } } function hasOwnProp(a, b) { return hasOwnProperty.call(a, b); } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function printMsg(msg) { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { printMsg(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } function deprecateSimple(name, msg) { if (!deprecations[name]) { printMsg(msg); deprecations[name] = true; } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Locale() { } // Moment prototype object function Moment(config, skipOverflow) { if (skipOverflow !== false) { checkOverflow(config); } copyConfig(this, config); this._d = new Date(+config._d); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = moment.localeData(); this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = makeAs(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = moment.duration(val, period); addOrSubtractDurationFromMoment(this, dur, direction); return this; }; } function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment._locale[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment._locale, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; if (!locales[name] && hasModule) { try { oldLocale = moment.locale(); require('./locale/' + name); // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales moment.locale(oldLocale); } catch (e) { } } return locales[name]; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Locale ************************************/ extend(Locale.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), months : function (m) { return this._months[m.month()]; }, _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace('%d', number); }, _ordinal : '%d', preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return config._locale._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return parseTokenOrdinal; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); return a; } } function timezoneMinutesFromString(string) { string = string || ''; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = config._locale.monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt(input, 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = config._locale.isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be 'T' or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += 'Z'; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function makeDateFromInput(config) { var input = config._i, matched; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if ((matched = aspNetJsonRegex.exec(input)) !== null) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); dateFromConfig(config); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(posNegDuration, withoutSuffix, locale) { var duration = moment.duration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), years = round(duration.as('y')), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days < relativeTimeThresholds.d && ['dd', days] || months === 1 && ['M'] || months < relativeTimeThresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = +posNegDuration > 0; args[4] = locale; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; config._locale = config._locale || moment.localeData(config._l); if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (moment.isMoment(input)) { return new Moment(input, true); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = locale; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i); } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, diffRes; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(moment(duration.from), moment(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (moment.isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function (threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } if (limit === undefined) { return relativeTimeThresholds[threshold]; } relativeTimeThresholds[threshold] = limit; return true; }; moment.lang = deprecate( 'moment.lang is deprecated. Use moment.locale instead.', function (key, value) { return moment.locale(key, value); } ); // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. moment.locale = function (key, values) { var data; if (key) { if (typeof(values) !== 'undefined') { data = moment.defineLocale(key, values); } else { data = moment.localeData(key); } if (data) { moment.duration._locale = moment._locale = data; } } return moment._locale._abbr; }; moment.defineLocale = function (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale moment.locale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } }; moment.langData = deprecate( 'moment.langData is deprecated. Use moment.localeData instead.', function (key) { return moment.localeData(key); } ); // returns locale data moment.localeData = function (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return moment._locale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && hasOwnProp(obj, '_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function (keepLocalTime) { return this.zone(0, keepLocalTime); }, local : function (keepLocalTime) { if (this._isUTC) { this.zone(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.add(this._dateTzOffset(), 'm'); } } return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.localeData().postformat(output); }, add : createAdder(1, 'add'), subtract : createAdder(-1, 'subtract'), diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output, daysAdjust; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. daysAdjust = (this - moment(this).startOf('month')) - (that - moment(that).startOf('month')); // same as above but with zones, to negate all dst daysAdjust -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4; output += daysAdjust / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } }, month : makeAccessor('Month', true), startOf : function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); }, isAfter: function (input, units) { units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this > +input; } else { return +this.clone().startOf(units) > +moment(input).startOf(units); } }, isBefore: function (input, units) { units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this < +input; } else { return +this.clone().startOf(units) < +moment(input).startOf(units); } }, isSame: function (input, units) { units = normalizeUnits(units || 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this === +input; } else { return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); } }, min: deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = this._dateTzOffset(); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.subtract(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._dateTzOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? 'UTC' : ''; }, zoneName : function () { return this._isUTC ? 'Coordinated Universal Time' : ''; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); }, week : function (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); }, weekday : function (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. locale : function (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = moment.localeData(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } }, lang : deprecate( 'moment().lang() is deprecated. Use moment().localeData() instead.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ), localeData : function () { return this._locale; }, _dateTzOffset : function () { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return Math.round(this._d.getTimezoneOffset() / 15) * 15; } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absRound(years / 4) - // absRound(years / 100) + absRound(years / 400); return years * 146097 / 400; } extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); // Accurately convert days to years, assume start from year 0. years = absRound(daysToYears(days)); days -= absRound(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absRound(days / 30); days %= 30; // 12 months -> 1 year years += absRound(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; }, abs : function () { this._milliseconds = Math.abs(this._milliseconds); this._days = Math.abs(this._days); this._months = Math.abs(this._months); this._data.milliseconds = Math.abs(this._data.milliseconds); this._data.seconds = Math.abs(this._data.seconds); this._data.minutes = Math.abs(this._data.minutes); this._data.hours = Math.abs(this._data.hours); this._data.months = Math.abs(this._data.months); this._data.years = Math.abs(this._data.years); return this; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var output = relativeTime(this, !withSuffix, this.localeData()); if (withSuffix) { output = this.localeData().pastFuture(+this, output); } return this.localeData().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { var days, months; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + this._milliseconds / 864e5; months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + yearsToDays(this._months / 12); switch (units) { case 'week': return days / 7 + this._milliseconds / 6048e5; case 'day': return days + this._milliseconds / 864e5; case 'hour': return days * 24 + this._milliseconds / 36e5; case 'minute': return days * 24 * 60 + this._milliseconds / 6e4; case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds; default: throw new Error('Unknown unit ' + units); } } }, lang : moment.fn.lang, locale : moment.fn.locale, toIsoString : deprecate( 'toIsoString() is deprecated. Please use toISOString() instead ' + '(notice the capitals)', function () { return this.toISOString(); } ), toISOString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); }, localeData : function () { return this._locale; } }); moment.duration.fn.toString = moment.duration.fn.toISOString; function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } for (i in unitMillisecondFactors) { if (hasOwnProp(unitMillisecondFactors, i)) { makeDurationGetter(i.toLowerCase()); } } moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; moment.duration.fn.asSeconds = function () { return this.as('s'); }; moment.duration.fn.asMinutes = function () { return this.as('m'); }; moment.duration.fn.asHours = function () { return this.as('h'); }; moment.duration.fn.asDays = function () { return this.as('d'); }; moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; moment.duration.fn.asMonths = function () { return this.as('M'); }; moment.duration.fn.asYears = function () { return this.as('y'); }; /************************************ Default Locale ************************************/ // Set default locale, other locale will inherit from English. moment.locale('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LOCALES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( 'Accessing Moment through the global scope is ' + 'deprecated, and will be removed in an upcoming ' + 'release.', moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (typeof define === 'function' && define.amd) { define('moment', function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }); makeGlobal(true); } else { makeGlobal(); } }).call(this); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],5:[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; },{}],6:[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}],7:[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 = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; 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":12,"./utils":24,"underscore":7}],"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"}],12:[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":59,"underscore":7}],13:[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;vertical-align:middle;text-align:left;padding:0 6px;color:rgba(255,255,255,.3);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.7;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":7}],"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'); },{}],16:[function(require,module,exports){ "use strict"; var PluginMixin = { initialize: function() { this.bindEvents(); }, enable: function() { this.bindEvents(); }, disable: function() { this.stopListening(); } }; module.exports = PluginMixin; },{}],17:[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":13,"jquery":3,"underscore":7}],"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":24,"jquery":3,"underscore":7}],"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":16,"./ui_object":"8lqCAT","./utils":24,"underscore":7}],"ui_plugin":[function(require,module,exports){ module.exports=require('Z7u8cr'); },{}],24:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var Moment = require('moment'); 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, options) { options = options || {}; var separator = options.humanFriendly ? 'm' : ':'; var duration = Moment.duration(time * 1000); var str = zeroPad(duration.seconds(), 2); if (duration.hours()) { str = zeroPad(duration.minutes(), 2) + separator + (options.humanFriendly ? '' : str); if (options.humanFriendly) { separator = 'h'; } str = duration.hours() + separator + str; } else { var minutes = duration.minutes(); str = (!options.humanFriendly || minutes > 0 ? minutes + separator : '') + str; if (options.humanFriendly) { str += 's'; } } if (options.showMillis && !options.humanFriendly) { str += separator + duration.milliseconds(); } return str; }; 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,"moment":4,"underscore":7}],"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.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|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'); },{}],27:[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.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":17,"../../base/ui_object":"8lqCAT","underscore":7}],28:[function(require,module,exports){ "use strict"; module.exports = require('./container'); },{"./container":27}],29:[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":28,"jquery":3,"underscore":7}],30:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":29}],31:[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":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"../container_factory":30,"../media_control":"A8Uh+k","../mediator":"veeMMc","../player_info":"Pce0iO","jquery":3,"underscore":7}],32:[function(require,module,exports){ "use strict"; module.exports = require('./core'); },{"./core":31}],33:[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":32,"underscore":7}],34:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":33}],35:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":36}],36:[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":49,"../../playbacks/hls":51,"../../playbacks/html5_audio":53,"../../playbacks/html5_video":55,"../../playbacks/no_op":56,"../../plugins/background_button":58,"../../plugins/poster":61,"../../plugins/spinner_three_bounce":63,"../../plugins/stats":65,"../../plugins/watermark":67,"../player_info":"Pce0iO","underscore":7}],"A8Uh+k":[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":39}],"media_control":[function(require,module,exports){ module.exports=require('A8Uh+k'); },{}],39:[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 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: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('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', (function() { $__0.$volumeBarContainer.off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend'); $__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; 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.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.$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.$el.ready((function() { if (!$__0.container.settings.seekEnabled) { $__0.$seekBarContainer.addClass('seek-disabled'); } $__0.setVolumeLevel($__0.currentVolume); $__0.setSeekPercentage(0); $__0.bindKeyEvents(); })); this.parseColors(); return this; } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"../seek_time":45,"jquery":3,"mousetrap":5,"underscore":7}],"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":12}],"mediator":[function(require,module,exports){ module.exports=require('veeMMc'); },{}],"Pce0iO":[function(require,module,exports){ "use strict"; module.exports = require('./player_info'); },{"./player_info":44}],"player_info":[function(require,module,exports){ module.exports=require('Pce0iO'); },{}],44:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var PlayerInfo = function PlayerInfo() { this.options = {}; this.playbackPlugins = []; }; ($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"}],45:[function(require,module,exports){ "use strict"; module.exports = require('./seek_time'); },{"./seek_time":46}],46:[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 offsetX = event.pageX - $(event.target).offset().left; var pos = offsetX / $(event.target).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":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"jquery":3}],47:[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 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); options.height || (options.height = 360); options.width || (options.width = 640); }; 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":34,"./components/loader":35,"./components/mediator":"veeMMc","scrollmonitor":6,"underscore":7}],48:[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":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../components/browser":"195Wj5","../../components/mediator":"veeMMc","jquery":3,"underscore":7}],49:[function(require,module,exports){ "use strict"; module.exports = require('./flash'); },{"./flash":48}],50:[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 %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls=""><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"> </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", "volume"], default: ['seekbar'], right: ["fullscreen", "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 { '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.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.el.globoPlayerSetflushLiveURLCache(true); if (this._tmpVolume !== undefined) { this.volume(this._tmpVolume); delete this._tmpVolume; } 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(); } var previousDvrInUse = !!this.dvrInUse; this.dvrInUse = this.dvrEnabled && (duration - position >= 5); if (this.dvrInUse !== previousDvrInUse) { this.trigger('playback:dvr', this.dvrInUse); } 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", "IDLE"], this.currentState) && bufferLength !== this.lastBufferLength) { this.trigger('playback:bufferfull', this.name); 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) { if (this.el.globoPlayerVolume) { this.el.globoPlayerVolume(value); } else { this._tmpVolume = value; } }, pause: function() { this.el.globoPlayerPause(); if (this.playbackType === 'live' && this.dvrEnabled) { this.trigger('playback:dvr', 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' && duration - time < 5) { time = -1; } this.el.globoPlayerSeek(time); }, 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[0]); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath }))); }, updateSettings: function() { this.settings = _.extend({}, this.defaultSettings); if (this.playbackType === "vod" || this.dvrEnabled) { this.settings.left = ["playpause", "position", "duration"]; this.settings.default = ["seekbar"]; } else { this.settings.seekEnabled = false; } this.trigger('playback:settingsupdate', this.name); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); this.$el.append(style); this.el.id = this.cid; if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } return this; } }, {}, UIPlugin); HLS.canPlay = function(resource) { return !!resource.match(/^http(.*).m3u8/); }; module.exports = HLS; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr","../../components/browser":"195Wj5","../../components/mediator":"veeMMc","underscore":7}],51:[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":50}],52:[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); }, 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"}],53:[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":52}],54:[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", "volume"]; this.settings.right = ["fullscreen"]; } 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":13,"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5"}],55:[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":54}],56:[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"}],57:[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, '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); if (this.shouldRender()) { this.render(); } }; 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': '' }; }, 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":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT"}],58:[function(require,module,exports){ "use strict"; module.exports = require('./background_button'); },{"./background_button":57}],59:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":60}],60:[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}],61:[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":62}],62:[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":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr","../../components/mediator":"veeMMc","../../components/player_info":"Pce0iO","jquery":3,"underscore":7}],63:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":64}],64:[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":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr"}],65:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":66}],66:[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}],67:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":68}],68:[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":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr"}]},{},[2,47])
/*! * jQuery JavaScript Library v1.11.0 * 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-01-23T21:02Z */ (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 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", // 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.16 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-13 */ (function( window ) { var i, support, 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 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 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, 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 ) { 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 ) { 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"); // 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>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #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 ) { 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 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 ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : 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 ]; // 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 ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // 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+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && 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) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
'use strict'; var React = require('react/addons'); var ReactTransitionGroup = React.addons.TransitionGroup; var PostsStore = require( '../stores/PostsStore'); // MATERIAL UI INIT var mui = require( 'material-ui' ); var ThemeManager = new mui.Styles.ThemeManager(); let Colors = mui.Styles.Colors; var Editor = require( './Editor' ); var EditorList = require( './EditorList' ); // import Editor // CSS require('normalize.css'); require('../styles/main.css'); var SafepressCoreApp = React.createClass({ mixins: [ ], childContextTypes: { muiTheme: React.PropTypes.object }, componentWillMount() { ThemeManager.setPalette({ accent1Color: Colors.deepOrange500 }); }, getChildContext: function() { return { muiTheme: ThemeManager.getCurrentTheme() }; }, getInitialState: function() { return PostsStore.getState(); }, componentDidMount: function() { PostsStore.listen( this.onChange ); }, componentWillUnmount: function() { PostsStore.unlisten( this.onChange ); }, onChange(state) { console.log( 'STATE PASSED??', state ); this.setState(state); }, render: function() { return ( <div className="main"> <ReactTransitionGroup transitionName="fade"> <Editor allPosts={ this.state.posts }/> <EditorList list={ this.state.posts }/> </ReactTransitionGroup> </div> ); } }); module.exports = SafepressCoreApp;
'use strict'; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; exports.__esModule = true; exports['default'] = valueValidation; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibSinglePropFrom = require('react-prop-types/lib/singlePropFrom'); var _reactPropTypesLibSinglePropFrom2 = _interopRequireDefault(_reactPropTypesLibSinglePropFrom); function valueValidation(props, propName, componentName) { var error = _reactPropTypesLibSinglePropFrom2['default']('children', 'value')(props, propName, componentName); if (!error) { error = _react2['default'].PropTypes.node(props, propName, componentName); } return error; } module.exports = exports['default'];
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["eio"] = factory(); else root["eio"] = factory(); })(this, function() { 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'; module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(2); /** * Exports parser * * @api public * */ module.exports.parser = __webpack_require__(9); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * Module dependencies. */ var transports = __webpack_require__(3); var Emitter = __webpack_require__(19); var debug = __webpack_require__(23)('engine.io-client:socket'); var index = __webpack_require__(30); var parser = __webpack_require__(9); var parseuri = __webpack_require__(31); var parsejson = __webpack_require__(32); var parseqs = __webpack_require__(20); /** * Module exports. */ module.exports = Socket; /** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */ function Socket(uri, opts) { if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.hostname = uri.host; opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } else if (opts.host) { opts.hostname = parseuri(opts.host).host; } this.secure = null != opts.secure ? opts.secure : global.location && 'https:' === location.protocol; if (opts.hostname && !opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : this.secure ? 443 : 80); this.query = opts.query || {}; if ('string' === typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.transportOptions = opts.transportOptions || {}; this.readyState = ''; this.writeBuffer = []; this.prevBufferLen = 0; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; this.perMessageDeflate = false !== opts.perMessageDeflate ? opts.perMessageDeflate || {} : false; if (true === this.perMessageDeflate) this.perMessageDeflate = {}; if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { this.perMessageDeflate.threshold = 1024; } // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized; this.forceNode = !!opts.forceNode; // other options for Node.js client var freeGlobal = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) === 'object' && global; if (freeGlobal.global === freeGlobal) { if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { this.extraHeaders = opts.extraHeaders; } if (opts.localAddress) { this.localAddress = opts.localAddress; } } // set on handshake this.id = null; this.upgrades = null; this.pingInterval = null; this.pingTimeout = null; // set on heartbeat this.pingIntervalTimer = null; this.pingTimeoutTimer = null; this.open(); } Socket.priorWebsocketSuccess = false; /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Protocol version. * * @api public */ Socket.protocol = parser.protocol; // this is an int /** * Expose deps for legacy compatibility * and standalone browser access. */ Socket.Socket = Socket; Socket.Transport = __webpack_require__(8); Socket.transports = __webpack_require__(3); Socket.parser = __webpack_require__(9); /** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */ Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // per-transport options var options = this.transportOptions[name] || {}; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ query: query, socket: this, agent: options.agent || this.agent, hostname: options.hostname || this.hostname, port: options.port || this.port, secure: options.secure || this.secure, path: options.path || this.path, forceJSONP: options.forceJSONP || this.forceJSONP, jsonp: options.jsonp || this.jsonp, forceBase64: options.forceBase64 || this.forceBase64, enablesXDR: options.enablesXDR || this.enablesXDR, timestampRequests: options.timestampRequests || this.timestampRequests, timestampParam: options.timestampParam || this.timestampParam, policyPort: options.policyPort || this.policyPort, pfx: options.pfx || this.pfx, key: options.key || this.key, passphrase: options.passphrase || this.passphrase, cert: options.cert || this.cert, ca: options.ca || this.ca, ciphers: options.ciphers || this.ciphers, rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized, perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate, extraHeaders: options.extraHeaders || this.extraHeaders, forceNode: options.forceNode || this.forceNode, localAddress: options.localAddress || this.localAddress, requestTimeout: options.requestTimeout || this.requestTimeout, protocols: options.protocols || void 0 }); return transport; }; function clone(obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; } /** * Initializes transport to use and starts probe. * * @api private */ Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { transport = 'websocket'; } else if (0 === this.transports.length) { // Emit error on next tick so it can be listened to var self = this; setTimeout(function () { self.emit('error', 'No transports available'); }, 0); return; } else { transport = this.transports[0]; } this.readyState = 'opening'; // Retry with the next transport if the transport is disabled (jsonp: false) try { transport = this.createTransport(transport); } catch (e) { this.transports.shift(); this.open(); return; } transport.open(); this.setTransport(transport); }; /** * Sets the current transport. Disables the existing one (if any). * * @api private */ Socket.prototype.setTransport = function (transport) { debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport.on('drain', function () { self.onDrain(); }).on('packet', function (packet) { self.onPacket(packet); }).on('error', function (e) { self.onError(e); }).on('close', function () { self.onClose('transport close'); }); }; /** * Probes a transport. * * @param {String} transport name * @api private */ Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }); var failed = false; var self = this; Socket.priorWebsocketSuccess = false; function onTransportOpen() { if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' === msg.type && 'probe' === msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' === transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' === self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); } function freezeTransport() { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; } // Handle any error that happens while probing function onerror(err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } function onTransportClose() { onerror('transport closed'); } // When the socket is closed while we're probing function onclose() { onerror('socket closed'); } // When the socket is upgraded while we're probing function onupgrade(to) { if (transport && to.name !== transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } } // Remove all listeners on the transport and on self function cleanup() { transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); } transport.once('open', onTransportOpen); transport.once('error', onerror); transport.once('close', onTransportClose); this.once('close', onclose); this.once('upgrading', onupgrade); transport.open(); }; /** * Called when connection is deemed open. * * @api public */ Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; this.emit('open'); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' === this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } } }; /** * Handles a packet. * * @api private */ Socket.prototype.onPacket = function (packet) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); this.emit('pong'); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.onError(err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); } }; /** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */ Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); // In case open handler closes socket if ('closed' === this.readyState) return; this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat); }; /** * Resets ping timeout. * * @api private */ Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' === self.readyState) return; self.onClose('ping timeout'); }, timeout || self.pingInterval + self.pingTimeout); }; /** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */ Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval); }; /** * Sends a ping packet. * * @api private */ Socket.prototype.ping = function () { var self = this; this.sendPacket('ping', function () { self.emit('ping'); }); }; /** * Called on `drain` event * * @api private */ Socket.prototype.onDrain = function () { this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (0 === this.writeBuffer.length) { this.emit('drain'); } else { this.flush(); } }; /** * Flush write buffers. * * @api private */ Socket.prototype.flush = function () { if ('closed' !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); } }; /** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @param {Object} options. * @return {Socket} for chaining. * @api public */ Socket.prototype.write = Socket.prototype.send = function (msg, options, fn) { this.sendPacket('message', msg, options, fn); return this; }; /** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Object} options. * @param {Function} callback function. * @api private */ Socket.prototype.sendPacket = function (type, data, options, fn) { if ('function' === typeof data) { fn = data; data = undefined; } if ('function' === typeof options) { fn = options; options = null; } if ('closing' === this.readyState || 'closed' === this.readyState) { return; } options = options || {}; options.compress = false !== options.compress; var packet = { type: type, data: data, options: options }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); if (fn) this.once('flush', fn); this.flush(); }; /** * Closes the connection. * * @api private */ Socket.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.readyState = 'closing'; var self = this; if (this.writeBuffer.length) { this.once('drain', function () { if (this.upgrading) { waitForUpgrade(); } else { close(); } }); } else if (this.upgrading) { waitForUpgrade(); } else { close(); } } function close() { self.onClose('forced close'); debug('socket closing - telling transport to close'); self.transport.close(); } function cleanupAndClose() { self.removeListener('upgrade', cleanupAndClose); self.removeListener('upgradeError', cleanupAndClose); close(); } function waitForUpgrade() { // wait for upgrade to finish since we can't send packets while pausing a transport self.once('upgrade', cleanupAndClose); self.once('upgradeError', cleanupAndClose); } return this; }; /** * Called upon transport error * * @api private */ Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onClose('transport error', err); }; /** * Called upon transport close. * * @api private */ Socket.prototype.onClose = function (reason, desc) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // stop event from firing again for transport this.transport.removeAllListeners('close'); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); // clean buffers after, so users can still // grab the buffers on `close` event self.writeBuffer = []; self.prevBufferLen = 0; } }; /** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */ Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i < j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades; }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; /** * Module dependencies */ var XMLHttpRequest = __webpack_require__(4); var XHR = __webpack_require__(6); var JSONP = __webpack_require__(27); var websocket = __webpack_require__(28); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling(opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; // browser shim for xmlhttprequest module var hasCORS = __webpack_require__(5); module.exports = function (opts) { var xdomain = opts.xdomain; // scheme must be same when usign XDomainRequest // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx var xscheme = opts.xscheme; // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. // https://github.com/Automattic/engine.io-client/pull/217 var enablesXDR = opts.enablesXDR; // XMLHttpRequest can be disabled on IE try { if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { return new XMLHttpRequest(); } } catch (e) {} // Use XDomainRequest for IE8 if enablesXDR is true // because loading bar keeps flashing when using jsonp-polling // https://github.com/yujiosaka/socke.io-ie8-loading-example try { if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) { return new XDomainRequest(); } } catch (e) {} if (!xdomain) { try { return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP'); } catch (e) {} } }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 5 */ /***/ function(module, exports) { /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; /** * Module requirements. */ var XMLHttpRequest = __webpack_require__(4); var Polling = __webpack_require__(7); var Emitter = __webpack_require__(19); var inherit = __webpack_require__(21); var debug = __webpack_require__(23)('engine.io-client:polling-xhr'); /** * Module exports. */ module.exports = XHR; module.exports.Request = Request; /** * Empty function */ function empty() {} /** * XHR Polling constructor. * * @param {Object} opts * @api public */ function XHR(opts) { Polling.call(this, opts); this.requestTimeout = opts.requestTimeout; this.extraHeaders = opts.extraHeaders; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } this.xd = opts.hostname !== global.location.hostname || port !== opts.port; this.xs = opts.secure !== isSSL; } } /** * Inherits from Polling. */ inherit(XHR, Polling); /** * XHR supports binary */ XHR.prototype.supportsBinary = true; /** * Creates a request. * * @param {String} method * @api private */ XHR.prototype.request = function (opts) { opts = opts || {}; opts.uri = this.uri(); opts.xd = this.xd; opts.xs = this.xs; opts.agent = this.agent || false; opts.supportsBinary = this.supportsBinary; opts.enablesXDR = this.enablesXDR; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; opts.requestTimeout = this.requestTimeout; // other options for Node.js client opts.extraHeaders = this.extraHeaders; return new Request(opts); }; /** * Sends data. * * @param {String} data to send. * @param {Function} called upon flush. * @api private */ XHR.prototype.doWrite = function (data, fn) { var isBinary = typeof data !== 'string' && data !== undefined; var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); var self = this; req.on('success', fn); req.on('error', function (err) { self.onError('xhr post error', err); }); this.sendXhr = req; }; /** * Starts a poll cycle. * * @api private */ XHR.prototype.doPoll = function () { debug('xhr poll'); var req = this.request(); var self = this; req.on('data', function (data) { self.onData(data); }); req.on('error', function (err) { self.onError('xhr poll error', err); }); this.pollXhr = req; }; /** * Request constructor * * @param {Object} options * @api public */ function Request(opts) { this.method = opts.method || 'GET'; this.uri = opts.uri; this.xd = !!opts.xd; this.xs = !!opts.xs; this.async = false !== opts.async; this.data = undefined !== opts.data ? opts.data : null; this.agent = opts.agent; this.isBinary = opts.isBinary; this.supportsBinary = opts.supportsBinary; this.enablesXDR = opts.enablesXDR; this.requestTimeout = opts.requestTimeout; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.create(); } /** * Mix in `Emitter`. */ Emitter(Request.prototype); /** * Creates the XHR object and sends the request. * * @api private */ Request.prototype.create = function () { var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; var xhr = this.xhr = new XMLHttpRequest(opts); var self = this; try { debug('xhr open %s: %s', this.method, this.uri); xhr.open(this.method, this.uri, this.async); try { if (this.extraHeaders) { xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); for (var i in this.extraHeaders) { if (this.extraHeaders.hasOwnProperty(i)) { xhr.setRequestHeader(i, this.extraHeaders[i]); } } } } catch (e) {} if ('POST' === this.method) { try { if (this.isBinary) { xhr.setRequestHeader('Content-type', 'application/octet-stream'); } else { xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); } } catch (e) {} } try { xhr.setRequestHeader('Accept', '*/*'); } catch (e) {} // ie6 check if ('withCredentials' in xhr) { xhr.withCredentials = true; } if (this.requestTimeout) { xhr.timeout = this.requestTimeout; } if (this.hasXDR()) { xhr.onload = function () { self.onLoad(); }; xhr.onerror = function () { self.onError(xhr.responseText); }; } else { xhr.onreadystatechange = function () { if (xhr.readyState === 2) { var contentType; try { contentType = xhr.getResponseHeader('Content-Type'); } catch (e) {} if (contentType === 'application/octet-stream') { xhr.responseType = 'arraybuffer'; } } if (4 !== xhr.readyState) return; if (200 === xhr.status || 1223 === xhr.status) { self.onLoad(); } else { // make sure the `error` event handler that's user-set // does not throw in the same tick and gets caught here setTimeout(function () { self.onError(xhr.status); }, 0); } }; } debug('xhr data %s', this.data); xhr.send(this.data); } catch (e) { // Need to defer since .create() is called directly fhrom the constructor // and thus the 'error' event can only be only bound *after* this exception // occurs. Therefore, also, we cannot throw here at all. setTimeout(function () { self.onError(e); }, 0); return; } if (global.document) { this.index = Request.requestsCount++; Request.requests[this.index] = this; } }; /** * Called upon successful response. * * @api private */ Request.prototype.onSuccess = function () { this.emit('success'); this.cleanup(); }; /** * Called if we have data. * * @api private */ Request.prototype.onData = function (data) { this.emit('data', data); this.onSuccess(); }; /** * Called upon error. * * @api private */ Request.prototype.onError = function (err) { this.emit('error', err); this.cleanup(true); }; /** * Cleans up house. * * @api private */ Request.prototype.cleanup = function (fromError) { if ('undefined' === typeof this.xhr || null === this.xhr) { return; } // xmlhttprequest if (this.hasXDR()) { this.xhr.onload = this.xhr.onerror = empty; } else { this.xhr.onreadystatechange = empty; } if (fromError) { try { this.xhr.abort(); } catch (e) {} } if (global.document) { delete Request.requests[this.index]; } this.xhr = null; }; /** * Called upon load. * * @api private */ Request.prototype.onLoad = function () { var data; try { var contentType; try { contentType = this.xhr.getResponseHeader('Content-Type'); } catch (e) {} if (contentType === 'application/octet-stream') { data = this.xhr.response || this.xhr.responseText; } else { data = this.xhr.responseText; } } catch (e) { this.onError(e); } if (null != data) { this.onData(data); } }; /** * Check if it has XDomainRequest. * * @api private */ Request.prototype.hasXDR = function () { return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR; }; /** * Aborts the request. * * @api public */ Request.prototype.abort = function () { this.cleanup(); }; /** * Aborts pending requests when unloading the window. This is needed to prevent * memory leaks (e.g. when using IE) and to ensure that no spurious error is * emitted. */ Request.requestsCount = 0; Request.requests = {}; if (global.document) { if (global.attachEvent) { global.attachEvent('onunload', unloadHandler); } else if (global.addEventListener) { global.addEventListener('beforeunload', unloadHandler, false); } } function unloadHandler() { for (var i in Request.requests) { if (Request.requests.hasOwnProperty(i)) { Request.requests[i].abort(); } } } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Module dependencies. */ var Transport = __webpack_require__(8); var parseqs = __webpack_require__(20); var parser = __webpack_require__(9); var inherit = __webpack_require__(21); var yeast = __webpack_require__(22); var debug = __webpack_require__(23)('engine.io-client:polling'); /** * Module exports. */ module.exports = Polling; /** * Is XHR2 supported? */ var hasXHR2 = function () { var XMLHttpRequest = __webpack_require__(4); var xhr = new XMLHttpRequest({ xdomain: false }); return null != xhr.responseType; }(); /** * Polling interface. * * @param {Object} opts * @api private */ function Polling(opts) { var forceBase64 = opts && opts.forceBase64; if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(Polling, Transport); /** * Transport name. */ Polling.prototype.name = 'polling'; /** * Opens the socket (triggers polling). We write a PING message to determine * when the transport is open. * * @api private */ Polling.prototype.doOpen = function () { this.poll(); }; /** * Pauses polling. * * @param {Function} callback upon buffers are flushed and transport is paused * @api private */ Polling.prototype.pause = function (onPause) { var self = this; this.readyState = 'pausing'; function pause() { debug('paused'); self.readyState = 'paused'; onPause(); } if (this.polling || !this.writable) { var total = 0; if (this.polling) { debug('we are currently polling - waiting to pause'); total++; this.once('pollComplete', function () { debug('pre-pause polling complete'); --total || pause(); }); } if (!this.writable) { debug('we are currently writing - waiting to pause'); total++; this.once('drain', function () { debug('pre-pause writing complete'); --total || pause(); }); } } else { pause(); } }; /** * Starts polling cycle. * * @api public */ Polling.prototype.poll = function () { debug('polling'); this.polling = true; this.doPoll(); this.emit('poll'); }; /** * Overloads onData to detect payloads. * * @api private */ Polling.prototype.onData = function (data) { var self = this; debug('polling got data %s', data); var callback = function callback(packet, index, total) { // if its the first message we consider the transport open if ('opening' === self.readyState) { self.onOpen(); } // if its a close packet, we close the ongoing requests if ('close' === packet.type) { self.onClose(); return false; } // otherwise bypass onData and handle the message self.onPacket(packet); }; // decode payload parser.decodePayload(data, this.socket.binaryType, callback); // if an event did not trigger closing if ('closed' !== this.readyState) { // if we got data we're not polling this.polling = false; this.emit('pollComplete'); if ('open' === this.readyState) { this.poll(); } else { debug('ignoring poll - transport state "%s"', this.readyState); } } }; /** * For polling, send a close packet. * * @api private */ Polling.prototype.doClose = function () { var self = this; function close() { debug('writing close packet'); self.write([{ type: 'close' }]); } if ('open' === this.readyState) { debug('transport open - closing'); close(); } else { // in case we're trying to close while // handshaking is in progress (GH-164) debug('transport not open - deferring close'); this.once('open', close); } }; /** * Writes a packets payload. * * @param {Array} data packets * @param {Function} drain callback * @api private */ Polling.prototype.write = function (packets) { var self = this; this.writable = false; var callbackfn = function callbackfn() { self.writable = true; self.emit('drain'); }; parser.encodePayload(packets, this.supportsBinary, function (data) { self.doWrite(data, callbackfn); }); }; /** * Generates uri for connection. * * @api private */ Polling.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'https' : 'http'; var port = ''; // cache busting is forced if (false !== this.timestampRequests) { query[this.timestampParam] = yeast(); } if (!this.supportsBinary && !query.sid) { query.b64 = 1; } query = parseqs.encode(query); // avoid port if default for schema if (this.port && ('https' === schema && Number(this.port) !== 443 || 'http' === schema && Number(this.port) !== 80)) { port = ':' + this.port; } // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Module dependencies. */ var parser = __webpack_require__(9); var Emitter = __webpack_require__(19); /** * Module exports. */ module.exports = Transport; /** * Transport abstract constructor. * * @param {Object} options. * @api private */ function Transport(opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; this.forceNode = opts.forceNode; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.localAddress = opts.localAddress; } /** * Mix in `Emitter`. */ Emitter(Transport.prototype); /** * Emits an error. * * @param {String} str * @return {Transport} for chaining * @api public */ Transport.prototype.onError = function (msg, desc) { var err = new Error(msg); err.type = 'TransportError'; err.description = desc; this.emit('error', err); return this; }; /** * Opens the transport. * * @api public */ Transport.prototype.open = function () { if ('closed' === this.readyState || '' === this.readyState) { this.readyState = 'opening'; this.doOpen(); } return this; }; /** * Closes the transport. * * @api private */ Transport.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.doClose(); this.onClose(); } return this; }; /** * Sends multiple packets. * * @param {Array} packets * @api private */ Transport.prototype.send = function (packets) { if ('open' === this.readyState) { this.write(packets); } else { throw new Error('Transport not open'); } }; /** * Called upon open * * @api private */ Transport.prototype.onOpen = function () { this.readyState = 'open'; this.writable = true; this.emit('open'); }; /** * Called with data. * * @param {String} data * @api private */ Transport.prototype.onData = function (data) { var packet = parser.decodePacket(data, this.socket.binaryType); this.onPacket(packet); }; /** * Called with a decoded packet. */ Transport.prototype.onPacket = function (packet) { this.emit('packet', packet); }; /** * Called upon close. * * @api private */ Transport.prototype.onClose = function () { this.readyState = 'closed'; this.emit('close'); }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Module dependencies. */ var keys = __webpack_require__(10); var hasBinary = __webpack_require__(11); var sliceBuffer = __webpack_require__(13); var after = __webpack_require__(14); var utf8 = __webpack_require__(15); var base64encoder; if (global && global.ArrayBuffer) { base64encoder = __webpack_require__(17); } /** * Check if we are running an android browser. That requires us to use * ArrayBuffer with polling transports... * * http://ghinda.net/jpeg-blob-ajax-android/ */ var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); /** * Check if we are running in PhantomJS. * Uploading a Blob with PhantomJS does not work correctly, as reported here: * https://github.com/ariya/phantomjs/issues/11395 * @type boolean */ var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent); /** * When true, avoids using Blobs to encode payloads. * @type boolean */ var dontSendBlobs = isAndroid || isPhantomJS; /** * Current protocol version. */ exports.protocol = 3; /** * Packet types. */ var packets = exports.packets = { open: 0 // non-ws , close: 1 // non-ws , ping: 2 , pong: 3 , message: 4 , upgrade: 5 , noop: 6 }; var packetslist = keys(packets); /** * Premade error packet. */ var err = { type: 'error', data: 'parser error' }; /** * Create a blob api even for blob builder when vendor prefixes exist */ var Blob = __webpack_require__(18); /** * Encodes a packet. * * <packet type id> [ <data> ] * * Example: * * 5hello world * 3 * 4 * * Binary is encoded in an identical principle * * @api private */ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { if (typeof supportsBinary === 'function') { callback = supportsBinary; supportsBinary = false; } if (typeof utf8encode === 'function') { callback = utf8encode; utf8encode = null; } var data = (packet.data === undefined) ? undefined : packet.data.buffer || packet.data; if (global.ArrayBuffer && data instanceof ArrayBuffer) { return encodeArrayBuffer(packet, supportsBinary, callback); } else if (Blob && data instanceof global.Blob) { return encodeBlob(packet, supportsBinary, callback); } // might be an object with { base64: true, data: dataAsBase64String } if (data && data.base64) { return encodeBase64Object(packet, callback); } // Sending data as a utf-8 string var encoded = packets[packet.type]; // data fragment is optional if (undefined !== packet.data) { encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data); } return callback('' + encoded); }; function encodeBase64Object(packet, callback) { // packet data is an object { base64: true, data: dataAsBase64String } var message = 'b' + exports.packets[packet.type] + packet.data.data; return callback(message); } /** * Encode packet helpers for binary types */ function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); } function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var fr = new FileReader(); fr.onload = function() { packet.data = fr.result; exports.encodePacket(packet, supportsBinary, true, callback); }; return fr.readAsArrayBuffer(packet.data); } function encodeBlob(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } if (dontSendBlobs) { return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); } var length = new Uint8Array(1); length[0] = packets[packet.type]; var blob = new Blob([length.buffer, packet.data]); return callback(blob); } /** * Encodes a packet with binary data in a base64 string * * @param {Object} packet, has `type` and `data` * @return {String} base64 encoded message */ exports.encodeBase64Packet = function(packet, callback) { var message = 'b' + exports.packets[packet.type]; if (Blob && packet.data instanceof global.Blob) { var fr = new FileReader(); fr.onload = function() { var b64 = fr.result.split(',')[1]; callback(message + b64); }; return fr.readAsDataURL(packet.data); } var b64data; try { b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); } catch (e) { // iPhone Safari doesn't let you apply with typed arrays var typed = new Uint8Array(packet.data); var basic = new Array(typed.length); for (var i = 0; i < typed.length; i++) { basic[i] = typed[i]; } b64data = String.fromCharCode.apply(null, basic); } message += global.btoa(b64data); return callback(message); }; /** * Decodes a packet. Changes format to Blob if requested. * * @return {Object} with `type` and `data` (if any) * @api private */ exports.decodePacket = function (data, binaryType, utf8decode) { if (data === undefined) { return err; } // String data if (typeof data === 'string') { if (data.charAt(0) === 'b') { return exports.decodeBase64Packet(data.substr(1), binaryType); } if (utf8decode) { data = tryDecode(data); if (data === false) { return err; } } var type = data.charAt(0); if (Number(type) != type || !packetslist[type]) { return err; } if (data.length > 1) { return { type: packetslist[type], data: data.substring(1) }; } else { return { type: packetslist[type] }; } } var asArray = new Uint8Array(data); var type = asArray[0]; var rest = sliceBuffer(data, 1); if (Blob && binaryType === 'blob') { rest = new Blob([rest]); } return { type: packetslist[type], data: rest }; }; function tryDecode(data) { try { data = utf8.decode(data, { strict: false }); } catch (e) { return false; } return data; } /** * Decodes a packet encoded in a base64 string * * @param {String} base64 encoded message * @return {Object} with `type` and `data` (if any) */ exports.decodeBase64Packet = function(msg, binaryType) { var type = packetslist[msg.charAt(0)]; if (!base64encoder) { return { type: type, data: { base64: true, data: msg.substr(1) } }; } var data = base64encoder.decode(msg.substr(1)); if (binaryType === 'blob' && Blob) { data = new Blob([data]); } return { type: type, data: data }; }; /** * Encodes multiple messages (payload). * * <length>:data * * Example: * * 11:hello world2:hi * * If any contents are binary, they will be encoded as base64 strings. Base64 * encoded strings are marked with a b before the length specifier * * @param {Array} packets * @api private */ exports.encodePayload = function (packets, supportsBinary, callback) { if (typeof supportsBinary === 'function') { callback = supportsBinary; supportsBinary = null; } var isBinary = hasBinary(packets); if (supportsBinary && isBinary) { if (Blob && !dontSendBlobs) { return exports.encodePayloadAsBlob(packets, callback); } return exports.encodePayloadAsArrayBuffer(packets, callback); } if (!packets.length) { return callback('0:'); } function setLengthHeader(message) { return message.length + ':' + message; } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) { doneCallback(null, setLengthHeader(message)); }); } map(packets, encodeOne, function(err, results) { return callback(results.join('')); }); }; /** * Async array map using after */ function map(ary, each, done) { var result = new Array(ary.length); var next = after(ary.length, done); var eachWithIndex = function(i, el, cb) { each(el, function(error, msg) { result[i] = msg; cb(error, result); }); }; for (var i = 0; i < ary.length; i++) { eachWithIndex(i, ary[i], next); } } /* * Decodes data when a payload is maybe expected. Possible binary contents are * decoded from their base64 representation * * @param {String} data, callback method * @api public */ exports.decodePayload = function (data, binaryType, callback) { if (typeof data !== 'string') { return exports.decodePayloadAsBinary(data, binaryType, callback); } if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var packet; if (data === '') { // parser error - ignoring payload return callback(err, 0, 1); } var length = '', n, msg; for (var i = 0, l = data.length; i < l; i++) { var chr = data.charAt(i); if (chr !== ':') { length += chr; continue; } if (length === '' || (length != (n = Number(length)))) { // parser error - ignoring payload return callback(err, 0, 1); } msg = data.substr(i + 1, n); if (length != msg.length) { // parser error - ignoring payload return callback(err, 0, 1); } if (msg.length) { packet = exports.decodePacket(msg, binaryType, false); if (err.type === packet.type && err.data === packet.data) { // parser error in individual packet - ignoring payload return callback(err, 0, 1); } var ret = callback(packet, i + n, l); if (false === ret) return; } // advance cursor i += n; length = ''; } if (length !== '') { // parser error - ignoring payload return callback(err, 0, 1); } }; /** * Encodes multiple messages (payload) as binary. * * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number * 255><data> * * Example: * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers * * @param {Array} packets * @return {ArrayBuffer} encoded payload * @api private */ exports.encodePayloadAsArrayBuffer = function(packets, callback) { if (!packets.length) { return callback(new ArrayBuffer(0)); } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(data) { return doneCallback(null, data); }); } map(packets, encodeOne, function(err, encodedPackets) { var totalLength = encodedPackets.reduce(function(acc, p) { var len; if (typeof p === 'string'){ len = p.length; } else { len = p.byteLength; } return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 }, 0); var resultArray = new Uint8Array(totalLength); var bufferIndex = 0; encodedPackets.forEach(function(p) { var isString = typeof p === 'string'; var ab = p; if (isString) { var view = new Uint8Array(p.length); for (var i = 0; i < p.length; i++) { view[i] = p.charCodeAt(i); } ab = view.buffer; } if (isString) { // not true binary resultArray[bufferIndex++] = 0; } else { // true binary resultArray[bufferIndex++] = 1; } var lenStr = ab.byteLength.toString(); for (var i = 0; i < lenStr.length; i++) { resultArray[bufferIndex++] = parseInt(lenStr[i]); } resultArray[bufferIndex++] = 255; var view = new Uint8Array(ab); for (var i = 0; i < view.length; i++) { resultArray[bufferIndex++] = view[i]; } }); return callback(resultArray.buffer); }); }; /** * Encode as Blob */ exports.encodePayloadAsBlob = function(packets, callback) { function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(encoded) { var binaryIdentifier = new Uint8Array(1); binaryIdentifier[0] = 1; if (typeof encoded === 'string') { var view = new Uint8Array(encoded.length); for (var i = 0; i < encoded.length; i++) { view[i] = encoded.charCodeAt(i); } encoded = view.buffer; binaryIdentifier[0] = 0; } var len = (encoded instanceof ArrayBuffer) ? encoded.byteLength : encoded.size; var lenStr = len.toString(); var lengthAry = new Uint8Array(lenStr.length + 1); for (var i = 0; i < lenStr.length; i++) { lengthAry[i] = parseInt(lenStr[i]); } lengthAry[lenStr.length] = 255; if (Blob) { var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); doneCallback(null, blob); } }); } map(packets, encodeOne, function(err, results) { return callback(new Blob(results)); }); }; /* * Decodes data when a payload is maybe expected. Strings are decoded by * interpreting each byte as a key code for entries marked to start with 0. See * description of encodePayloadAsBinary * * @param {ArrayBuffer} data, callback method * @api public */ exports.decodePayloadAsBinary = function (data, binaryType, callback) { if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var bufferTail = data; var buffers = []; while (bufferTail.byteLength > 0) { var tailArray = new Uint8Array(bufferTail); var isString = tailArray[0] === 0; var msgLength = ''; for (var i = 1; ; i++) { if (tailArray[i] === 255) break; // 310 = char length of Number.MAX_VALUE if (msgLength.length > 310) { return callback(err, 0, 1); } msgLength += tailArray[i]; } bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); msgLength = parseInt(msgLength); var msg = sliceBuffer(bufferTail, 0, msgLength); if (isString) { try { msg = String.fromCharCode.apply(null, new Uint8Array(msg)); } catch (e) { // iPhone Safari doesn't let you apply to typed arrays var typed = new Uint8Array(msg); msg = ''; for (var i = 0; i < typed.length; i++) { msg += String.fromCharCode(typed[i]); } } } buffers.push(msg); bufferTail = sliceBuffer(bufferTail, msgLength); } var total = buffers.length; buffers.forEach(function(buffer, i) { callback(exports.decodePacket(buffer, binaryType, true), i, total); }); }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 10 */ /***/ function(module, exports) { /** * Gets the keys for an object. * * @return {Array} keys * @api private */ module.exports = Object.keys || function keys (obj){ var arr = []; var has = Object.prototype.hasOwnProperty; for (var i in obj) { if (has.call(obj, i)) { arr.push(i); } } return arr; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/* global Blob File */ /* * Module requirements. */ var isArray = __webpack_require__(12); var toString = Object.prototype.toString; var withNativeBlob = typeof global.Blob === 'function' || toString.call(global.Blob) === '[object BlobConstructor]'; var withNativeFile = typeof global.File === 'function' || toString.call(global.File) === '[object FileConstructor]'; /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Supports Buffer, ArrayBuffer, Blob and File. * * @param {Object} anything * @api public */ function hasBinary (obj) { if (!obj || typeof obj !== 'object') { return false; } if (isArray(obj)) { for (var i = 0, l = obj.length; i < l; i++) { if (hasBinary(obj[i])) { return true; } } return false; } if ((typeof global.Buffer === 'function' && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) || (typeof global.ArrayBuffer === 'function' && obj instanceof ArrayBuffer) || (withNativeBlob && obj instanceof Blob) || (withNativeFile && obj instanceof File) ) { return true; } // see: https://github.com/Automattic/has-binary/pull/4 if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) { return hasBinary(obj.toJSON(), true); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { return true; } } return false; } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 12 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }, /* 13 */ /***/ function(module, exports) { /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported * * @api public */ module.exports = function(arraybuffer, start, end) { var bytes = arraybuffer.byteLength; start = start || 0; end = end || bytes; if (arraybuffer.slice) { return arraybuffer.slice(start, end); } if (start < 0) { start += bytes; } if (end < 0) { end += bytes; } if (end > bytes) { end = bytes; } if (start >= bytes || start >= end || bytes === 0) { return new ArrayBuffer(0); } var abv = new Uint8Array(arraybuffer); var result = new Uint8Array(end - start); for (var i = start, ii = 0; i < end; i++, ii++) { result[ii] = abv[i]; } return result.buffer; }; /***/ }, /* 14 */ /***/ function(module, exports) { module.exports = after function after(count, callback, err_cb) { var bail = false err_cb = err_cb || noop proxy.count = count return (count === 0) ? callback() : proxy function proxy(err, result) { if (proxy.count <= 0) { throw new Error('after called too many times') } --proxy.count // after first error, rest are passed to err_cb if (err) { bail = true callback(err) // future error callbacks will go to error handler callback = err_cb } else if (proxy.count === 0 && !bail) { callback(null, result) } } } function noop() {} /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/utf8js v2.1.2 by @mathias */ ;(function(root) { // Detect free variables `exports` var freeExports = typeof exports == 'object' && exports; // Detect free variable `module` var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root` var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var stringFromCharCode = String.fromCharCode; // Taken from https://mths.be/punycode function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; var value; var extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } // Taken from https://mths.be/punycode function ucs2encode(array) { var length = array.length; var index = -1; var value; var output = ''; while (++index < length) { value = array[index]; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); } return output; } function checkScalarValue(codePoint, strict) { if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { if (strict) { throw Error( 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + ' is not a scalar value' ); } return false; } return true; } /*--------------------------------------------------------------------------*/ function createByte(codePoint, shift) { return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); } function encodeCodePoint(codePoint, strict) { if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence return stringFromCharCode(codePoint); } var symbol = ''; if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); } else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence if (!checkScalarValue(codePoint, strict)) { codePoint = 0xFFFD; } symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); symbol += createByte(codePoint, 6); } else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); symbol += createByte(codePoint, 12); symbol += createByte(codePoint, 6); } symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); return symbol; } function utf8encode(string, opts) { opts = opts || {}; var strict = false !== opts.strict; var codePoints = ucs2decode(string); var length = codePoints.length; var index = -1; var codePoint; var byteString = ''; while (++index < length) { codePoint = codePoints[index]; byteString += encodeCodePoint(codePoint, strict); } return byteString; } /*--------------------------------------------------------------------------*/ function readContinuationByte() { if (byteIndex >= byteCount) { throw Error('Invalid byte index'); } var continuationByte = byteArray[byteIndex] & 0xFF; byteIndex++; if ((continuationByte & 0xC0) == 0x80) { return continuationByte & 0x3F; } // If we end up here, it’s not a continuation byte throw Error('Invalid continuation byte'); } function decodeSymbol(strict) { var byte1; var byte2; var byte3; var byte4; var codePoint; if (byteIndex > byteCount) { throw Error('Invalid byte index'); } if (byteIndex == byteCount) { return false; } // Read first byte byte1 = byteArray[byteIndex] & 0xFF; byteIndex++; // 1-byte sequence (no continuation bytes) if ((byte1 & 0x80) == 0) { return byte1; } // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { byte2 = readContinuationByte(); codePoint = ((byte1 & 0x1F) << 6) | byte2; if (codePoint >= 0x80) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 3-byte sequence (may include unpaired surrogates) if ((byte1 & 0xF0) == 0xE0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; if (codePoint >= 0x0800) { return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD; } else { throw Error('Invalid continuation byte'); } } // 4-byte sequence if ((byte1 & 0xF8) == 0xF0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); byte4 = readContinuationByte(); codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { return codePoint; } } throw Error('Invalid UTF-8 detected'); } var byteArray; var byteCount; var byteIndex; function utf8decode(byteString, opts) { opts = opts || {}; var strict = false !== opts.strict; byteArray = ucs2decode(byteString); byteCount = byteArray.length; byteIndex = 0; var codePoints = []; var tmp; while ((tmp = decodeSymbol(strict)) !== false) { codePoints.push(tmp); } return ucs2encode(codePoints); } /*--------------------------------------------------------------------------*/ var utf8 = { 'version': '2.1.2', 'encode': utf8encode, 'decode': utf8decode }; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( true ) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return utf8; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = utf8; } else { // in Narwhal or RingoJS v0.7.0- var object = {}; var hasOwnProperty = object.hasOwnProperty; for (var key in utf8) { hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); } } } else { // in Rhino or a web browser root.utf8 = utf8; } }(this)); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)(module), (function() { return this; }()))) /***/ }, /* 16 */ /***/ 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; } /***/ }, /* 17 */ /***/ function(module, exports) { /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function(){ "use strict"; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Use a lookup table to find the index. var lookup = new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } exports.encode = function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; for (i = 0; i < len; i+=3) { base64 += chars[bytes[i] >> 2]; base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64 += chars[bytes[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }; exports.decode = function(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { encoded1 = lookup[base64.charCodeAt(i)]; encoded2 = lookup[base64.charCodeAt(i+1)]; encoded3 = lookup[base64.charCodeAt(i+2)]; encoded4 = lookup[base64.charCodeAt(i+3)]; bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; }; })(); /***/ }, /* 18 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** * Create a blob builder even when vendor prefixes exist */ var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder; /** * Check if Blob constructor is supported */ var blobSupported = (function() { try { var a = new Blob(['hi']); return a.size === 2; } catch(e) { return false; } })(); /** * Check if Blob constructor supports ArrayBufferViews * Fails in Safari 6, so we need to map to ArrayBuffers there. */ var blobSupportsArrayBufferView = blobSupported && (function() { try { var b = new Blob([new Uint8Array([1,2])]); return b.size === 2; } catch(e) { return false; } })(); /** * Check if BlobBuilder is supported */ var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob; /** * Helper function that maps ArrayBufferViews to ArrayBuffers * Used by BlobBuilder constructor and old browsers that didn't * support it in the Blob constructor. */ function mapArrayBufferViews(ary) { for (var i = 0; i < ary.length; i++) { var chunk = ary[i]; if (chunk.buffer instanceof ArrayBuffer) { var buf = chunk.buffer; // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { var copy = new Uint8Array(chunk.byteLength); copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); buf = copy.buffer; } ary[i] = buf; } } } function BlobBuilderConstructor(ary, options) { options = options || {}; var bb = new BlobBuilder(); mapArrayBufferViews(ary); for (var i = 0; i < ary.length; i++) { bb.append(ary[i]); } return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); }; function BlobConstructor(ary, options) { mapArrayBufferViews(ary); return new Blob(ary, options || {}); }; module.exports = (function() { if (blobSupported) { return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; } else if (blobBuilderSupported) { return BlobBuilderConstructor; } else { return undefined; } })(); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /** * Expose `Emitter`. */ if (true) { 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){ function on() { this.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; }; /***/ }, /* 20 */ /***/ function(module, exports) { /** * Compiles a querystring * Returns string representation of the object * * @param {Object} * @api private */ exports.encode = function (obj) { var str = ''; for (var i in obj) { if (obj.hasOwnProperty(i)) { if (str.length) str += '&'; str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); } } return str; }; /** * Parses a simple querystring into an object * * @param {String} qs * @api private */ exports.decode = function(qs){ var qry = {}; var pairs = qs.split('&'); for (var i = 0, l = pairs.length; i < l; i++) { var pair = pairs[i].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; }; /***/ }, /* 21 */ /***/ function(module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; /***/ }, /* 22 */ /***/ function(module, exports) { 'use strict'; var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') , length = 64 , map = {} , seed = 0 , i = 0 , prev; /** * Return a string representing the specified number. * * @param {Number} num The number to convert. * @returns {String} The string representation of the number. * @api public */ function encode(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; } /** * Return the integer value specified by the given string. * * @param {String} str The string to convert. * @returns {Number} The integer value represented by the string. * @api public */ function decode(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; } /** * Yeast: A tiny growing id generator. * * @returns {String} A unique id. * @api public */ function yeast() { var now = encode(+new Date()); if (now !== prev) return seed = 0, prev = now; return now +'.'+ encode(seed++); } // // Map each character to its index. // for (; i < length; i++) map[alphabet[i]] = i; // // Expose the `yeast`, `encode` and `decode` functions. // yeast.encode = encode; yeast.decode = decode; module.exports = yeast; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __webpack_require__(25); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24))) /***/ }, /* 24 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(26); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }, /* 26 */ /***/ function(module, exports) { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; /** * Module requirements. */ var Polling = __webpack_require__(7); var inherit = __webpack_require__(21); /** * Module exports. */ module.exports = JSONPPolling; /** * Cached regular expressions. */ var rNewline = /\n/g; var rEscapedNewline = /\\n/g; /** * Global JSONP callbacks. */ var callbacks; /** * Noop. */ function empty() {} /** * JSONP Polling constructor. * * @param {Object} opts. * @api public */ function JSONPPolling(opts) { Polling.call(this, opts); this.query = this.query || {}; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; // prevent spurious errors from being emitted when the window is unloaded if (global.document && global.addEventListener) { global.addEventListener('beforeunload', function () { if (self.script) self.script.onerror = empty; }, false); } } /** * Inherits from Polling. */ inherit(JSONPPolling, Polling); /* * JSONP only supports binary as base64 encoded strings */ JSONPPolling.prototype.supportsBinary = false; /** * Closes the socket. * * @api private */ JSONPPolling.prototype.doClose = function () { if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } if (this.form) { this.form.parentNode.removeChild(this.form); this.form = null; this.iframe = null; } Polling.prototype.doClose.call(this); }; /** * Starts a poll cycle. * * @api private */ JSONPPolling.prototype.doPoll = function () { var self = this; var script = document.createElement('script'); if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } script.async = true; script.src = this.uri(); script.onerror = function (e) { self.onError('jsonp poll error', e); }; var insertAt = document.getElementsByTagName('script')[0]; if (insertAt) { insertAt.parentNode.insertBefore(script, insertAt); } else { (document.head || document.body).appendChild(script); } this.script = script; var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); if (isUAgecko) { setTimeout(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); document.body.removeChild(iframe); }, 100); } }; /** * Writes with a hidden iframe. * * @param {String} data to send * @param {Function} called upon flush. * @api private */ JSONPPolling.prototype.doWrite = function (data, fn) { var self = this; if (!this.form) { var form = document.createElement('form'); var area = document.createElement('textarea'); var id = this.iframeId = 'eio_iframe_' + this.index; var iframe; form.className = 'socketio'; form.style.position = 'absolute'; form.style.top = '-1000px'; form.style.left = '-1000px'; form.target = id; form.method = 'POST'; form.setAttribute('accept-charset', 'utf-8'); area.name = 'd'; form.appendChild(area); document.body.appendChild(form); this.form = form; this.area = area; } this.form.action = this.uri(); function complete() { initIframe(); fn(); } function initIframe() { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '<iframe src="javascript:0" name="' + self.iframeId + '">'; iframe = document.createElement(html); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; iframe.src = 'javascript:0'; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; } initIframe(); // escape \n to prevent it from being converted into \r\n by some UAs // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side data = data.replace(rEscapedNewline, '\\\n'); this.area.value = data.replace(rNewline, '\\n'); try { this.form.submit(); } catch (e) {} if (this.iframe.attachEvent) { this.iframe.onreadystatechange = function () { if (self.iframe.readyState === 'complete') { complete(); } }; } else { this.iframe.onload = complete; } }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; /** * Module dependencies. */ var Transport = __webpack_require__(8); var parser = __webpack_require__(9); var parseqs = __webpack_require__(20); var inherit = __webpack_require__(21); var yeast = __webpack_require__(22); var debug = __webpack_require__(23)('engine.io-client:websocket'); var BrowserWebSocket = global.WebSocket || global.MozWebSocket; var NodeWebSocket; if (typeof window === 'undefined') { try { NodeWebSocket = __webpack_require__(29); } catch (e) {} } /** * Get either the `WebSocket` or `MozWebSocket` globals * in the browser or try to resolve WebSocket-compatible * interface exposed by `ws` for Node-like environment. */ var WebSocket = BrowserWebSocket; if (!WebSocket && typeof window === 'undefined') { WebSocket = NodeWebSocket; } /** * Module exports. */ module.exports = WS; /** * WebSocket transport constructor. * * @api {Object} connection options * @api public */ function WS(opts) { var forceBase64 = opts && opts.forceBase64; if (forceBase64) { this.supportsBinary = false; } this.perMessageDeflate = opts.perMessageDeflate; this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode; this.protocols = opts.protocols; if (!this.usingBrowserWebSocket) { WebSocket = NodeWebSocket; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(WS, Transport); /** * Transport name. * * @api public */ WS.prototype.name = 'websocket'; /* * WebSockets support binary */ WS.prototype.supportsBinary = true; /** * Opens socket. * * @api private */ WS.prototype.doOpen = function () { if (!this.check()) { // let probe timeout return; } var uri = this.uri(); var protocols = this.protocols; var opts = { agent: this.agent, perMessageDeflate: this.perMessageDeflate }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; if (this.extraHeaders) { opts.headers = this.extraHeaders; } if (this.localAddress) { opts.localAddress = this.localAddress; } try { this.ws = this.usingBrowserWebSocket ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts); } catch (err) { return this.emit('error', err); } if (this.ws.binaryType === undefined) { this.supportsBinary = false; } if (this.ws.supports && this.ws.supports.binary) { this.supportsBinary = true; this.ws.binaryType = 'nodebuffer'; } else { this.ws.binaryType = 'arraybuffer'; } this.addEventListeners(); }; /** * Adds event listeners to the socket * * @api private */ WS.prototype.addEventListeners = function () { var self = this; this.ws.onopen = function () { self.onOpen(); }; this.ws.onclose = function () { self.onClose(); }; this.ws.onmessage = function (ev) { self.onData(ev.data); }; this.ws.onerror = function (e) { self.onError('websocket error', e); }; }; /** * Writes data to socket. * * @param {Array} array of packets. * @api private */ WS.prototype.write = function (packets) { var self = this; this.writable = false; // encodePacket efficient as it uses WS framing // no need for encodePayload var total = packets.length; for (var i = 0, l = total; i < l; i++) { (function (packet) { parser.encodePacket(packet, self.supportsBinary, function (data) { if (!self.usingBrowserWebSocket) { // always create a new object (GH-437) var opts = {}; if (packet.options) { opts.compress = packet.options.compress; } if (self.perMessageDeflate) { var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length; if (len < self.perMessageDeflate.threshold) { opts.compress = false; } } } // Sometimes the websocket has already been closed but the browser didn't // have a chance of informing us about it yet, in that case send will // throw an error try { if (self.usingBrowserWebSocket) { // TypeError is thrown when passing the second argument on Safari self.ws.send(data); } else { self.ws.send(data, opts); } } catch (e) { debug('websocket closed before onclose event'); } --total || done(); }); })(packets[i]); } function done() { self.emit('flush'); // fake drain // defer to next tick to allow Socket to clear writeBuffer setTimeout(function () { self.writable = true; self.emit('drain'); }, 0); } }; /** * Called upon close * * @api private */ WS.prototype.onClose = function () { Transport.prototype.onClose.call(this); }; /** * Closes socket. * * @api private */ WS.prototype.doClose = function () { if (typeof this.ws !== 'undefined') { this.ws.close(); } }; /** * Generates uri for connection. * * @api private */ WS.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'wss' : 'ws'; var port = ''; // avoid port if default for schema if (this.port && ('wss' === schema && Number(this.port) !== 443 || 'ws' === schema && Number(this.port) !== 80)) { port = ':' + this.port; } // append timestamp to URI if (this.timestampRequests) { query[this.timestampParam] = yeast(); } // communicate binary support capabilities if (!this.supportsBinary) { query.b64 = 1; } query = parseqs.encode(query); // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; /** * Feature detection for WebSocket. * * @return {Boolean} whether this transport is available. * @api public */ WS.prototype.check = function () { return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 29 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, /* 30 */ /***/ function(module, exports) { var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; /***/ }, /* 31 */ /***/ function(module, exports) { /** * Parses an URI * * @author Steven Levithan <stevenlevithan.com> (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var src = str, b = str.indexOf('['), e = str.indexOf(']'); if (b != -1 && e != -1) { str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); } var m = re.exec(str || ''), uri = {}, i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } if (b != -1 && e != -1) { uri.source = src; uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); uri.ipv6uri = true; } return uri; }; /***/ }, /* 32 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 * @api private */ var rvalidchars = /^[\],:{}\s]*$/; var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; var rtrimLeft = /^\s+/; var rtrimRight = /\s+$/; module.exports = function parsejson(data) { if ('string' != typeof data || !data) { return null; } data = data.replace(rtrimLeft, '').replace(rtrimRight, ''); // Attempt to parse using the native JSON parser first if (global.JSON && JSON.parse) { return JSON.parse(data); } if (rvalidchars.test(data.replace(rvalidescape, '@') .replace(rvalidtokens, ']') .replace(rvalidbraces, ''))) { return (new Function('return ' + data))(); } }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ } /******/ ]) }); ;
/** * Core.js 0.9.6 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(undefined){ 'use strict'; var __e = null, __g = null; /******/ (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__(4); __webpack_require__(2); __webpack_require__(5); __webpack_require__(3); __webpack_require__(6); __webpack_require__(10); __webpack_require__(9); __webpack_require__(8); __webpack_require__(7); __webpack_require__(11); __webpack_require__(12); __webpack_require__(13); __webpack_require__(14); __webpack_require__(15); __webpack_require__(16); __webpack_require__(18); __webpack_require__(17); __webpack_require__(19); __webpack_require__(20); __webpack_require__(21); __webpack_require__(22); __webpack_require__(23); __webpack_require__(24); __webpack_require__(25); __webpack_require__(26); __webpack_require__(27); __webpack_require__(38); __webpack_require__(31); __webpack_require__(28); __webpack_require__(29); __webpack_require__(30); __webpack_require__(32); __webpack_require__(33); __webpack_require__(34); __webpack_require__(35); __webpack_require__(36); __webpack_require__(37); __webpack_require__(39); __webpack_require__(40); __webpack_require__(41); __webpack_require__(42); __webpack_require__(43); __webpack_require__(44); __webpack_require__(45); __webpack_require__(46); __webpack_require__(47); __webpack_require__(48); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , cel = __webpack_require__(53) , cof = __webpack_require__(54) , $def = __webpack_require__(49) , invoke = __webpack_require__(58) , arrayMethod = __webpack_require__(55) , IE_PROTO = __webpack_require__(56).safe('__proto__') , assert = __webpack_require__(57) , assertObject = assert.obj , ObjectProto = Object.prototype , A = [] , slice = A.slice , indexOf = A.indexOf , classof = cof.classof , has = $.has , defineProperty = $.setDesc , getOwnDescriptor = $.getDesc , defineProperties = $.setDescs , isFunction = $.isFunction , toObject = $.toObject , toLength = $.toLength , IE8_DOM_DEFINE = false , $indexOf = __webpack_require__(59)(false) , $forEach = arrayMethod(0) , $map = arrayMethod(1) , $filter = arrayMethod(2) , $some = arrayMethod(3) , $every = arrayMethod(4); if(!$.DESC){ try { IE8_DOM_DEFINE = defineProperty(cel('div'), 'x', {get: function(){ return 8; }} ).x == 8; } catch(e){ /* empty */ } $.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)assertObject(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 $.desc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]); }; $.setDescs = defineProperties = function(O, Properties){ assertObject(O); var keys = $.getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)$.setDesc(O, P = keys[i++], Properties[P]); return O; }; } $def($def.S + $def.F * !$.DESC, '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(); }; function createGetKeys(names, length){ return function(object){ var O = toObject(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++])){ ~indexOf.call(result, key) || result.push(key); } return result; }; } function isPrimitive(it){ return !$.isObject(it); } function Empty(){} $def($def.S, 'Object', { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: $.getProto = $.getProto || function(O){ O = Object(assert.def(O)); if(has(O, IE_PROTO))return O[IE_PROTO]; if(isFunction(O.constructor) && 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 = assertObject(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), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: $.it, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: $.it, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: $.it, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: $.isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $def($def.P, 'Function', { bind: function(that /*, args... */){ var fn = assert.fn(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return invoke(fn, args, this instanceof bound ? $.create(fn.prototype) : that); } if(fn.prototype)bound.prototype = fn.prototype; return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply($.ES5Object(this), arguments); }; } if(!(0 in Object('z') && 'z'[0] == 'z')){ $.ES5Object = function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; } $def($def.P + $def.F * ($.ES5Object != Object), 'Array', { slice: arrayMethodFix(slice), join: arrayMethodFix(A.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $def($def.S, 'Array', { isArray: function(arg){ return cof(arg) == 'Array'; } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assert.fn(callbackfn); var O = toObject(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; assert(isRight ? index >= 0 : length > index, '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; }; } $def($def.P, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: $.each = $.each || function forEach(callbackfn/*, that = undefined */){ return $forEach(this, callbackfn, arguments[1]); }, // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: function map(callbackfn/*, that = undefined */){ return $map(this, callbackfn, arguments[1]); }, // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: function filter(callbackfn/*, that = undefined */){ return $filter(this, callbackfn, arguments[1]); }, // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: function some(callbackfn/*, that = undefined */){ return $some(this, callbackfn, arguments[1]); }, // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: function every(callbackfn/*, that = undefined */){ return $every(this, callbackfn, arguments[1]); }, // 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: indexOf = indexOf || function indexOf(el /*, fromIndex = 0 */){ return $indexOf(this, el, arguments[1]); }, // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toObject(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; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $def($def.P, 'String', {trim: __webpack_require__(62)(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $def($def.S, 'Date', {now: function(){ return +new Date; }}); function lz(num){ return num > 9 ? num : '0' + num; } // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() // PhantomJS and old webkit had a broken Date implementation. var date = new Date(-5e13 - 1) , brokenDate = !(date.toISOString && date.toISOString() == '0385-07-25T07:06:39.999Z' && __webpack_require__(60)(function(){ new Date(NaN).toISOString(); })); $def($def.P + $def.F * brokenDate, 'Date', {toISOString: function(){ 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'; }}); if(classof(function(){ return arguments; }()) == 'Object')cof.classof = function(it){ var tag = classof(it); return tag == 'Object' && isFunction(it.callee) ? 'Arguments' : tag; }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $def = __webpack_require__(49); $def($def.S, 'Object', {assign: __webpack_require__(50)}); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $def = __webpack_require__(49); $def($def.S, 'Object', {setPrototypeOf: __webpack_require__(51).set}); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var $ = __webpack_require__(52) , setTag = __webpack_require__(54).set , uid = __webpack_require__(56) , $def = __webpack_require__(49) , keyOf = __webpack_require__(61) , enumKeys = __webpack_require__(63) , assertObject = __webpack_require__(57).obj , has = $.has , $create = $.create , getDesc = $.getDesc , setDesc = $.setDesc , desc = $.desc , getNames = $.getNames , toObject = $.toObject , $Symbol = $.g.Symbol , setter = false , TAG = uid('tag') , HIDDEN = uid('hidden') , SymbolRegistry = {} , AllSymbols = {} , useNative = $.isFunction($Symbol); function wrap(tag){ var sym = AllSymbols[tag] = $.set($create($Symbol.prototype), TAG, tag); $.DESC && setter && setDesc(Object.prototype, tag, { configurable: true, set: function(value){ if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setDesc(this, tag, desc(1, value)); } }); return sym; } function defineProperty(it, key, D){ if(D && has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))setDesc(it, HIDDEN, desc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D.enumerable = false; } } return setDesc(it, key, D); } function defineProperties(it, P){ assertObject(it); var keys = enumKeys(P = toObject(P)) , i = 0 , l = keys.length , key; while(l > i)defineProperty(it, key = keys[i++], P[key]); return it; } function create(it, P){ return P === undefined ? $create(it) : defineProperties($create(it), P); } function getOwnPropertyDescriptor(it, key){ var D = getDesc(it = toObject(it), key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; } function getOwnPropertyNames(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); return result; } function getOwnPropertySymbols(it){ var names = getNames(toObject(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(!useNative){ $Symbol = function Symbol(description){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor'); return wrap(uid(description)); }; $.hide($Symbol.prototype, 'toString', function(){ return this[TAG]; }); $.create = create; $.setDesc = defineProperty; $.getDesc = getOwnPropertyDescriptor; $.setDescs = defineProperties; $.getNames = getOwnPropertyNames; $.getSymbols = getOwnPropertySymbols; } 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 = __webpack_require__(64)(it); symbolStatics[it] = useNative ? sym : wrap(sym); } ); setter = true; $def($def.G + $def.W, {Symbol: $Symbol}); $def($def.S, 'Symbol', symbolStatics); $def($def.S + $def.F * !useNative, '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 }); // 19.4.3.5 Symbol.prototype[@@toStringTag] setTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setTag($.g.JSON, 'JSON', true); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.10 Object.is(value1, value2) var $def = __webpack_require__(49); $def($def.S, 'Object', { is: function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 19.1.3.6 Object.prototype.toString() var $ = __webpack_require__(52) , cof = __webpack_require__(54) , tmp = {}; tmp[__webpack_require__(64)('toStringTag')] = 'z'; if($.FW && cof(tmp) != 'z')$.hide(Object.prototype, 'toString', function toString(){ return '[object ' + cof.classof(this) + ']'; }); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , isObject = $.isObject , isFunction = $.isFunction , NUMBER = 'Number' , $Number = $.g[NUMBER] , Base = $Number , proto = $Number.prototype; function toPrimitive(it){ var fn, val; if(isFunction(fn = it.valueOf) && !isObject(val = fn.call(it)))return val; if(isFunction(fn = it.toString) && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to number"); } function toNumber(it){ if(isObject(it))it = toPrimitive(it); if(typeof it == 'string' && it.length > 2 && it.charCodeAt(0) == 48){ var binary = false; switch(it.charCodeAt(1)){ case 66 : case 98 : binary = true; case 79 : case 111 : return parseInt(it.slice(2), binary ? 2 : 8); } } return +it; } if($.FW && !($Number('0o1') && $Number('0b1'))){ $Number = function Number(it){ return this instanceof $Number ? new Base(toNumber(it)) : toNumber(it); }; $.each.call($.DESC ? $.getNames(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(','), function(key){ if($.has(Base, key) && !$.has($Number, key)){ $.setDesc($Number, key, $.getDesc(Base, key)); } } ); $Number.prototype = proto; proto.constructor = $Number; $.hide($.g, NUMBER, $Number); } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , HAS_INSTANCE = __webpack_require__(64)('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(!$.isFunction(this) || !$.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; }}); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , NAME = 'name' , setDesc = $.setDesc , FunctionProto = Function.prototype; // 19.2.4.2 name NAME in FunctionProto || $.FW && $.DESC && setDesc(FunctionProto, NAME, { configurable: true, get: function(){ var match = String(this).match(/^\s*function ([^ (]*)/) , name = match ? match[1] : ''; $.has(this, NAME) || setDesc(this, NAME, $.desc(5, name)); return name; }, set: function(value){ $.has(this, NAME) || setDesc(this, NAME, $.desc(0, value)); } }); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , $def = __webpack_require__(49) , isObject = $.isObject , toObject = $.toObject; function wrapObjectMethod(METHOD, MODE){ var fn = ($.core.Object || {})[METHOD] || Object[METHOD] , f = 0 , o = {}; o[METHOD] = MODE == 1 ? function(it){ return isObject(it) ? fn(it) : it; } : MODE == 2 ? function(it){ return isObject(it) ? fn(it) : true; } : MODE == 3 ? function(it){ return isObject(it) ? fn(it) : false; } : MODE == 4 ? function getOwnPropertyDescriptor(it, key){ return fn(toObject(it), key); } : MODE == 5 ? function getPrototypeOf(it){ return fn(Object($.assertDefined(it))); } : function(it){ return fn(toObject(it)); }; try { fn('z'); } catch(e){ f = 1; } $def($def.S + $def.F * f, 'Object', o); } wrapObjectMethod('freeze', 1); wrapObjectMethod('seal', 1); wrapObjectMethod('preventExtensions', 1); wrapObjectMethod('isFrozen', 2); wrapObjectMethod('isSealed', 2); wrapObjectMethod('isExtensible', 3); wrapObjectMethod('getOwnPropertyDescriptor', 4); wrapObjectMethod('getPrototypeOf', 5); wrapObjectMethod('keys'); wrapObjectMethod('getOwnPropertyNames'); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , $def = __webpack_require__(49) , abs = Math.abs , floor = Math.floor , _isFinite = $.g.isFinite , MAX_SAFE_INTEGER = 0x1fffffffffffff; // pow(2, 53) - 1 == 9007199254740991; function isInteger(it){ return !$.isObject(it) && _isFinite(it) && floor(it) === it; } $def($def.S, 'Number', { // 20.1.2.1 Number.EPSILON EPSILON: Math.pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: function isNaN(number){ return number != number; }, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var Infinity = 1 / 0 , $def = __webpack_require__(49) , E = Math.E , pow = Math.pow , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , ceil = Math.ceil , floor = Math.floor , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); function roundTiesToEven(n){ return n + 1 / EPSILON - 1 / EPSILON; } // 20.2.2.28 Math.sign(x) function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; } // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $def($def.S, 'Math', { // 20.2.2.3 Math.acosh(x) acosh: function acosh(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function atanh(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function cbrt(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function clz32(x){ return (x >>>= 0) ? 31 - floor(log(x + 0.5) * Math.LOG2E) : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) fround: function fround(x){ var $abs = 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; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , len1 = arguments.length , len2 = len1 , args = Array(len1) , larg = -Infinity , arg; while(len1--){ arg = args[len1] = +arguments[len1]; if(arg == Infinity || arg == -Infinity)return Infinity; if(arg > larg)larg = arg; } larg = arg || 1; while(len2--)sum += pow(args[len2] / larg, 2); return larg * sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) 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); }, // 20.2.2.20 Math.log1p(x) log1p: function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function log10(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function log2(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function sinh(x){ return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) 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)); }, // 20.2.2.34 Math.trunc(x) trunc: function trunc(it){ return (it > 0 ? floor : ceil)(it); } }); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(49) , toIndex = __webpack_require__(52).toIndex , fromCharCode = String.fromCharCode , $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem $def($def.S + $def.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 = [] , len = arguments.length , i = 0 , code; while(len > 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(''); } }); /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , $def = __webpack_require__(49); $def($def.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = $.toObject(callSite.raw) , len = $.toLength(tpl.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var set = __webpack_require__(52).set , $at = __webpack_require__(65)(true) , ITER = __webpack_require__(56).safe('iter') , $iter = __webpack_require__(66) , step = $iter.step; // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(67)(String, 'String', function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return step(1); point = $at(O, index); iter.i += point.length; return step(0, point); }); /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $def = __webpack_require__(49) , $at = __webpack_require__(65)(false); $def($def.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos){ return $at(this, pos); } }); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , cof = __webpack_require__(54) , $def = __webpack_require__(49); $def($def.P, 'String', { // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function includes(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); return !!~String($.assertDefined(this)).indexOf(searchString, arguments[1]); } }); /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , cof = __webpack_require__(54) , $def = __webpack_require__(49) , toLength = $.toLength; // should throw error on regex $def($def.P + $def.F * !__webpack_require__(60)(function(){ 'q'.endsWith(/./); }), 'String', { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function endsWith(searchString /*, endPosition = @length */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; } }); /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(49); $def($def.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: __webpack_require__(68) }); /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , cof = __webpack_require__(54) , $def = __webpack_require__(49); // should throw error on regex $def($def.P + $def.F * !__webpack_require__(60)(function(){ 'q'.startsWith(/./); }), 'String', { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function startsWith(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , index = $.toLength(Math.min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , ctx = __webpack_require__(69) , $def = __webpack_require__(49) , $iter = __webpack_require__(66) , call = __webpack_require__(70); $def($def.S + $def.F * !__webpack_require__(71)(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 = Object($.assertDefined(arrayLike)) , mapfn = arguments[1] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, arguments[2], 2) : undefined , index = 0 , length, result, step, iterator; if($iter.is(O)){ iterator = $iter.get(O); // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array); for(; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, f, [step.value, index], true) : step.value; } } else { // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array)(length = $.toLength(O.length)); for(; length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } } result.length = index; return result; } }); /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(49); $def($def.S, 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , length = arguments.length // strange IE quirks mode bug -> use typeof instead of isFunction , result = new (typeof this == 'function' ? this : Array)(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , setUnscope = __webpack_require__(72) , ITER = __webpack_require__(56).safe('iter') , $iter = __webpack_require__(66) , step = $iter.step , Iterators = $iter.Iterators; // 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]() __webpack_require__(67)(Array, 'Array', function(iterated, kind){ $.set(this, ITER, {o: $.toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length){ iter.o = 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; setUnscope('keys'); setUnscope('values'); setUnscope('entries'); /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(73)(Array); /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , $def = __webpack_require__(49) , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function copyWithin(target/* = 0 */, start /* = 0, end = @length */){ var O = Object($.assertDefined(this)) , len = $.toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = Math.min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; } }); __webpack_require__(72)('copyWithin'); /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , $def = __webpack_require__(49) , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function fill(value /*, start = 0, end = @length */){ var O = Object($.assertDefined(this)) , length = $.toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; } }); __webpack_require__(72)('fill'); /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var KEY = 'find' , $def = __webpack_require__(49) , forced = true , $find = __webpack_require__(55)(5); // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $def($def.P + $def.F * forced, 'Array', { find: function find(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments[1]); } }); __webpack_require__(72)(KEY); /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , ctx = __webpack_require__(69) , cof = __webpack_require__(54) , $def = __webpack_require__(49) , assert = __webpack_require__(57) , forOf = __webpack_require__(74) , setProto = __webpack_require__(51).set , species = __webpack_require__(73) , SPECIES = __webpack_require__(64)('species') , RECORD = __webpack_require__(56).safe('record') , PROMISE = 'Promise' , global = $.g , process = global.process , asap = process && process.nextTick || __webpack_require__(75).set , P = global[PROMISE] , isFunction = $.isFunction , isObject = $.isObject , assertFunction = assert.fn , assertObject = assert.obj; var useNative = function(){ var test, works = false; function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } try { works = isFunction(P) && isFunction(P.resolve) && P.resolve(test = new P(function(){})) == test; 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; } } catch(e){ works = false; } return works; }(); // helpers function getConstructor(C){ var S = assertObject(C)[SPECIES]; return S != undefined ? S : C; } function isThenable(it){ var then; if(isObject(it))then = it.then; return isFunction(then) ? then : false; } function notify(record){ var chain = record.c; if(chain.length)asap(function(){ var value = record.v , ok = record.s == 1 , i = 0; function run(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ if(!ok)record.h = true; ret = cb === true ? value : cb(value); if(ret === react.P){ react.rej(TypeError('Promise-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(value); } catch(err){ react.rej(err); } } while(chain.length > i)run(chain[i++]); // variable length - can't use forEach chain.length = 0; }); } function isUnhandled(promise){ var record = promise[RECORD] , chain = record.a || record.c , i = 0 , react; if(record.h)return false; while(chain.length > i){ react = chain[i++]; if(react.fail || !isUnhandled(react.P))return false; } return true; } function $reject(value){ var record = this , promise; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; record.a = record.c.slice(); setTimeout(function(){ asap(function(){ if(isUnhandled(promise = record.p)){ if(cof(process) == 'process'){ process.emit('unhandledRejection', value, promise); } else if(global.console && isFunction(console.error)){ console.error('Unhandled promise rejection', value); } } record.a = undefined; }); }, 1); notify(record); } function $resolve(value){ var record = this , then, wrapper; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(then = isThenable(value)){ wrapper = {r: record, d: false}; // wrap then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } else { record.v = value; record.s = 1; notify(record); } } catch(err){ $reject.call(wrapper || {r: record, d: false}, err); // wrap } } // constructor polyfill if(!useNative){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ assertFunction(executor); var record = { p: assert.inst(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 }; $.hide(this, RECORD, record); try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; $.mix(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var S = assertObject(assertObject(this).constructor)[SPECIES]; var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false }; var promise = react.P = new (S != undefined ? S : P)(function(res, rej){ react.res = assertFunction(res); react.rej = assertFunction(rej); }); var record = this[RECORD]; record.c.push(react); if(record.a)record.a.push(react); record.s && notify(record); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } // export $def($def.G + $def.W + $def.F * !useNative, {Promise: P}); cof.set(P, PROMISE); species(P); species($.core[PROMISE]); // for wrapper // statics $def($def.S + $def.F * !useNative, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ return new (getConstructor(this))(function(res, rej){ rej(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ return isObject(x) && RECORD in x && $.getProto(x) === this.prototype ? x : new (getConstructor(this))(function(res){ res(x); }); } }); $def($def.S + $def.F * !(useNative && __webpack_require__(71)(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , values = []; return new C(function(res, rej){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ C.resolve(promise).then(function(value){ results[index] = value; --remaining || res(results); }, rej); }); else res(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this); return new C(function(res, rej){ forOf(iterable, false, function(promise){ C.resolve(promise).then(res, rej); }); }); } }); /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(76); // 23.1 Map Objects __webpack_require__(77)('Map', { // 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); /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(76); // 23.2 Set Objects __webpack_require__(77)('Set', { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , cof = __webpack_require__(54) , $RegExp = $.g.RegExp , Base = $RegExp , proto = $RegExp.prototype , re = /a/g // "new" creates a new object , CORRECT_NEW = new $RegExp(re) !== re // RegExp allows a regex with flags as the pattern , ALLOWS_RE_WITH_FLAGS = function(){ try { return $RegExp(re, 'i') == '/a/i'; } catch(e){ /* empty */ } }(); if($.FW && $.DESC){ if(!CORRECT_NEW || !ALLOWS_RE_WITH_FLAGS){ $RegExp = function RegExp(pattern, flags){ var patternIsRegExp = cof(pattern) == 'RegExp' , flagsIsUndefined = flags === undefined; if(!(this instanceof $RegExp) && patternIsRegExp && flagsIsUndefined)return pattern; return CORRECT_NEW ? new Base(patternIsRegExp && !flagsIsUndefined ? pattern.source : pattern, flags) : new Base(patternIsRegExp ? pattern.source : pattern , patternIsRegExp && flagsIsUndefined ? pattern.flags : flags); }; $.each.call($.getNames(Base), function(key){ key in $RegExp || $.setDesc($RegExp, key, { configurable: true, get: function(){ return Base[key]; }, set: function(it){ Base[key] = it; } }); }); proto.constructor = $RegExp; $RegExp.prototype = proto; $.hide($.g, 'RegExp', $RegExp); } // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')$.setDesc(proto, 'flags', { configurable: true, get: __webpack_require__(62)(/^.*\/(\w*)$/, '$1') }); } __webpack_require__(73)($RegExp); /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , weak = __webpack_require__(78) , leakStore = weak.leakStore , ID = weak.ID , WEAK = weak.WEAK , has = $.has , isObject = $.isObject , isFrozen = Object.isFrozen || $.core.Object.isFrozen , tmp = {}; // 23.3 WeakMap Objects var WeakMap = __webpack_require__(77)('WeakMap', { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ if(isFrozen(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[ID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }, weak, true, true); // IE11 WeakMap frozen keys fix if($.FW && new WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ $.each.call(['delete', 'has', 'get', 'set'], function(key){ var method = WeakMap.prototype[key]; WeakMap.prototype[key] = function(a, b){ // store frozen objects on leaky map if(isObject(a) && isFrozen(a)){ var result = leakStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }; }); } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var weak = __webpack_require__(78); // 23.4 WeakSet Objects __webpack_require__(77)('WeakSet', { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , $def = __webpack_require__(49) , setProto = __webpack_require__(51) , $iter = __webpack_require__(66) , ITERATOR = __webpack_require__(64)('iterator') , ITER = __webpack_require__(56).safe('iter') , step = $iter.step , assert = __webpack_require__(57) , isObject = $.isObject , getProto = $.getProto , $Reflect = $.g.Reflect , _apply = Function.apply , assertObject = assert.obj , _isExtensible = Object.isExtensible || $.isObject , _preventExtensions = Object.preventExtensions || $.it // IE TP has broken Reflect.enumerate , buggyEnumerate = !($Reflect && $Reflect.enumerate && ITERATOR in $Reflect.enumerate({})); function Enumerate(iterated){ $.set(this, ITER, {o: iterated, k: undefined, i: 0}); } $iter.create(Enumerate, 'Object', function(){ var iter = this[ITER] , keys = iter.k , key; if(keys == undefined){ iter.k = keys = []; for(key in iter.o)keys.push(key); } do { if(iter.i >= keys.length)return step(1); } while(!((key = keys[iter.i++]) in iter.o)); return step(0, key); }); var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: function apply(target, thisArgument, argumentsList){ return _apply.call(target, thisArgument, argumentsList); }, // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: function construct(target, argumentsList /*, newTarget*/){ var proto = assert.fn(arguments.length < 3 ? target : arguments[2]).prototype , instance = $.create(isObject(proto) ? proto : Object.prototype) , result = _apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; }, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: function defineProperty(target, propertyKey, attributes){ assertObject(target); try { $.setDesc(target, propertyKey, attributes); return true; } catch(e){ return false; } }, // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function deleteProperty(target, propertyKey){ var desc = $.getDesc(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc = $.getDesc(assertObject(target), propertyKey), proto; if(desc)return $.has(desc, 'value') ? desc.value : desc.get === undefined ? undefined : desc.get.call(receiver); return isObject(proto = getProto(target)) ? get(proto, propertyKey, receiver) : undefined; }, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return $.getDesc(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function getPrototypeOf(target){ return getProto(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function has(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function isExtensible(target){ return _isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: __webpack_require__(79), // 26.1.12 Reflect.preventExtensions(target) preventExtensions: function preventExtensions(target){ assertObject(target); try { _preventExtensions(target); return true; } catch(e){ return false; } }, // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = $.getDesc(assertObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getProto(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = $.desc(0); } if($.has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = $.getDesc(receiver, propertyKey) || $.desc(0); existingDescriptor.value = V; $.setDesc(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } }; // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setProto)reflect.setPrototypeOf = function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } }; $def($def.G, {Reflect: {}}); $def($def.S + $def.F * buggyEnumerate, 'Reflect', { // 26.1.5 Reflect.enumerate(target) enumerate: function enumerate(target){ return new Enumerate(assertObject(target)); } }); $def($def.S, 'Reflect', reflect); /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/domenic/Array.prototype.includes var $def = __webpack_require__(49) , $includes = __webpack_require__(59)(true); $def($def.P, 'Array', { includes: function includes(el /*, fromIndex = 0 */){ return $includes(this, el, arguments[1]); } }); __webpack_require__(72)('includes'); /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/mathiasbynens/String.prototype.at 'use strict'; var $def = __webpack_require__(49) , $at = __webpack_require__(65)(true); $def($def.P, 'String', { at: function at(pos){ return $at(this, pos); } }); /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $def = __webpack_require__(49) , $pad = __webpack_require__(80); $def($def.P, 'String', { lpad: function lpad(n){ return $pad(this, n, arguments[1], true); } }); /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var KEY = 'findIndex' , $def = __webpack_require__(49) , forced = true , $find = __webpack_require__(55)(6); // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $def($def.P + $def.F * forced, 'Array', { findIndex: function findIndex(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments[1]); } }); __webpack_require__(72)(KEY); /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $def = __webpack_require__(49) , $pad = __webpack_require__(80); $def($def.P, 'String', { rpad: function rpad(n){ return $pad(this, n, arguments[1], false); } }); /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/kangax/9698100 var $def = __webpack_require__(49); $def($def.S, 'RegExp', { escape: __webpack_require__(62)(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/WebReflection/9353781 var $ = __webpack_require__(52) , $def = __webpack_require__(49) , ownKeys = __webpack_require__(79); $def($def.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = $.toObject(object) , result = {}; $.each.call(ownKeys(O), function(key){ $.setDesc(result, key, $.desc(0, $.getDesc(O, key))); }); return result; } }); /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $ = __webpack_require__(52) , $def = __webpack_require__(49); function createObjectToArray(isEntries){ return function(object){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; }; } $def($def.S, 'Object', { values: createObjectToArray(false), entries: createObjectToArray(true) }); /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON __webpack_require__(81)('Map'); /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON __webpack_require__(81)('Set'); /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(49) , $task = __webpack_require__(75); $def($def.G + $def.B, { setImmediate: $task.set, clearImmediate: $task.clear }); /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(23); var $ = __webpack_require__(52) , Iterators = __webpack_require__(66).Iterators , ITERATOR = __webpack_require__(64)('iterator') , ArrayValues = Iterators.Array , NodeList = $.g.NodeList; if($.FW && NodeList && !(ITERATOR in NodeList.prototype)){ $.hide(NodeList.prototype, ITERATOR, ArrayValues); } Iterators.NodeList = ArrayValues; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // ie9- setTimeout & setInterval additional parameters fix var $ = __webpack_require__(52) , $def = __webpack_require__(49) , invoke = __webpack_require__(58) , partial = __webpack_require__(82) , navigator = $.g.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), $.isFunction(fn) ? fn : Function(fn) ), time); } : set; } $def($def.G + $def.B + $def.F * MSIE, { setTimeout: wrap($.g.setTimeout), setInterval: wrap($.g.setInterval) }); /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { // JavaScript 1.6 / Strawman array statics shim var $ = __webpack_require__(52) , $def = __webpack_require__(49) , $Array = $.core.Array || Array , statics = {}; function setStatics(keys, length){ $.each.call(keys.split(','), function(key){ if(length == undefined && key in $Array)statics[key] = $Array[key]; else if(key in [])statics[key] = __webpack_require__(69)(Function.call, [][key], length); }); } setStatics('pop,reverse,shift,keys,values,entries', 1); setStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $def($def.S, 'Array', statics); /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , global = $.g , core = $.core , isFunction = $.isFunction; function ctx(fn, that){ return function(){ return fn.apply(that, arguments); }; } global.core = core; // type bitmap $def.F = 1; // forced $def.G = 2; // global $def.S = 4; // static $def.P = 8; // proto $def.B = 16; // bind $def.W = 32; // wrap function $def(type, name, source){ var key, own, out, exp , isGlobal = type & $def.G , target = isGlobal ? global : type & $def.S ? global[name] : (global[name] || {}).prototype , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // contains in native own = !(type & $def.F) && target && key in target; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & $def.B && own)exp = ctx(out, global); else exp = type & $def.P && isFunction(out) ? ctx(Function.call, out) : out; // extend global if(target && !own){ if(isGlobal)target[key] = out; else delete target[key] && $.hide(target, key, out); } // export if(exports[key] != out)$.hide(exports, key, exp); } } module.exports = $def; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , enumKeys = __webpack_require__(63); // 19.1.2.1 Object.assign(target, source, ...) /* eslint-disable no-unused-vars */ module.exports = Object.assign || function assign(target, source){ /* eslint-enable no-unused-vars */ var T = Object($.assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = $.ES5Object(arguments[i++]) , keys = enumKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var $ = __webpack_require__(52) , assert = __webpack_require__(57); function check(O, proto){ assert.obj(O); assert(proto === null || $.isObject(proto), proto, ": can't set as prototype!"); } module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} // eslint-disable-line ? function(buggy, set){ try { set = __webpack_require__(69)(Function.call, $.getDesc(Object.prototype, '__proto__').set, 2); set({}, []); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }() : undefined), check: check }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = typeof self != 'undefined' ? self : Function('return this')() , core = {} , defineProperty = Object.defineProperty , hasOwnProperty = {}.hasOwnProperty , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min; // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){ try { return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2; } catch(e){ /* empty */ } }(); var hide = createDefiner(1); // 7.1.4 ToInteger function toInteger(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); } function desc(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return $.setDesc(object, key, desc(bitmap, value)); } : simpleSet; } function isObject(it){ return it !== null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } function assertDefined(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; } var $ = module.exports = __webpack_require__(83)({ g: global, core: core, html: global.document && document.documentElement, // http://jsperf.com/core-js-isobject isObject: isObject, isFunction: isFunction, it: function(it){ return it; }, that: function(){ return this; }, // 7.1.4 ToInteger toInteger: toInteger, // 7.1.15 ToLength toLength: function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }, toIndex: function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }, has: function(it, key){ return hasOwnProperty.call(it, key); }, create: Object.create, getProto: Object.getPrototypeOf, DESC: DESC, desc: desc, getDesc: Object.getOwnPropertyDescriptor, setDesc: defineProperty, setDescs: Object.defineProperties, getKeys: Object.keys, getNames: Object.getOwnPropertyNames, getSymbols: Object.getOwnPropertySymbols, assertDefined: assertDefined, // Dummy, fix for not array-like ES3 string in es5 module ES5Object: Object, toObject: function(it){ return $.ES5Object(assertDefined(it)); }, hide: hide, def: createDefiner(0), set: global.Symbol ? simpleSet : hide, mix: function(target, src){ for(var key in src)hide(target, key, src[key]); return target; }, each: [].forEach }); /* eslint-disable no-undef */ if(typeof __e != 'undefined')__e = core; if(typeof __g != 'undefined')__g = global; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , document = $.g.document , isObject = $.isObject // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , TAG = __webpack_require__(64)('toStringTag') , toString = {}.toString; function cof(it){ return toString.call(it).slice(8, -1); } cof.classof = function(it){ var O, T; return it == undefined ? it === undefined ? 'Undefined' : 'Null' : typeof (T = (O = Object(it))[TAG]) == 'string' ? T : cof(O); }; cof.set = function(it, tag, stat){ if(it && !$.has(it = stat ? it : it.prototype, TAG))$.hide(it, TAG, tag); }; module.exports = cof; /***/ }, /* 55 */ /***/ 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 $ = __webpack_require__(52) , ctx = __webpack_require__(69); module.exports = function(TYPE){ 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; return function($this, callbackfn, that){ var O = Object($.assertDefined($this)) , self = $.ES5Object(O) , f = ctx(callbackfn, that, 3) , length = $.toLength(self.length) , index = 0 , result = IS_MAP ? Array(length) : IS_FILTER ? [] : 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; }; }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var sid = 0; function uid(key){ return 'Symbol(' + key + ')_' + (++sid + Math.random()).toString(36); } uid.safe = __webpack_require__(52).g.Symbol || uid; module.exports = uid; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52); function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } assert.def = $.assertDefined; assert.fn = function(it){ if(!$.isFunction(it))throw TypeError(it + ' is not a function!'); return it; }; assert.obj = function(it){ if(!$.isObject(it))throw TypeError(it + ' is not an object!'); return it; }; assert.inst = function(it, Constructor, name){ if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); return it; }; module.exports = assert; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { // 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]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var $ = __webpack_require__(52); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = $.toObject($this) , length = $.toLength(O.length) , index = $.toIndex(fromIndex, length) , value; if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(exec){ try { exec(); return false; } catch(e){ return true; } }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52); module.exports = function(object, el){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = function(regExp, replace, isStatic){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); }; }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52); module.exports = function(it){ var keys = $.getKeys(it) , getDesc = $.getDesc , getSymbols = $.getSymbols; if(getSymbols)$.each.call(getSymbols(it), function(key){ if(getDesc(it, key).enumerable)keys.push(key); }); return keys; }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(52).g , store = {}; module.exports = function(name){ return store[name] || (store[name] = global.Symbol && global.Symbol[name] || __webpack_require__(56).safe('Symbol.' + name)); }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { // true -> String#at // false -> String#codePointAt var $ = __webpack_require__(52); module.exports = function(TO_STRING){ return function(that, pos){ var s = String($.assertDefined(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; }; }; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , cof = __webpack_require__(54) , assertObject = __webpack_require__(57).obj , SYMBOL_ITERATOR = __webpack_require__(64)('iterator') , FF_ITERATOR = '@@iterator' , Iterators = {} , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, $.that); function setIterator(O, value){ $.hide(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol if(FF_ITERATOR in [])$.hide(O, FF_ITERATOR, value); } module.exports = { // Safari has buggy iterators w/o `next` BUGGY: 'keys' in [] && !('next' in [].keys()), Iterators: Iterators, step: function(done, value){ return {value: value, done: !!done}; }, is: function(it){ var O = Object(it) , Symbol = $.g.Symbol , SYM = Symbol && Symbol.iterator || FF_ITERATOR; return SYM in O || SYMBOL_ITERATOR in O || $.has(Iterators, cof.classof(O)); }, get: function(it){ var Symbol = $.g.Symbol , ext = it[Symbol && Symbol.iterator || FF_ITERATOR] , getIter = ext || it[SYMBOL_ITERATOR] || Iterators[cof.classof(it)]; return assertObject(getIter.call(it)); }, set: setIterator, create: function(Constructor, NAME, next, proto){ Constructor.prototype = $.create(proto || IteratorPrototype, {next: $.desc(1, next)}); cof.set(Constructor, NAME + ' Iterator'); } }; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(49) , $ = __webpack_require__(52) , cof = __webpack_require__(54) , $iter = __webpack_require__(66) , SYMBOL_ITERATOR = __webpack_require__(64)('iterator') , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values' , Iterators = $iter.Iterators; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){ $iter.create(Constructor, NAME, next); function createMethod(kind){ function $$(that){ return new Constructor(that, kind); } switch(kind){ case KEYS: return function keys(){ return $$(this); }; case VALUES: return function values(){ return $$(this); }; } return function entries(){ return $$(this); }; } var TAG = NAME + ' Iterator' , proto = Base.prototype , _native = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , _default = _native || createMethod(DEFAULT) , methods, key; // Fix native if(_native){ var IteratorPrototype = $.getProto(_default.call(new Base)); // Set @@toStringTag to native iterators cof.set(IteratorPrototype, TAG, true); // FF fix if($.FW && $.has(proto, FF_ITERATOR))$iter.set(IteratorPrototype, $.that); } // Define iterator if($.FW)$iter.set(proto, _default); // Plug for library Iterators[NAME] = _default; Iterators[TAG] = $.that; if(DEFAULT){ methods = { keys: IS_SET ? _default : createMethod(KEYS), values: DEFAULT == VALUES ? _default : createMethod(VALUES), entries: DEFAULT != VALUES ? _default : createMethod('entries') }; if(FORCE)for(key in methods){ if(!(key in proto))$.hide(proto, key, methods[key]); } else $def($def.P + $def.F * $iter.BUGGY, NAME, methods); } }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52); module.exports = function repeat(count){ var str = String($.assertDefined(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; }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { // Optional / simple context binding var assertFunction = __webpack_require__(57).fn; module.exports = function(fn, that, length){ assertFunction(fn); if(~length && 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); }; }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { var assertObject = __webpack_require__(57).obj; function close(iterator){ var ret = iterator['return']; if(ret !== undefined)assertObject(ret.call(iterator)); } function call(iterator, fn, value, entries){ try { return entries ? fn(assertObject(value)[0], value[1]) : fn(value); } catch(e){ close(iterator); throw e; } } call.close = close; module.exports = call; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var SYMBOL_ITERATOR = __webpack_require__(64)('iterator') , SAFE_CLOSING = false; try { var riter = [7][SYMBOL_ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec){ if(!SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[SYMBOL_ITERATOR](); iter.next = function(){ safe = true; }; arr[SYMBOL_ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.31 Array.prototype[@@unscopables] var $ = __webpack_require__(52) , UNSCOPABLES = __webpack_require__(64)('unscopables'); if($.FW && !(UNSCOPABLES in []))$.hide(Array.prototype, UNSCOPABLES, {}); module.exports = function(key){ if($.FW)[][UNSCOPABLES][key] = true; }; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , SPECIES = __webpack_require__(64)('species'); module.exports = function(C){ if($.DESC && !(SPECIES in C))$.setDesc(C, SPECIES, { configurable: true, get: $.that }); }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(69) , get = __webpack_require__(66).get , call = __webpack_require__(70); module.exports = function(iterable, entries, fn, that){ var iterator = get(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done){ if(call(iterator, f, step.value, entries) === false){ return call.close(iterator); } } }; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , ctx = __webpack_require__(69) , cof = __webpack_require__(54) , invoke = __webpack_require__(58) , cel = __webpack_require__(53) , global = $.g , isFunction = $.isFunction , html = $.html , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; function run(){ var id = +this; if($.has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run.call(event.data); } // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!isFunction(setTask) || !isFunction(clearTask)){ setTask = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function(id){ delete queue[id]; }; // Node.js 0.8- if(cof(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); }; addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // 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 }; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , ctx = __webpack_require__(69) , safe = __webpack_require__(56).safe , assert = __webpack_require__(57) , forOf = __webpack_require__(74) , step = __webpack_require__(66).step , has = $.has , set = $.set , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , ID = safe('id') , O1 = safe('O1') , LAST = safe('last') , FIRST = safe('first') , ITER = safe('iter') , SIZE = $.DESC ? safe('size') : 'size' , id = 0; function fastKey(it, create){ // return primitive with prefix if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // can't set id to frozen object if(isFrozen(it))return 'F'; if(!has(it, ID)){ // not necessary to add id if(!create)return 'E'; // add missing object id hide(it, ID, ++id); // return object id with prefix } return 'O' + it[ID]; } function getEntry(that, key){ // fast case var index = fastKey(key), entry; if(index != 'F')return that[O1][index]; // frozen object case for(entry = that[FIRST]; entry; entry = entry.n){ if(entry.k == key)return entry; } } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ var that = assert.inst(this, C, NAME) , iterable = arguments[0]; set(that, O1, $.create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); } $.mix(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[O1], entry = that[FIRST]; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that[FIRST] = that[LAST] = 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[O1][entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = 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[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ 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($.DESC)$.setDesc(C.prototype, 'size', { get: function(){ return assert.def(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[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index != 'F')that[O1][index] = entry; } return that; }, getEntry: getEntry, // 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 setIter: function(C, NAME, IS_MAP){ __webpack_require__(67)(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , kind = iter.k , entry = iter.l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){ // or finish the iteration iter.o = 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); } }; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , $def = __webpack_require__(49) , BUGGY = __webpack_require__(66).BUGGY , forOf = __webpack_require__(74) , species = __webpack_require__(73) , assertInstance = __webpack_require__(57).inst; module.exports = function(NAME, methods, common, IS_MAP, IS_WEAK){ var Base = $.g[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; function fixMethod(KEY, CHAIN){ var method = proto[KEY]; if($.FW)proto[KEY] = function(a, b){ var result = method.call(this, a === 0 ? 0 : a, b); return CHAIN ? this : result; }; } if(!$.isFunction(C) || !(IS_WEAK || !BUGGY && proto.forEach && proto.entries)){ // create collection constructor C = common.getConstructor(NAME, IS_MAP, ADDER); $.mix(C.prototype, methods); } else { var inst = new C , chain = inst[ADDER](IS_WEAK ? {} : -0, 1) , buggyZero; // wrap for init collections from iterable if(!__webpack_require__(71)(function(iter){ new C(iter); })){ // eslint-disable-line no-new C = function(){ assertInstance(this, C, NAME); var that = new Base , iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }; C.prototype = proto; if($.FW)proto.constructor = C; } IS_WEAK || inst.forEach(function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixMethod(ADDER, true); } __webpack_require__(54).set(C, NAME); O[NAME] = C; $def($def.G + $def.W + $def.F * (C != Base), O); species(C); species($.core[NAME]); // for wrapper if(!IS_WEAK)common.setIter(C, NAME, IS_MAP); return C; }; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , safe = __webpack_require__(56).safe , assert = __webpack_require__(57) , forOf = __webpack_require__(74) , _has = $.has , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , id = 0 , ID = safe('id') , WEAK = safe('weak') , LEAK = safe('leak') , method = __webpack_require__(55) , find = method(5) , findIndex = method(6); function findFrozen(store, key){ return find(store.array, function(it){ return it[0] === key; }); } // fallback for frozen keys function leakStore(that){ return that[LEAK] || hide(that, LEAK, { array: [], get: function(key){ var entry = findFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findFrozen(this, key); }, set: function(key, value){ var entry = findFrozen(this, key); if(entry)entry[1] = value; else this.array.push([key, value]); }, 'delete': function(key){ var index = findIndex(this.array, function(it){ return it[0] === key; }); if(~index)this.array.splice(index, 1); return !!~index; } })[LEAK]; } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ $.set(assert.inst(this, C, NAME), ID, id++); var iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, this[ADDER], this); } $.mix(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; if(isFrozen(key))return leakStore(this)['delete'](key); return _has(key, WEAK) && _has(key[WEAK], this[ID]) && delete key[WEAK][this[ID]]; }, // 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; if(isFrozen(key))return leakStore(this).has(key); return _has(key, WEAK) && _has(key[WEAK], this[ID]); } }); return C; }, def: function(that, key, value){ if(isFrozen(assert.obj(key))){ leakStore(that).set(key, value); } else { _has(key, WEAK) || hide(key, WEAK, {}); key[WEAK][that[ID]] = value; } return that; }, leakStore: leakStore, WEAK: WEAK, ID: ID }; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(52) , assertObject = __webpack_require__(57).obj; module.exports = function ownKeys(it){ assertObject(it); var keys = $.getNames(it) , getSymbols = $.getSymbols; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { // http://wiki.ecmascript.org/doku.php?id=strawman:string_padding var $ = __webpack_require__(52) , repeat = __webpack_require__(68); module.exports = function(that, minLength, fillChar, left){ // 1. Let O be CheckObjectCoercible(this value). // 2. Let S be ToString(O). var S = String($.assertDefined(that)); // 4. If intMinLength is undefined, return S. if(minLength === undefined)return S; // 4. Let intMinLength be ToInteger(minLength). var intMinLength = $.toInteger(minLength); // 5. Let fillLen be the number of characters in S minus intMinLength. var fillLen = intMinLength - S.length; // 6. If fillLen < 0, then throw a RangeError exception. // 7. If fillLen is +∞, then throw a RangeError exception. if(fillLen < 0 || fillLen === Infinity){ throw new RangeError('Cannot satisfy string length ' + minLength + ' for string: ' + S); } // 8. Let sFillStr be the string represented by fillStr. // 9. If sFillStr is undefined, let sFillStr be a space character. var sFillStr = fillChar === undefined ? ' ' : String(fillChar); // 10. Let sFillVal be a String made of sFillStr, repeated until fillLen is met. var sFillVal = repeat.call(sFillStr, Math.ceil(fillLen / sFillStr.length)); // truncate if we overflowed if(sFillVal.length > fillLen)sFillVal = left ? sFillVal.slice(sFillVal.length - fillLen) : sFillVal.slice(0, fillLen); // 11. Return a string made from sFillVal, followed by S. // 11. Return a String made from S, followed by sFillVal. return left ? sFillVal.concat(S) : S.concat(sFillVal); }; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $def = __webpack_require__(49) , forOf = __webpack_require__(74); module.exports = function(NAME){ $def($def.P, NAME, { toJSON: function toJSON(){ var arr = []; forOf(this, false, arr.push, arr); return arr; } }); }; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(52) , invoke = __webpack_require__(58) , assertFunction = __webpack_require__(57).fn; module.exports = function(/* ...pargs */){ var fn = assertFunction(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 , _length = arguments.length , j = 0, k = 0, args; if(!holder && !_length)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(_length > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { module.exports = function($){ $.FW = true; $.path = $.g; return $; }; /***/ } /******/ ]); // 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; }();
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import { GraphQLObjectType as ObjectType, GraphQLString as StringType, GraphQLNonNull as NonNull, } from 'graphql'; const NewsItemType = new ObjectType({ name: 'NewsItem', fields: { title: { type: new NonNull(StringType) }, link: { type: new NonNull(StringType) }, author: { type: StringType }, pubDate: { type: new NonNull(StringType) }, content: { type: StringType }, }, }); export default NewsItemType;
/*! * js-data * @version 1.5.10 - Homepage <http://www.js-data.io/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else if(typeof define === 'function' && define.amd) define(["bluebird", "js-data-schema"], factory); else if(typeof exports === 'object') exports["JSData"] = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else root["JSData"] = factory(root["bluebird"], root["Schemator"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_5__) { 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__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var DS = _interopRequire(__webpack_require__(3)); module.exports = { DS: DS, createStore: function createStore(options) { return new DS(options); }, DSUtils: DSUtils, DSErrors: DSErrors, version: { full: "1.5.10", major: parseInt("1", 10), minor: parseInt("5", 10), patch: parseInt("10", 10), alpha: true ? "false" : false, beta: true ? "false" : false } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; /* jshint eqeqeq:false */ var DSErrors = _interopRequire(__webpack_require__(2)); var forEach = _interopRequire(__webpack_require__(10)); var slice = _interopRequire(__webpack_require__(11)); var forOwn = _interopRequire(__webpack_require__(15)); var contains = _interopRequire(__webpack_require__(12)); var deepMixIn = _interopRequire(__webpack_require__(16)); var pascalCase = _interopRequire(__webpack_require__(20)); var remove = _interopRequire(__webpack_require__(13)); var pick = _interopRequire(__webpack_require__(17)); var sort = _interopRequire(__webpack_require__(14)); var upperCase = _interopRequire(__webpack_require__(21)); var observe = _interopRequire(__webpack_require__(6)); var es6Promise = _interopRequire(__webpack_require__(22)); var BinaryHeap = _interopRequire(__webpack_require__(9)); var w = undefined, _Promise = undefined; var DSUtils = undefined; var objectProto = Object.prototype; var toString = objectProto.toString; es6Promise.polyfill(); var isArray = Array.isArray || function isArray(value) { return toString.call(value) == "[object Array]" || false; }; var isRegExp = function (value) { return toString.call(value) == "[object RegExp]" || false; }; // adapted from lodash.isBoolean var isBoolean = function (value) { return value === true || value === false || value && typeof value == "object" && toString.call(value) == "[object Boolean]" || false; }; // adapted from lodash.isString var isString = function (value) { return typeof value == "string" || value && typeof value == "object" && toString.call(value) == "[object String]" || false; }; var isObject = function (value) { return toString.call(value) == "[object Object]" || false; }; // adapted from lodash.isDate var isDate = function (value) { return value && typeof value == "object" && toString.call(value) == "[object Date]" || false; }; // adapted from lodash.isNumber var isNumber = function (value) { var type = typeof value; return type == "number" || value && type == "object" && toString.call(value) == "[object Number]" || false; }; // adapted from lodash.isFunction var isFunction = function (value) { return typeof value == "function" || value && toString.call(value) === "[object Function]" || false; }; // shorthand argument checking functions, using these shaves 1.18 kb off of the minified build var isStringOrNumber = function (value) { return isString(value) || isNumber(value); }; var isStringOrNumberErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be a string or a number!"); }; var isObjectErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an object!"); }; var isArrayErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an array!"); }; // adapted from mout.isEmpty var isEmpty = function (val) { if (val == null) { // jshint ignore:line // typeof null == 'object' so we check it first return true; } else if (typeof val === "string" || isArray(val)) { return !val.length; } else if (typeof val === "object") { var _ret = (function () { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return { v: result }; })(); if (typeof _ret === "object") return _ret.v; } else { return true; } }; var intersection = function (array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item = undefined; for (var i = 0, _length = array1.length; i < _length; i++) { item = array1[i]; if (DSUtils.contains(result, item)) { continue; } if (DSUtils.contains(array2, item)) { result.push(item); } } return result; }; var filter = function (array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; }; function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype["finally"]) { w.Promise.prototype["finally"] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; _Promise = __webpack_require__(4); } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } var toPromisify = ["beforeValidate", "validate", "afterValidate", "beforeCreate", "afterCreate", "beforeUpdate", "afterUpdate", "beforeDestroy", "afterDestroy"]; // adapted from angular.copy var copy = function (source, destination, stackSource, stackDest) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { destination = copy(source, Object.create(Object.getPrototypeOf(source)), stackSource, stackDest); } } } else { if (source === destination) { throw new Error("Cannot copy! Source and destination are identical."); } stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) { return stackDest[index]; } stackSource.push(source); stackDest.push(destination); } var result = undefined; if (isArray(source)) { destination.length = 0; for (var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function (value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; }; // adapted from angular.equals var equals = function (o1, o2) { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if (o1 !== o1 && o2 !== o2) { return true; } // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == "object") { if (isArray(o1)) { if (!isArray(o2)) { return false; } if ((length = o1.length) == o2.length) { // jshint ignore:line for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) { return false; } } return true; } } else if (isDate(o1)) { if (!isDate(o2)) { return false; } return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(o2)) { return false; } keySet = {}; for (key in o1) { if (key.charAt(0) === "$" || isFunction(o1[key])) { continue; } if (!equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== "$" && o2[key] !== undefined && !isFunction(o2[key])) { return false; } } return true; } } } return false; }; var resolveId = function (definition, idOrInstance) { if (isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }; var resolveItem = function (resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }; var isValidString = function (val) { return val != null && val !== ""; // jshint ignore:line }; var join = function (items, separator) { separator = separator || ""; return filter(items, isValidString).join(separator); }; var makePath = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var result = join(args, "/"); return result.replace(/([^:\/]|^)\/{2,}/g, "$1/"); }; DSUtils = { // Options that inherit from defaults _: function _(parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new DSErrors.IA("\"options\" must be an object!"); } forEach(toPromisify, function (name) { if (typeof options[name] === "function" && options[name].toString().indexOf("for (var _len = arg") === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; O.prototype = parent; O.prototype.orig = function () { var orig = {}; forOwn(this, function (value, key) { orig[key] = value; }); return orig; }; return new O(options); }, _n: isNumber, _s: isString, _sn: isStringOrNumber, _snErr: isStringOrNumberErr, _o: isObject, _oErr: isObjectErr, _a: isArray, _aErr: isArrayErr, compute: function compute(fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property _this[field] = fn[fn.length - 1].apply(_this, args); }, contains: contains, copy: copy, deepMixIn: deepMixIn, diffObjectFromOldObject: observe.diffObjectFromOldObject, BinaryHeap: BinaryHeap, equals: equals, Events: Events, filter: filter, forEach: forEach, forOwn: forOwn, fromJson: function fromJson(json) { return isString(json) ? JSON.parse(json) : json; }, get: __webpack_require__(18), intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: pascalCase, pick: pick, Promise: _Promise, promisify: function promisify(fn, target) { var _this = this; if (!fn) { return; } else if (typeof fn !== "function") { throw new Error("Can only promisify functions!"); } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new _this.Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: remove, set: __webpack_require__(19), slice: slice, sort: sort, toJson: JSON.stringify, updateTimestamp: function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === "function" ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, upperCase: upperCase, removeCircular: function removeCircular(object) { var objects = []; return (function rmCirc(value) { var i = undefined; var nu = undefined; if (typeof value === "object" && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return undefined; } } objects.push(value); if (DSUtils.isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i]); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k]); }); } return nu; } return value; })(object); }, resolveItem: resolveItem, resolveId: resolveId, w: w }; module.exports = DSUtils; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var IllegalArgumentError = (function (_Error) { function IllegalArgumentError(message) { _classCallCheck(this, IllegalArgumentError); _get(Object.getPrototypeOf(IllegalArgumentError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "Illegal Argument!"; } _inherits(IllegalArgumentError, _Error); return IllegalArgumentError; })(Error); var RuntimeError = (function (_Error2) { function RuntimeError(message) { _classCallCheck(this, RuntimeError); _get(Object.getPrototypeOf(RuntimeError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "RuntimeError Error!"; } _inherits(RuntimeError, _Error2); return RuntimeError; })(Error); var NonexistentResourceError = (function (_Error3) { function NonexistentResourceError(resourceName) { _classCallCheck(this, NonexistentResourceError); _get(Object.getPrototypeOf(NonexistentResourceError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = "" + resourceName + " is not a registered resource!"; } _inherits(NonexistentResourceError, _Error3); return NonexistentResourceError; })(Error); module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /* jshint eqeqeq:false */ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var syncMethods = _interopRequire(__webpack_require__(7)); var asyncMethods = _interopRequire(__webpack_require__(8)); var Schemator = undefined; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(_x, _x2, _x3, _x4) { var _again = true; _function: while (_again) { _again = false; var orderBy = _x, index = _x2, a = _x3, b = _x4; def = cA = cB = undefined; var def = orderBy[index]; var cA = DSUtils.get(a, def[0]), cB = DSUtils.get(b, def[0]); if (DSUtils._s(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils._s(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === "DESC") { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } } } var Defaults = (function () { function Defaults() { _classCallCheck(this, Defaults); } _createClass(Defaults, { errorFn: { value: function errorFn(a, b) { if (this.error && typeof this.error === "function") { try { if (typeof a === "string") { throw new Error(a); } else { throw a; } } catch (err) { a = err; } this.error(this.name || null, a || null, b || null); } } } }); return Defaults; })(); var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.basePath = ""; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.bypassCache = false; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.defaultAdapter = "http"; defaultsPrototype.debug = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ""; defaultsPrototype.error = console ? function (a, b, c) { return console[typeof console.error === "function" ? "error" : "log"](a, b, c); } : false; defaultsPrototype.fallbackAdapters = ["http"]; defaultsPrototype.findBelongsTo = true; defaultsPrototype.findHasOne = true; defaultsPrototype.findHasMany = true; defaultsPrototype.findInverseLinks = true; defaultsPrototype.idAttribute = "id"; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.loadFromServer = false; defaultsPrototype.log = console ? function (a, b, c, d, e) { return console[typeof console.info === "function" ? "info" : "log"](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { var _this = this; if (_this.debug && _this.log && typeof _this.log === "function") { _this.log(_this.name || null, a || null, b || null, c || null, d || null); } }; defaultsPrototype.maxAge = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.reapAction = !!DSUtils.w ? "inject" : "none"; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = "single"; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var filtered = collection; var where = null; var reserved = { skip: "", offset: "", where: "", limit: "", orderBy: "", sort: "" }; params = params || {}; options = options || {}; if (DSUtils._o(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { "==": value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils._s(clause)) { clause = { "===": clause }; } else if (DSUtils._n(clause) || DSUtils.isBoolean(clause)) { clause = { "==": clause }; } if (DSUtils._o(clause)) { DSUtils.forOwn(clause, function (term, op) { var expr = undefined; var isOr = op[0] === "|"; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === "==") { expr = val == term; } else if (op === "===") { expr = val === term; } else if (op === "!=") { expr = val != term; } else if (op === "!==") { expr = val !== term; } else if (op === ">") { expr = val > term; } else if (op === ">=") { expr = val >= term; } else if (op === "<") { expr = val < term; } else if (op === "<=") { expr = val <= term; } else if (op === "isectEmpty") { expr = !DSUtils.intersection(val || [], term || []).length; } else if (op === "isectNotEmpty") { expr = DSUtils.intersection(val || [], term || []).length; } else if (op === "in") { if (DSUtils._s(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === "notIn") { if (DSUtils._s(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } else if (op === "contains") { if (DSUtils._s(val)) { expr = val.indexOf(term) !== -1; } else { expr = DSUtils.contains(val, term); } } else if (op === "notContains") { if (DSUtils._s(val)) { expr = val.indexOf(term) === -1; } else { expr = !DSUtils.contains(val, term); } } if (expr !== undefined) { keep = first ? expr : isOr ? keep || expr : keep && expr; } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils._s(params.orderBy)) { orderBy = [[params.orderBy, "ASC"]]; } else if (DSUtils._a(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils._s(params.sort)) { orderBy = [[params.sort, "ASC"]]; } else if (!orderBy && DSUtils._a(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { (function () { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils._s(def)) { orderBy[i] = [def, "ASC"]; } else if (!DSUtils._a(def)) { throw new DSErrors.IA("DS.filter(\"" + resourceName + "\"[, params][, options]): " + DSUtils.toJson(def) + ": Must be a string or an array!", { params: { "orderBy[i]": { actual: typeof def, expected: "string|array" } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); })(); } var limit = DSUtils._n(params.limit) ? params.limit : null; var skip = null; if (DSUtils._n(params.skip)) { skip = params.skip; } else if (DSUtils._n(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils._n(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils._n(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; var DS = (function () { function DS(options) { _classCallCheck(this, DS); var _this = this; options = options || {}; try { Schemator = __webpack_require__(5); } catch (e) {} if (!Schemator || DSUtils.isEmpty(Schemator)) { try { Schemator = window.Schemator; } catch (e) {} } Schemator = Schemator || options.schemator; if (typeof Schemator === "function") { _this.schemator = new Schemator(); } _this.store = {}; // alias store, shaves 0.1 kb off the minified build _this.s = _this.store; _this.definitions = {}; // alias definitions, shaves 0.3 kb off the minified build _this.defs = _this.definitions; _this.adapters = {}; _this.defaults = new Defaults(); _this.observe = DSUtils.observe; DSUtils.forOwn(options, function (v, k) { _this.defaults[k] = v; }); } _createClass(DS, { getAdapter: { value: function getAdapter(options) { var errorIfNotExist = false; options = options || {}; if (DSUtils._s(options)) { errorIfNotExist = true; options = { adapter: options }; } var adapter = this.adapters[options.adapter]; if (adapter) { return adapter; } else if (errorIfNotExist) { throw new Error("" + options.adapter + " is not a registered adapter!"); } else { return this.adapters[options.defaultAdapter]; } } }, registerAdapter: { value: function registerAdapter(name, Adapter, options) { var _this = this; options = options || {}; if (DSUtils.isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options["default"]) { _this.defaults.defaultAdapter = name; } } }, is: { value: function is(resourceName, instance) { var definition = this.defs[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } return instance instanceof definition[definition["class"]]; } } }); return DS; })(); var dsPrototype = DS.prototype; dsPrototype.getAdapter.shorthand = false; dsPrototype.registerAdapter.shorthand = false; dsPrototype.errors = DSErrors; dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { if(typeof __WEBPACK_EXTERNAL_MODULE_5__ === 'undefined') {var e = new Error("Cannot find module \"undefined\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // Modifications // Copyright 2014-2015 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; var testingExposeCycleCount = global.testingExposeCycleCount; var equalityFn = function (a, b) { return a === b; }; var blacklist = []; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ return function(fn) { return Promise.resolve().then(fn); } })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, 'delete': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } // Export the observe-js object for **Node.js**, with backwards-compatibility // for the old `require()` API. Also ensure `exports` is not a DOM Element. // If we're in the browser, export as a global object. global.Observer = Observer; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.diffObjectFromOldObject = diffObjectFromOldObject; global.ObjectObserver = ObjectObserver; })(exports); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var defineResource = _interopRequire(__webpack_require__(31)); var eject = _interopRequire(__webpack_require__(32)); var ejectAll = _interopRequire(__webpack_require__(33)); var filter = _interopRequire(__webpack_require__(34)); var inject = _interopRequire(__webpack_require__(35)); var link = _interopRequire(__webpack_require__(36)); var linkAll = _interopRequire(__webpack_require__(37)); var linkInverse = _interopRequire(__webpack_require__(38)); var unlinkInverse = _interopRequire(__webpack_require__(39)); var NER = DSErrors.NER; var IA = DSErrors.IA; var R = DSErrors.R; function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } module.exports = { changes: function changes(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); var item = _this.get(resourceName, id); if (item) { var _ret = (function () { if (DSUtils.w) { _this.s[resourceName].observers[id].deliver(); } var diff = DSUtils.diffObjectFromOldObject(item, _this.s[resourceName].previousAttributes[id], DSUtils.equals, options.ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return { v: diff }; })(); if (typeof _ret === "object") { return _ret.v; } } }, changeHistory: function changeHistory(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.defs[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils._sn(id)) { throw DSUtils._snErr("id"); } if (!definition.keepChangeHistory) { definition.errorFn("changeHistory is disabled for this resource!"); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } }, compute: function compute(resourceName, instance) { var _this = this; var definition = _this.defs[resourceName]; instance = DSUtils.resolveItem(_this.s[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R("Item not in the store!"); } else if (!DSUtils._o(instance) && !DSUtils._sn(instance)) { throw new IA("\"instance\" must be an object, string or number!"); } DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field); }); return instance; }, createInstance: function createInstance(resourceName, attrs, options) { var definition = this.defs[resourceName]; var item = undefined; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA("\"attrs\" must be an object!"); } options = DSUtils._(definition, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition["class"]]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, attrs); } return item; }, defineResource: defineResource, digest: function digest() { this.observe.Platform.performMicrotaskCheckpoint(); }, eject: eject, ejectAll: ejectAll, filter: filter, get: function get(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); // cache miss, request resource from server var item = _this.s[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; }, getAll: function getAll(resourceName, ids) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var collection = []; if (!definition) { throw new NER(resourceName); } else if (ids && !DSUtils._a(ids)) { throw DSUtils._aErr("ids"); } if (DSUtils._a(ids)) { var _length = ids.length; for (var i = 0; i < _length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; }, hasChanges: function hasChanges(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } }, inject: inject, lastModified: function lastModified(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; }, lastSaved: function lastSaved(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; }, link: link, linkAll: linkAll, linkInverse: linkInverse, previous: function previous(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } // return resource from cache return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined; }, unlinkInverse: unlinkInverse }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var create = _interopRequire(__webpack_require__(40)); var destroy = _interopRequire(__webpack_require__(41)); var destroyAll = _interopRequire(__webpack_require__(42)); var find = _interopRequire(__webpack_require__(43)); var findAll = _interopRequire(__webpack_require__(44)); var loadRelations = _interopRequire(__webpack_require__(45)); var reap = _interopRequire(__webpack_require__(46)); var save = _interopRequire(__webpack_require__(47)); var update = _interopRequire(__webpack_require__(48)); var updateAll = _interopRequire(__webpack_require__(49)); module.exports = { create: create, destroy: destroy, destroyAll: destroyAll, find: find, findAll: findAll, loadRelations: loadRelations, reap: reap, refresh: function refresh(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.defs[resourceName]; id = DSUtils.resolveId(_this.defs[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.bypassCache = true; resolve(_this.get(resourceName, id)); } }).then(function (item) { return item ? _this.find(resourceName, id, options) : item; }); }, save: save, update: update, updateAll: updateAll }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /*! * yabh * @version 1.0.0 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["BinaryHeap"] = factory(); else root["BinaryHeap"] = factory(); })(this, function() { 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__) { var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var _parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(_parent)) { break; } else { heap[parentN] = element; heap[n] = _parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ var bubbleDown = function (heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } }; var BinaryHeap = (function () { function BinaryHeap(weightFunc, compareFunc) { _classCallCheck(this, BinaryHeap); if (!weightFunc) { weightFunc = function (x) { return x; }; } if (!compareFunc) { compareFunc = function (x, y) { return x === y; }; } if (typeof weightFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"weightFunc\" must be a function!"); } if (typeof compareFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"compareFunc\" must be a function!"); } this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } _createClass(BinaryHeap, { push: { value: function push(node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); } }, peek: { value: function peek() { return this.heap[0]; } }, pop: { value: function pop() { var front = this.heap[0]; var end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; } }, remove: { value: function remove(node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; } }, removeAll: { value: function removeAll() { this.heap = []; } }, size: { value: function size() { return this.heap.length; } } }); return BinaryHeap; })(); module.exports = BinaryHeap; /***/ } /******/ ]) }); ; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(23); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(23); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(24); var forIn = __webpack_require__(25); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var forOwn = __webpack_require__(15); var isPlainObject = __webpack_require__(26); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var slice = __webpack_require__(11); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var isPrimitive = __webpack_require__(27); /** * get "nested" object property */ function get(obj, prop){ var parts = prop.split('.'), last = parts.pop(); while (prop = parts.shift()) { obj = obj[prop]; if (obj == null) return; } return obj[last]; } module.exports = get; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var namespace = __webpack_require__(28); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); var camelCase = __webpack_require__(30); var upperCase = __webpack_require__(21); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(process, global, module) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if ("function" === 'function' && __webpack_require__(51)['amd']) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return es6$promise$umd$$ES6Promise; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(50), (function() { return this; }()), __webpack_require__(52)(module))) /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(24); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the object is a primitive */ function isPrimitive(value) { // Using switch fallthrough because it's simple to read and is // generally fast: http://jsperf.com/testing-value-is-primitive/5 switch (typeof value) { case "string": case "number": case "boolean": return true; } return value == null; } module.exports = isPrimitive; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var forEach = __webpack_require__(10); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); var replaceAccents = __webpack_require__(53); var removeNonWord = __webpack_require__(54); var upperCase = __webpack_require__(21); var lowerCase = __webpack_require__(55); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; module.exports = defineResource; /*jshint evil:true, loopfunc:true*/ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var Resource = function Resource(options) { _classCallCheck(this, Resource); DSUtils.deepMixIn(this, options); if ("endpoint" in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } }; var instanceMethods = ["compute", "refresh", "save", "update", "destroy", "loadRelations", "changeHistory", "changes", "hasChanges", "lastModified", "lastSaved", "link", "linkInverse", "previous", "unlinkInverse"]; function defineResource(definition) { var _this = this; var definitions = _this.defs; if (DSUtils._s(definition)) { definition = { name: definition.replace(/\s/gi, "") }; } if (!DSUtils._o(definition)) { throw DSUtils._oErr("definition"); } else if (!DSUtils._s(definition.name)) { throw new DSErrors.IA("\"name\" must be a string!"); } else if (_this.s[definition.name]) { throw new DSErrors.R("" + definition.name + " is already registered!"); } try { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); var def = definitions[definition.name]; // alias name, shaves 0.08 kb off the minified build def.n = def.name; if (!DSUtils._s(def.idAttribute)) { throw new DSErrors.IA("\"idAttribute\" must be a string!"); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils._a(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.n; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; def.parentField = relation.localField; } }); }); } if (typeof Object.freeze === "function") { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getResource = function (resourceName) { return _this.defs[resourceName]; }; def.getEndpoint = function (id, options) { options.params = options.params || {}; var item = undefined; var parentKey = def.parentKey; var endpoint = options.hasOwnProperty("endpoint") ? options.endpoint : def.endpoint; var parentField = def.parentField; var parentDef = definitions[def.parent]; var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (DSUtils._sn(id)) { item = def.get(id); } else if (DSUtils._o(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { var _ret = (function () { delete options.endpoint; var _options = {}; DSUtils.forOwn(options, function (value, key) { _options[key] = value; }); return { v: DSUtils.makePath(parentDef.getEndpoint(parentId, DSUtils._(parentDef, _options)), parentId, endpoint) }; })(); if (typeof _ret === "object") return _ret.v; } else { return endpoint; } } }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource var _class = def["class"] = DSUtils.pascalCase(def.name); try { if (typeof def.useClass === "function") { eval("function " + _class + "() { def.useClass.call(this); }"); def[_class] = eval(_class); def[_class].prototype = (function (proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval("function " + _class + "() {}"); def[_class] = eval(_class); } } catch (e) { def[_class] = function () {}; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[_class].prototype, def.methods); } def[_class].prototype.set = function (key, value) { DSUtils.set(this, key, value); var observer = _this.s[def.n].observers[this[def.idAttribute]]; if (observer && !DSUtils.observe.hasObjectObserve) { observer.deliver(); } else { _this.compute(def.n, this); } return this; }; def[_class].prototype.get = function (key) { return DSUtils.get(this, key); }; // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { def.errorFn("Computed property \"" + field + "\" conflicts with previously defined prototype method!"); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(","); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { def.errorFn("Use the computed property array syntax for compatibility with minified code!"); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.n, definition.schema); if (!definition.hasOwnProperty("validate")) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[_class].prototype["DS" + DSUtils.pascalCase(name)] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this[def.idAttribute] || this); args.unshift(def.n); return _this[name].apply(_this, args); }; }); def[_class].prototype.DSCreate = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this); args.unshift(def.n); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.s[def.n] = { collection: [], expiresHeap: new DSUtils.BinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { return _this.reap(def.n, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones var fns = ["registerAdapter", "getAdapter", "is"]; for (var key in _this) { if (typeof _this[key] === "function") { fns.push(key); } } DSUtils.forEach(fns, function (key) { var k = key; if (_this[k].shorthand !== false) { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(def.n); return _this[k].apply(_this, args); }; } else { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _this[k].apply(_this, args); }; } }); def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); DSUtils.forOwn(def.actions, function (action, name) { if (def[name] && !def.actions[name]) { throw new Error("Cannot override existing method \"" + name + "\"!"); } def[name] = function (options) { options = options || {}; var adapter = _this.getAdapter(action.adapter || "http"); var config = DSUtils.deepMixIn({}, action); if (!options.hasOwnProperty("endpoint") && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === "function") { config.url = options.getEndpoint(def, options); } else { config.url = DSUtils.makePath(options.basePath || adapter.defaults.basePath || def.basePath, def.getEndpoint(null, options), name); } config.method = config.method || "GET"; DSUtils.deepMixIn(config, options); return adapter.HTTP(config); }; }); // Mix-in events DSUtils.Events(def); return def; } catch (err) { delete definitions[definition.name]; delete _this.s[definition.name]; throw err; } } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { module.exports = eject; function eject(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { // jshint ignore:line item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { var _ret = (function () { if (options.notify) { definition.beforeEject(options, item); definition.emit("DS.beforeEject", definition, item); } _this.unlinkInverse(definition.n, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } if (!items.length) { toRemove.push(queryHash); } }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); definition.emit("DS.afterEject", definition, item); } return { v: item }; })(); if (typeof _ret === "object") { return _ret.v; } } } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { module.exports = ejectAll; function ejectAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; params = params || {}; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._o(params)) { throw DSUtils._oErr("params"); } var resource = _this.s[resourceName]; var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.n, params); var ids = []; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } else { delete resource.completedQueries[queryHash]; } DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); DSUtils.forEach(ids, function (id) { _this.eject(definition.n, id, options); }); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { module.exports = filter; function filter(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; if (!definition) { throw new _this.errors.NER(resourceName); } else if (params && !DSUtils._o(params)) { throw DSUtils._oErr("params"); } // Protect against null params = params || {}; options = DSUtils._(definition, options); var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; module.exports = inject; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); function _getReactFunction(DS, definition, resource) { var name = definition.n; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item = undefined; var innerId = oldValueFn && oldValueFn(definition.idAttribute) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { definition.errorFn("Doh! You just changed the primary key of an object! Your data for the \"" + name + "\" resource is now in an undefined (probably broken) state."); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected = undefined; if (DSUtils._a(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { (function () { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); })(); } if (!(idA in attrs)) { var error = new DSErrors.R("" + definition.n + ".inject: \"attrs\" must contain the property specified by \"idAttribute\"!"); options.errorFn(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.defs[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DSErrors.R("" + definition.n + " relation is defined but the resource is not!"); } if (DSUtils._a(toInject)) { (function () { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.s[relationName].index[toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = _this.inject(relationName, toInjectItem, options.orig()); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } }); attrs[def.localField] = items; })(); } else { if (toInject !== _this.s[relationName].index[toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options.orig()); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } } } }); var id = attrs[idA]; var item = _this.get(definition.n, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition["class"]]) { item = attrs; } else { item = new definition[definition["class"]](); } } else { item = {}; } DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); resource.previousAttributes[id] = DSUtils.copy(item); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(item); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); var timestamp = new Date().getTime(); resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { options.errorFn(err, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === "belongsTo" && injected[definition.idAttribute]) { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } else if (options.findHasMany && def.type === "hasMany" || options.findHasOne && def.type === "hasOne") { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var injected = undefined; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._o(attrs) && !DSUtils._a(attrs)) { throw new DSErrors.IA("" + resourceName + ".inject: \"attrs\" must be an object or an array!"); } var name = definition.n; options = DSUtils._(definition, options); if (options.notify) { options.beforeInject(options, attrs); definition.emit("DS.beforeInject", definition, attrs); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils._a(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); definition.emit("DS.afterInject", definition, injected); } return injected; } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { module.exports = link; function link(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } var params = {}; if (def.type === "belongsTo") { var _parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (_parent) { linked[def.localField] = _parent; } } else if (def.type === "hasMany") { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === "hasOne") { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkAll; function linkAll(resourceName, params, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } if (def.type === "belongsTo") { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === "hasMany") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === "hasOne") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkInverse; function linkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.n)) { return; } if (definition.n === relationName) { _this.linkAll(d.n, {}, [definition.n]); } }); }); }); } return linked; } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { module.exports = unlinkInverse; function unlinkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.n === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.s[def.name].collection, function (item) { if (def.type === "hasMany" && item[def.localField]) { (function () { var index = undefined; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); if (index !== undefined) { item[def.localField].splice(index, 1); } })(); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { module.exports = create; function create(resourceName, attrs, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; options = options || {}; attrs = attrs || {}; var rejectionError = undefined; if (!definition) { rejectionError = new _this.errors.NER(resourceName); } else if (!DSUtils._o(attrs)) { rejectionError = DSUtils._oErr("attrs"); } else { options = DSUtils._(definition, options); if (options.upsert && DSUtils._sn(attrs[definition.idAttribute])) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeCreate", definition, attrs); } return _this.getAdapter(options).create(definition, attrs, options); }).then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterCreate", definition, attrs); } if (options.cacheResponse) { var created = _this.inject(definition.n, attrs, options.orig()); var id = created[definition.idAttribute]; var resource = _this.s[resourceName]; resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroy; function destroy(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var item = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { item = _this.get(resourceName, id) || { id: id }; options = DSUtils._(definition, options); resolve(item); } }).then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeDestroy", definition, attrs); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }).then(function () { return options.afterDestroy.call(item, options, item); }).then(function (item) { if (options.notify) { definition.emit("DS.afterDestroy", definition, item); } _this.eject(resourceName, id); return id; })["catch"](function (err) { if (options && options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } throw err; }); } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroyAll; function destroyAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var ejected = undefined, toEject = undefined; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("attrs")); } else { options = DSUtils._(definition, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.beforeDestroy", definition, toEject); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.afterDestroy", definition, toEject); } return ejected || _this.ejectAll(resourceName, params); })["catch"](function (err) { if (options && options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } throw err; }); } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /* jshint -W082 */ module.exports = find; function find(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries && _this.get(resourceName, id)) { resolve(_this.get(resourceName, id)); } else { delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise = undefined; var strategy = options.findStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { var injected = _this.inject(resourceName, data, options.orig()); resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return injected; } else { return _this.createInstance(resourceName, data, options.orig()); } }); } return resource.pendingQueries[id]; } else { return item; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[id]; } throw err; }); } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { module.exports = findAll; /* jshint -W082 */ function processResults(data, resourceName, queryHash, options) { var _this = this; var DSUtils = _this.utils; var resource = _this.s[resourceName]; var idAttribute = _this.defs[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options.orig()); // Make sure each object is added to completedQueries if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (item) { if (item) { var id = item[idAttribute]; if (id) { resource.completedQueries[id] = date; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); } } }); } else { options.errorFn("response is expected to be an array!"); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var queryHash = undefined; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.defs[resourceName]) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("params")); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { resolve(_this.filter(resourceName, params, options.orig())); } else { resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise = undefined; var strategy = options.findAllStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options); resource.queryData[queryHash].$$injected = true; return resource.queryData[queryHash]; } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options.orig()); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } throw err; }); } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { module.exports = loadRelations; function loadRelations(resourceName, instance, relations, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils._sn(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils._s(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(instance)) { reject(new DSErrors.IA("\"instance(id)\" must be a string, number or object!")); } else if (!DSUtils._a(relations)) { reject(new DSErrors.IA("\"relations\" must be a string or an array!")); } else { (function () { var _options = DSUtils._(definition, options); if (!_options.hasOwnProperty("findBelongsTo")) { _options.findBelongsTo = true; } if (!_options.hasOwnProperty("findHasMany")) { _options.findHasMany = true; } var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); if (DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) { var task = undefined; var params = {}; if (__options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { "==": instance[definition.idAttribute] }; } if (def.type === "hasMany" && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()); } else if (def.type === "hasOne") { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], __options.orig()); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); resolve(tasks); })(); } }).then(function (tasks) { return DSUtils.Promise.all(tasks); }).then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { module.exports = reap; function reap(resourceName, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty("notify")) { options.notify = false; } var items = []; var now = new Date().getTime(); var expiredItem = undefined; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { definition.beforeReap(options, items); definition.emit("DS.beforeReap", definition, items); } if (options.reapAction === "inject") { (function () { var timestamp = new Date().getTime(); DSUtils.forEach(items, function (item) { resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); }); })(); } else if (options.reapAction === "eject") { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === "refresh") { var _ret2 = (function () { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return { v: DSUtils.Promise.all(tasks) }; })(); if (typeof _ret2 === "object") return _ret2.v; } return items; }).then(function (items) { if (options.isInterval || options.notify) { definition.afterReap(options, items); definition.emit("DS.afterReap", definition, items); } return items; }); } /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { module.exports = save; function save(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var item = undefined; var noChanges = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R("id \"" + id + "\" not found in cache!")); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } if (options.changesOnly) { var resource = _this.s[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return noChanges = true; return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (noChanges) { return attrs; } else if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { module.exports = update; function update(resourceName, id, attrs, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { module.exports = updateAll; function updateAll(resourceName, attrs, params, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (data) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } var origOptions = options.orig(); if (options.cacheResponse) { var _ret = (function () { var injected = _this.inject(definition.n, data, origOptions); var resource = _this.s[resourceName]; DSUtils.forEach(injected, function (i) { var id = i[definition.idAttribute]; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(i); } }); return { v: injected }; })(); if (typeof _ret === "object") return _ret.v; } else { var _ret2 = (function () { var instances = []; DSUtils.forEach(data, function (item) { instances.push(_this.createInstance(resourceName, item, origOptions)); }); return { v: instances }; })(); if (typeof _ret2 === "object") return _ret2.v; } }); } /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { 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'); }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; /***/ } /******/ ]) });
/** * @license AngularJS v0.10.2 * (c) 2010-2011 AngularJS http://angularjs.org * License: MIT */ 'use strict'; (function(window, document, undefined){ //////////////////////////////////// if (typeof document.getAttribute == $undefined) document.getAttribute = function() {}; /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function (string){ return isString(string) ? string.toLowerCase() : string; }; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function (string){ return isString(string) ? string.toUpperCase() : string; }; var manualLowercase = function (s) { return isString(s) ? s.replace(/[A-Z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) | 32); }) : s; }; var manualUppercase = function (s) { return isString(s) ? s.replace(/[a-z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) & ~32); }) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) { return String.fromCharCode(code); } var _undefined = undefined, _null = null, $$scope = '$scope', $$validate = '$validate', $angular = 'angular', $array = 'array', $boolean = 'boolean', $console = 'console', $date = 'date', $length = 'length', $name = 'name', $noop = 'noop', $null = 'null', $number = 'number', $object = 'object', $string = 'string', $value = 'value', $selected = 'selected', $undefined = 'undefined', NG_EXCEPTION = 'ng-exception', NG_VALIDATION_ERROR = 'ng-validation-error', NOOP = 'noop', Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, error = window[$console] ? bind(window[$console], window[$console]['error'] || noop) : noop, /** @name angular */ angular = window[$angular] || (window[$angular] = {}), /** @name angular.markup */ angularTextMarkup = extensionMap(angular, 'markup'), /** @name angular.attrMarkup */ angularAttrMarkup = extensionMap(angular, 'attrMarkup'), /** @name angular.directive */ angularDirective = extensionMap(angular, 'directive'), /** @name angular.widget */ angularWidget = extensionMap(angular, 'widget', lowercase), /** @name angular.validator */ angularValidator = extensionMap(angular, 'validator'), /** @name angular.fileter */ angularFilter = extensionMap(angular, 'filter'), /** @name angular.formatter */ angularFormatter = extensionMap(angular, 'formatter'), /** @name angular.service */ angularService = extensionMap(angular, 'service'), angularCallbacks = extensionMap(angular, 'callbacks'), nodeName_, rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/, uid = ['0', '0', '0'], DATE_ISOSTRING_LN = 24; /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {function()} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != $length && key != $name && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) iterator.call(context, obj[key], key); } } return obj; } function forEachSorted(obj, iterator, context) { var keys = []; for (var key in obj) keys.push(key); keys.sort(); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } /** * @description * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function inherit(parent, extra) { return extend(new (extend(function(){}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} function valueFn(value) {return function(){ return value; };} function extensionMap(angular, name, transform) { var extPoint; return angular[name] || (extPoint = angular[name] = function (name, fn, prop){ name = (transform || identity)(name); if (isDefined(fn)) { extPoint[name] = extend(fn, prop || {}); } return extPoint[name]; }); } /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){ return typeof value == $undefined; } /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){ return typeof value != $undefined; } /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){ return value!=null && typeof value == $object;} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){ return typeof value == $string;} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){ return typeof value == $number;} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return value instanceof Date; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return value instanceof Array; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){ return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isBoolean(value) { return typeof value == $boolean; } function isTextNode(node) { return nodeName_(node) == '#text'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } /** * HTML class which is the only class which can be used in ng:bind to inline HTML for security * reasons. * * @constructor * @param html raw (unsafe) html * @param {string=} option If set to 'usafe', get method will return raw (unsafe/unsanitized) html */ function HTML(html, option) { this.html = html; this.get = lowercase(option) == 'unsafe' ? valueFn(html) : function htmlSanitize() { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function isVisible(element) { var rect = element[0].getBoundingClientRect(), width = (rect.width || (rect.right||0 - rect.left||0)), height = (rect.height || (rect.bottom||0 - rect.top||0)); return width>0 && height>0; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @ngdoc function * @name angular.Object.size * @function * * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. * * @example * <doc:example> * <doc:source> * <script> * function SizeCtrl() { * this.fooStringLength = angular.Object.size('foo'); * } * </script> * <div ng:controller="SizeCtrl"> * Number of items in array: {{ [1,2].$size() }}<br/> * Number of items in object: {{ {a:1, b:2, c:3}.$size() }}<br/> * String length: {{fooStringLength}} * </div> * </doc:source> * <doc:scenario> * it('should print correct sizes for an array and an object', function() { * expect(binding('[1,2].$size()')).toBe('2'); * expect(binding('{a:1, b:2, c:3}.$size()')).toBe('3'); * expect(binding('fooStringLength')).toBe('3'); * }); * </doc:scenario> * </doc:example> */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return true; } return false; } function indexOf(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Alias for {@link angular.Object.copy} */ /** * @ngdoc function * @name angular.Object.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. * * @example * <doc:example> * <doc:source> Salutation: <input type="text" name="master.salutation" value="Hello" /><br/> Name: <input type="text" name="master.name" value="world"/><br/> <button ng:click="form = master.$copy()">copy</button> <hr/> The master object is <span ng:hide="master.$equals(form)">NOT</span> equal to the form object. <pre>master={{master}}</pre> <pre>form={{form}}</pre> * </doc:source> * <doc:scenario> it('should print that initialy the form object is NOT equal to master', function() { expect(element('.doc-example-live input[name="master.salutation"]').val()).toBe('Hello'); expect(element('.doc-example-live input[name="master.name"]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); it('should make form and master equal when the copy button is clicked', function() { element('.doc-example-live button').click(); expect(element('.doc-example-live span').css('display')).toBe('none'); }); * </doc:scenario> * </doc:example> */ function copy(source, destination){ if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * @ngdoc function * @name angular.equals * @function * * @description * Alias for {@link angular.Object.equals} */ /** * @ngdoc function * @name angular.Object.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * During a property comparision, properties of `function` type and properties with names * that begin with `$` are ignored. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. * * @example * <doc:example> * <doc:source> Salutation: <input type="text" name="greeting.salutation" value="Hello" /><br/> Name: <input type="text" name="greeting.name" value="world"/><br/> <hr/> The <code>greeting</code> object is <span ng:hide="greeting.$equals({salutation:'Hello', name:'world'})">NOT</span> equal to <code>{salutation:'Hello', name:'world'}</code>. <pre>greeting={{greeting}}</pre> * </doc:source> * <doc:scenario> it('should print that initialy greeting is equal to the hardcoded value object', function() { expect(element('.doc-example-live input[name="greeting.salutation"]').val()).toBe('Hello'); expect(element('.doc-example-live input[name="greeting.name"]').val()).toBe('world'); expect(element('.doc-example-live span').css('display')).toBe('none'); }); it('should say that the objects are not equal when the form is modified', function() { input('greeting.name').enter('kitty'); expect(element('.doc-example-live span').css('display')).toBe('inline'); }); * </doc:scenario> * </doc:example> */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2 && t1 == 'object') { if (o1 instanceof Array) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else { keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } return false; } function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { node.innerText = html; } else { node.textContent = html; } } else { node.innerHTML = html; } } function isRenderableElement(element) { var name = element && element[0] && element[0].nodeName; return name && name.charAt(0) != '#' && !includes(['TR', 'COL', 'COLGROUP', 'TBODY', 'THEAD', 'TFOOT'], name); } function elementError(element, type, error) { var parent; while (!isRenderableElement(element)) { parent = element.parent(); if (parent.length) { element = element.parent(); } else { return; } } if (element[0]['$NG_ERROR'] !== error) { element[0]['$NG_ERROR'] = error; if (error) { element.addClass(type); element.attr(type, error.message || error); } else { element.removeClass(type); element.removeAttr(type); } } } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** @name angular.compile */ function compile(element) { return new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget) .compile(element); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @ngdoc directive * @name angular.directive.ng:autobind * @element script * * @TODO ng:autobind is not a directive!! it should be documented as bootstrap parameter in a * separate bootstrap section. * @TODO rename to ng:autobind to ng:autoboot * * @description * Technically, ng:autobind is not a directive; it is an Angular bootstrap parameter that can act * as a directive. It must exist in the script used to boot Angular and can be used only one time. * For details on bootstrapping Angular, see {@link guide/dev_guide.bootstrap Initializing Angular} * in the Angular Developer Guide. * * `ng:autobind` with no parameters tells Angular to compile and manage the whole page. * * `ng:autobind="[root element ID]"` tells Angular to compile and manage part of the document, * starting at "root element ID". * */ function angularInit(config, document){ var autobind = config.autobind; if (autobind) { var element = isString(autobind) ? document.getElementById(autobind) : document, scope = compile(element)(createScope()), $browser = scope.$service('$browser'); if (config.css) $browser.addCss(config.base_url + config.css); else if(msie<8) $browser.addJs(config.ie_compat, config.ie_compat_id); scope.$apply(); } } function angularJsConfig(document, config) { bindJQuery(); var scripts = document.getElementsByTagName("script"), match; config = extend({ ie_compat_id: 'ng-ie-compat' }, config); for(var j = 0; j < scripts.length; j++) { match = (scripts[j].src || "").match(rngScript); if (match) { config.base_url = match[1]; config.ie_compat = match[1] + 'angular-ie-compat' + (match[2] || '') + '.js'; extend(config, parseKeyValue(match[6])); eachAttribute(jqLite(scripts[j]), function(value, name){ if (/^ng:/.exec(name)) { name = name.substring(3).replace(/-/g, '_'); value = value || true; config[name] = value; } }); } } return config; } function bindJQuery(){ // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope }); } else { jqLite = jqLiteWrap; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { var error = new Error("Argument '" + (name||'?') + "' is " + (reason || "required")); throw error; } } function assertArgFn(arg, name) { assertArg(isFunction(arg), name, 'not a function, got ' + (typeof arg == 'object' ? arg.constructor.name : typeof arg)); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '0.10.2', // all of these placeholder strings will be replaced by rake's major: 0, // compile task minor: 10, dot: 2, codeName: 'sneaky-seagull' }; var array = [].constructor; /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { var buf = []; toJsonArray(buf, obj, pretty ? "\n " : null, []); return buf.join(''); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @param {boolean} [useNative=false] Use native JSON parser, if available. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json, useNative) { if (!isString(json)) return json; var obj; try { if (useNative && window.JSON && window.JSON.parse) { obj = JSON.parse(json); return transformDates(obj); } return parser(json, true).primary()(); } catch (e) { error("fromJson error: ", json, e); throw e; } // TODO make forEach optionally recursive and remove this function function transformDates(obj) { if (isString(obj) && obj.length === DATE_ISOSTRING_LN) { return angularString.toDate(obj); } else if (isArray(obj) || isObject(obj)) { forEach(obj, function(val, name) { obj[name] = transformDates(val); }); } return obj; } } angular.toJson = toJson; angular.fromJson = fromJson; function toJsonArray(buf, obj, pretty, stack) { if (isObject(obj)) { if (obj === window) { buf.push('WINDOW'); return; } if (obj === document) { buf.push('DOCUMENT'); return; } if (includes(stack, obj)) { buf.push('RECURSION'); return; } stack.push(obj); } if (obj === null) { buf.push($null); } else if (obj instanceof RegExp) { buf.push(angularString.quoteUnicode(obj.toString())); } else if (isFunction(obj)) { return; } else if (isBoolean(obj)) { buf.push('' + obj); } else if (isNumber(obj)) { if (isNaN(obj)) { buf.push($null); } else { buf.push('' + obj); } } else if (isString(obj)) { return buf.push(angularString.quoteUnicode(obj)); } else if (isObject(obj)) { if (isArray(obj)) { buf.push("["); var len = obj.length; var sep = false; for(var i=0; i<len; i++) { var item = obj[i]; if (sep) buf.push(","); if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) { buf.push($null); } else { toJsonArray(buf, item, pretty, stack); } sep = true; } buf.push("]"); } else if (isElement(obj)) { // TODO(misko): maybe in dev mode have a better error reporting? buf.push('DOM_ELEMENT'); } else if (isDate(obj)) { buf.push(angularString.quoteUnicode(angular.Date.toString(obj))); } else { buf.push("{"); if (pretty) buf.push(pretty); var comma = false; var childPretty = pretty ? pretty + " " : false; var keys = []; for(var k in obj) { if (obj.hasOwnProperty(k) && obj[k] !== undefined) { keys.push(k); } } keys.sort(); for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) { var key = keys[keyIndex]; var value = obj[key]; if (!isFunction(value)) { if (comma) { buf.push(","); if (pretty) buf.push(pretty); } buf.push(angularString.quote(key)); buf.push(":"); toJsonArray(buf, value, childPretty, stack); comma = true; } } buf.push("}"); } } if (isObject(obj)) { stack.pop(); } } /** * Template provides directions an how to bind to a given element. * It contains a list of init functions which need to be called to * bind to a new instance of elements. It also provides a list * of child paths which contain child templates */ function Template() { this.paths = []; this.children = []; this.linkFns = []; this.newScope = false; } Template.prototype = { link: function(element, scope) { var childScope = scope; if (this.newScope) { childScope = isFunction(this.newScope) ? scope.$new(this.newScope(scope)) : scope.$new(); element.data($$scope, childScope); } forEach(this.linkFns, function(fn) { try { childScope.$service.invoke(childScope, fn, [element]); } catch (e) { childScope.$service('$exceptionHandler')(e); } }); var i, childNodes = element[0].childNodes, children = this.children, paths = this.paths, length = paths.length; for (i = 0; i < length; i++) { children[i].link(jqLite(childNodes[paths[i]]), childScope); } }, addLinkFn:function(linkingFn) { if (linkingFn) { if (!linkingFn.$inject) linkingFn.$inject = []; this.linkFns.push(linkingFn); } }, addChild: function(index, template) { if (template) { this.paths.push(index); this.children.push(template); } }, empty: function() { return this.linkFns.length === 0 && this.paths.length === 0; } }; /////////////////////////////////// //Compiler ////////////////////////////////// /** * @workInProgress * @ngdoc function * @name angular.compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link angular.scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link angular.markup markup}, {@link angular.attrMarkup attrMarkup}, * {@link angular.widget widgets}, and {@link angular.directive directives}. For each match it * executes corresponding markup, attrMarkup, widget or directive template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link angular.widget.@ng:repeat repeater} many-times, in which case each call results in a view * that is a DOM clone of the original template. * <pre> // compile the entire window.document and give me the scope bound to this template. var rootScope = angular.compile(window.document)(); // compile a piece of html var rootScope2 = angular.compile('<div ng:click="clicked = true">click me</div>')(); // compile a piece of html and retain reference to both the dom and scope var template = angular.element('<div ng:click="clicked = true">click me</div>'), scope = angular.compile(template)(); // at this point template was transformed into a view </pre> * * * @param {string|DOMElement} element Element or HTML to compile into a template function. * @returns {function([scope][, cloneAttachFn])} a template function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link angular.scope Scope} to bind to. If none specified, then a new * root scope is created. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br/> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the template function returns the scope to which the element is bound to. It is either * the same scope as the one passed into the template function, or if none were provided it's the * newly create scope. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var view = angular.element('<p>{{total}}</p>'), * scope = angular.compile(view)(); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var original = angular.element('<p>{{total}}</p>'), * scope = someParentScope.$new(), * clone; * * angular.compile(original)(scope, function(clonedElement, scope) { * clone = clonedElement; * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * Compiler Methods For Widgets and Directives: * * The following methods are available for use when you write your own widgets, directives, * and markup. (Recall that the compile function's this is a reference to the compiler.) * * `compile(element)` - returns linker - * Invoke a new instance of the compiler to compile a DOM element and return a linker function. * You can apply the linker function to the original element or a clone of the original element. * The linker function returns a scope. * * * `comment(commentText)` - returns element - Create a comment element. * * * `element(elementName)` - returns element - Create an element by name. * * * `text(text)` - returns element - Create a text element. * * * `descend([set])` - returns descend state (true or false). Get or set the current descend * state. If true the compiler will descend to children elements. * * * `directives([set])` - returns directive state (true or false). Get or set the current * directives processing state. The compiler will process directives only when directives set to * true. * * For information on how the compiler works, see the * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide. */ function Compiler(markup, attrMarkup, directives, widgets){ this.markup = markup; this.attrMarkup = attrMarkup; this.directives = directives; this.widgets = widgets; } Compiler.prototype = { compile: function(templateElement) { templateElement = jqLite(templateElement); var index = 0, template, parent = templateElement.parent(); if (templateElement.length > 1) { // https://github.com/angular/angular.js/issues/338 throw Error("Cannot compile multiple element roots: " + jqLite('<div>').append(templateElement.clone()).html()); } if (parent && parent[0]) { parent = parent[0]; for(var i = 0; i < parent.childNodes.length; i++) { if (parent.childNodes[i] == templateElement[0]) { index = i; } } } template = this.templatize(templateElement, index) || new Template(); return function(scope, cloneConnectFn){ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var element = cloneConnectFn ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!! : templateElement; scope = scope || createScope(); element.data($$scope, scope); scope.$element = element; (cloneConnectFn||noop)(element, scope); template.link(element, scope); return scope; }; }, templatize: function(element, elementIndex){ var self = this, widget, fn, directiveFns = self.directives, descend = true, directives = true, elementName = nodeName_(element), elementNamespace = elementName.indexOf(':') > 0 ? lowercase(elementName).replace(':', '-') : '', template, selfApi = { compile: bind(self, self.compile), descend: function(value){ if(isDefined(value)) descend = value; return descend;}, directives: function(value){ if(isDefined(value)) directives = value; return directives;}, scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;} }; element.addClass(elementNamespace); template = new Template(); eachAttribute(element, function(value, name){ if (!widget) { if ((widget = self.widgets('@' + name))) { element.addClass('ng-attr-widget'); widget = bind(selfApi, widget, value, element); } } }); if (!widget) { if ((widget = self.widgets(elementName))) { if (elementNamespace) element.addClass('ng-widget'); widget = bind(selfApi, widget, element); } } if (widget) { descend = false; directives = false; var parent = element.parent(); template.addLinkFn(widget.call(selfApi, element)); if (parent && parent[0]) { element = jqLite(parent[0].childNodes[elementIndex]); } } if (descend){ // process markup for text nodes only for(var i=0, child=element[0].childNodes; i<child.length; i++) { if (isTextNode(child[i])) { forEach(self.markup, function(markup){ if (i<child.length) { var textNode = jqLite(child[i]); markup.call(selfApi, textNode.text(), textNode, element); } }); } } } if (directives) { // Process attributes/directives eachAttribute(element, function(value, name){ forEach(self.attrMarkup, function(markup){ markup.call(selfApi, value, name, element); }); }); eachAttribute(element, function(value, name){ fn = directiveFns[name]; if (fn) { element.addClass('ng-directive'); template.addLinkFn((directiveFns[name]).call(selfApi, value, element)); } }); } // Process non text child nodes if (descend) { eachNode(element, function(child, i){ template.addChild(i, self.templatize(child, i)); }); } return template.empty() ? null : template; } }; function eachNode(element, fn){ var i, chldNodes = element[0].childNodes || [], chld; for (i = 0; i < chldNodes.length; i++) { if(!isTextNode(chld = chldNodes[i])) { fn(jqLite(chld), i); } } } function eachAttribute(element, fn){ var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {}; for (i = 0; i < attrs.length; i++) { attr = attrs[i]; name = attr.name; value = attr.value; if (msie && name == 'href') { value = decodeURIComponent(element[0].getAttribute(name, 2)); } attrValue[name] = value; } forEachSorted(attrValue, fn); } /** * DESIGN NOTES * * The design decisions behind the scope ware heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive from speed as well as memory: * - no closures, instead ups prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the begging (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using array would be slow since inserts in meddle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ function createScope(providers, instanceCache) { var scope = new Scope(); (scope.$service = createInjector(scope, providers, instanceCache)).eager(); return scope; } /** * @ngdoc function * @name angular.scope * * @description * A root scope can be created by calling {@link angular.scope angular.scope()}. Child scopes * are created using the {@link angular.scope.$new $new()} method. * (Most scopes are created automatically when compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> var scope = angular.scope(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function(){ this.greeting = this.salutation + ' ' + this.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = angular.scope(); var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * # Dependency Injection * See {@link guide/dev_guide.di dependency injection}. * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link angular.service}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this.$destructor = noop; this['this'] = this.$root = this; this.$$asyncQueue = []; this.$$listeners = {}; } /** * @ngdoc property * @name angular.scope.$id * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ /** * @ngdoc property * @name angular.scope.$service * @function * * @description * Provides reference to an instance of {@link angular.injector injector} which can be used to * retrieve {@link angular.service services}. In general the use of this api is discouraged, * in favor of proper {@link guide/dev_guide.di dependency injection}. * * @returns {function} {@link angular.injector injector} */ /** * @ngdoc property * @name angular.scope.$root * @returns {Scope} The root scope of the current scope hierarchy. */ /** * @ngdoc property * @name angular.scope.$parent * @returns {Scope} The parent scope of the current scope. */ Scope.prototype = { /** * @ngdoc function * @name angular.scope.$new * @function * * @description * Creates a new child {@link angular.scope scope}. The new scope can optionally behave as a * controller. The parent scope will propagate the {@link angular.scope.$digest $digest()} and * {@link angular.scope.$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link angular.scope.$destroy $destroy()}. * * {@link angular.scope.$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @param {function()=} Class Constructor function which the scope should be applied to the scope. * @param {...*} curryArguments Any additional arguments which are curried into the constructor. * See {@link guide/dev_guide.di dependency injection}. * @returns {Object} The newly created child scope. * */ $new: function(Class, curryArguments) { var Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. var child; Child.prototype = this; child = new Child(); child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$id = nextUid(); child.$$asyncQueue = []; child.$$phase = child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } // short circuit if we have no class if (Class) { // can't use forEach, we need speed! var ClassPrototype = Class.prototype; for(var key in ClassPrototype) { child[key] = bind(child, ClassPrototype[key]); } this.$service.invoke(child, Class, curryArguments); } return child; }, /** * @ngdoc function * @name angular.scope.$watch * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link angular.scope.$digest $digest()} and * should return the value which will be watched. (Since {@link angular.scope.$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link angular.scope.$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression' are not equal. The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 100 to prevent infinity loop deadlock. * * * If you want to be notified whenever {@link angular.scope.$digest $digest} is called, * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`, * can execute multiple times per {@link angular.scope.$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * * # Example <pre> var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(scope, newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link angular.scope.$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(scope, newValue, oldValue)`: called with current `scope` an previous and * current values as parameters. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener) { var scope = this, get = compileToFn(watchExp, 'watch'), listenFn = compileToFn(listener || noop, 'listener'), array = scope.$$watchers, watcher = { fn: listenFn, last: Number.NaN, // NaN !== NaN. We used this to force $watch to fire on first run. get: get }; if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { angularArray.remove(array, watcher); }; }, /** * @ngdoc function * @name angular.scope.$digest * @function * * @description * Process all of the {@link angular.scope.$watch watchers} of the current scope and its children. * Because a {@link angular.scope.$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link angular.scope.$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100. * * Usually you don't call `$digest()` directly in * {@link angular.directive.ng:controller controllers} or in {@link angular.directive directives}. * Instead a call to {@link angular.scope.$apply $apply()} (typically from within a * {@link angular.directive directive}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link angular.scope.$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example <pre> var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$digest('name', function(scope, newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue, length, dirty, ttl = 100, next, current, target = this; if (target.$$phase) { throw Error(target.$$phase + ' already in progress'); } do { dirty = false; current = target; do { current.$$phase = '$digest'; asyncQueue = current.$$asyncQueue; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { current.$service('$exceptionHandler')(e); } } if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last)) { dirty = true; watch.fn(current, watch.last = copy(value), last); } } catch (e) { current.$service('$exceptionHandler')(e); } } } current.$$phase = null; // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(!(ttl--)) { throw Error('100 $digest() iterations reached. Aborting!'); } } while (dirty); }, /** * @ngdoc function * @name angular.scope.$destroy * @function * * @description * Remove the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link angular.scope.$digest $digest()} will no longer propagate to the current * scope and its children. Removal also implies that the current scope is eligible for garbage * collection. * * The destructing scope emits an `$destroy` {@link angular.scope.$emit event}. * * The `$destroy()` is usually used by directives such as * {@link angular.widget.@ng:repeat ng:repeat} for managing the unrolling of the loop. * */ $destroy: function() { if (this.$root == this) return; // we can't remove the root node; this.$emit('$destroy'); var parent = this.$parent; if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; }, /** * @ngdoc function * @name angular.scope.$eval * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating engular expressions. * * # Example <pre> var scope = angular.scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr) { var fn = isString(expr) ? expressionCompile(expr) : expr || noop; return fn(this); }, /** * @ngdoc function * @name angular.scope.$evalAsync * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link angular.scope.$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link angular.service.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name angular.scope.$apply * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link angular.service.$exceptionHandler exception handling}, * {@link angular.scope.$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/dev_guide.expressions expression} is executed using the * {@link angular.scope.$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link angular.service.$exceptionHandler $exceptionHandler} service. * 3. The {@link angular.scope.$watch watch} listeners are fired immediately after the expression * was executed using the {@link angular.scope.$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { return this.$eval(expr); } catch (e) { this.$service('$exceptionHandler')(e); } finally { this.$root.$digest(); } }, /** * @ngdoc function * @name angular.scope.$on * @function * * @description * Listen on events of a given type. See {@link angular.scope.$emit $emit} for discussion of * event life cycle. * * @param {string} name Event name to listen on. * @param {function(event)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. * * The event listener function format is: `function(event)`. The `event` object passed into the * listener has the following attributes * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - {Scope}: the current scope which is handling the event. * - `name` - {string}: Name of the event. * - `cancel` - {function=}: calling `cancel` function will cancel further event propagation * (available only for events that were `$emit`-ed). */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { angularArray.remove(namedListeners, listener); }; }, /** * @ngdoc function * @name angular.scope.$emit * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link angular.scope.$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emmited from the {@link angular.scope.$on listeners} will be passed * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. */ $emit: function(name, args) { var empty = [], namedListeners, canceled = false, scope = this, event = { name: name, targetScope: scope, cancel: function(){canceled = true;} }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { try { namedListeners[i].apply(null, listenerArgs); if (canceled) return; } catch (e) { scope.$service('$exceptionHandler')(e); } } //traverse upwards scope = scope.$parent; } while (scope); }, /** * @ngdoc function * @name angular.scope.$broadcast * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link angular.scope.$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emmited from the {@link angular.scope.$on listeners} will be passed * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target }, listenerArgs = concat([event], arguments, 1); //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; forEach(current.$$listeners[name], function(listener) { try { listener.apply(null, listenerArgs); } catch(e) { current.$service('$exceptionHandler')(e); } }); // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); } }; function compileToFn(exp, name) { var fn = isString(exp) ? expressionCompile(exp) : exp; assertArgFn(fn, name); return fn; } /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/dev_guide.di dependency injection}). * * Angular creates an injector automatically for the root scope and it is available as the * {@link angular.scope.$service $service} property. Creating an injector doesn't automatically * create all of the `$eager` {@link angular.service services}. You have to call `injector.eager()` * to initialize them. * * @param {Object=} [factoryScope={}] The `this` for the service factory function. * @param {Object.<string, function()>=} [factories=angular.service] Map of the service factory * functions. * @param {Object.<string, function()>=} [instanceCache={}] Place where instances of services are * saved for reuse. Can also be used to override services specified by `serviceFactory` * (useful in tests). * @returns {function()} Injector function: * * * `injector(serviceName)`: * * `serviceName` - `{string=}` - Name of the service to retrieve. * * The injector function also has these properties: * * * An `invoke` property which can be used to invoke methods with dependency-injected arguments. * `injector.invoke(self, fn, curryArgs)` * * `self` - The "`this`" to be used when invoking the function. * * `fn` - The function to be invoked. The function may have the `$inject` property that * lists the set of arguments which should be auto-injected. * (see {@link guide/dev_guide.di dependency injection}). * * `curryArgs(array)` - Optional array of arguments to pass to the function * invocation after the injection arguments (also known as curry arguments or currying). * * An `eager` property which is used to initialize the eager services. * `injector.eager()` */ function createInjector(factoryScope, factories, instanceCache) { factories = factories || angularService; instanceCache = instanceCache || {}; factoryScope = factoryScope || {}; injector.invoke = invoke; injector.eager = function(){ forEach(factories, function(factory, name){ if (factory.$eager) injector(name); if (factory.$creation) throw new Error("Failed to register service '" + name + "': $creation property is unsupported. Use $eager:true or see release notes."); }); }; return injector; function injector(value){ if (!(value in instanceCache)) { var factory = factories[value]; if (!factory) throw Error("Unknown provider for '"+value+"'."); instanceCache[value] = invoke(factoryScope, factory); } return instanceCache[value]; } function invoke(self, fn, args){ args = args || []; var injectNames = injectionArgs(fn); var i = injectNames.length; while(i--) { args.unshift(injector(injectNames[i])); } return fn.apply(self, args); } } /** * THIS IS NOT PUBLIC DOC YET! * * @name angular.annotate * @function * * @description * Annotate the function with injection arguments. This is equivalent to setting the `$inject` * property as described in {@link guide.di dependency injection}. * * <pre> * var MyController = angular.annotate('$location', function($location){ ... }); * </pre> * * is the same as * * <pre> * var MyController = function($location){ ... }; * MyController.$inject = ['$location']; * </pre> * * @param {String|Array} serviceName... zero or more service names to inject into the * `annotatedFunction`. * @param {function} annotatedFunction function to annotate with `$inject` * functions. * @returns {function} `annotatedFunction` */ function annotate(services, fn) { if (services instanceof Array) { fn.$inject = services; return fn; } else { var i = 0, length = arguments.length - 1, // last one is the destination function $inject = arguments[length].$inject = []; for (; i < length; i++) { $inject.push(arguments[i]); } return arguments[length]; // return the last one } } function angularServiceInject(name, fn, inject, eager) { angularService(name, fn, {$inject:inject, $eager:eager}); } /** * @returns the $inject property of function. If not found the * the $inject is computed by looking at the toString of function and * extracting all arguments which and assuming that they are the * injection names. */ var FN_ARGS = /^function\s*[^\(]*\(([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(.+?)\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function injectionArgs(fn) { assertArgFn(fn); if (!fn.$inject) { var args = fn.$inject = []; var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, name){ args.push(name); }); }); } return fn.$inject; } var OPERATORS = { 'null':function(self){return null;}, 'true':function(self){return true;}, 'false':function(self){return false;}, $undefined:noop, '+':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, a,b){return a(self)*b(self);}, '/':function(self, a,b){return a(self)/b(self);}, '%':function(self, a,b){return a(self)%b(self);}, '^':function(self, a,b){return a(self)^b(self);}, '=':noop, '==':function(self, a,b){return a(self)==b(self);}, '!=':function(self, a,b){return a(self)!=b(self);}, '<':function(self, a,b){return a(self)<b(self);}, '>':function(self, a,b){return a(self)>b(self);}, '<=':function(self, a,b){return a(self)<=b(self);}, '>=':function(self, a,b){return a(self)>=b(self);}, '&&':function(self, a,b){return a(self)&&b(self);}, '||':function(self, a,b){return a(self)||b(self);}, '&':function(self, a,b){return a(self)&b(self);}, // '|':function(self, a,b){return a|b;}, '|':function(self, a,b){return b(self)(self, a(self));}, '!':function(self, a){return !a(self);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, parseStringsForObjects){ var dateParseLength = parseStringsForObjects ? DATE_ISOSTRING_LN : -1, tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function(){return number;}}); } function readIdent() { var ident = ""; var start = index; var fn; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { ident += ch; } else { break; } index++; } fn = OPERATORS[ident]; tokens.push({ index:start, text:ident, json: fn, fn:fn||extend(getterFn(ident), { assign:function(self, value){ return setter(self, ident, value); } }) }); } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({index:start, text:rawString, string:string, json:true, fn:function(){ return (string.length == dateParseLength) ? angular['String']['toDate'](string) : string; }}); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json){ var ZERO = valueFn(0), tokens = lex(text, json), assignment = _assignment, assignable = logicalOR, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain, functionIdent = _functionIdent, pipeFunction = _pipeFunction; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = assignable = filterChain = functionIdent = pipeFunction = function (){ throwError("is not valid json", {text:text, index:0}); }; } //TODO: Shouldn't all of the public methods have assertAllConsumed? //TODO: I think these should be public as part of the parser api instead of scope.$eval(). return { assignable: assertConsumed(assignable), primary: assertConsumed(primary), statements: assertConsumed(statements), validator: assertConsumed(validator), formatter: assertConsumed(formatter), filter: assertConsumed(filter) }; function assertConsumed(fn) { return function(){ var value = fn(); if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } return value; }; } /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self) { return fn(self, right); }; } function binaryFn(left, fn, right) { return function(self) { return fn(self, left, right); }; } function hasTokens () { return tokens.length > 0; } function statements(){ var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function (self){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self); } return value; }; } } } function _filterChain(){ var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter(){ return pipeFunction(angularFilter); } function validator(){ return pipeFunction(angularValidator); } function formatter(){ var token = expect(); var formatter = angularFormatter[token.text]; var argFns = []; if (!formatter) throwError('is not a valid formatter.', token); while(true) { if ((token = expect(':'))) { argFns.push(expression()); } else { return valueFn({ format:invokeFn(formatter.format), parse:invokeFn(formatter.parse) }); } } function invokeFn(fn){ return function(self, input){ var args = [input]; for ( var i = 0; i < argFns.length; i++) { args.push(argFns[i](self)); } return fn.apply(self, args); }; } } function _pipeFunction(fnScope){ var fn = functionIdent(fnScope); var argsFn = []; var token; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } return fn.apply(self, args); }; return function(){ return fnInvoke; }; } } } function expression(){ return assignment(); } function _assignment(){ var left = logicalOR(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self){ return left.assign(self, right(self)); }; } else { return left; } } function logicalOR(){ var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND(){ var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality(){ var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational(){ var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive(){ var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative(){ var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary(){ var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function _functionIdent(fnScope) { var token = expect(); var element = token.text.split('.'); var instance = fnScope; var key; for ( var i = 0; i < element.length; i++) { key = element[i]; if (instance) instance = instance[key]; } if (!isFunction(instance)) { throwError("should be a function", token); } return instance; } function primary() { var primary; if (expect('(')) { var expression = filterChain(); consume(')'); primary = expression; } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary); } else if (next.text === '[') { primary = objectIndex(primary); } else if (next.text === '.') { primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field); return extend(function (self){ return getter(object(self)); }, { assign:function(self, value){ return setter(object(self), field, value); } }); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function (self){ var o = obj(self); var i = indexFn(self); return (o) ? o[i] : undefined; }, { assign:function(self, value){ return obj(self)[indexFn(self)] = value; } }); } function _functionCall(fn) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function (self){ var args = []; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } var fnPtr = fn(self) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(self, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function (self){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function (self){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self); object[keyValue.key] = value; } return object; }; } function watchDecl () { var anchorName = expect().text; consume(":"); var expressionFn; if (peekToken().text == '{') { consume("{"); expressionFn = statements(); consume("}"); } else { expressionFn = expression(); } return function(self) { return {name:anchorName, fn:expressionFn}; }; } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accesible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accesbile by path */ function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } if (isUndefined(obj) && key.charAt(0) == '$') { var type = angularGlobal.typeOf(lastInstance); type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; var fn = type ? type[[key.substring(1)]] : _undefined; if (fn) { return obj = bind(lastInstance, fn, lastInstance); } } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}, compileCache = {}, JS_KEYWORDS = {}; forEach( ("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," + "delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," + "if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," + "protected,public,return,short,static,super,switch,synchronized,this,throw,throws," + "transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/), function(key){ JS_KEYWORDS[key] = true;} ); function getterFn(path) { var fn = getterFnCache[path]; if (fn) return fn; var code = 'var l, fn, t;\n'; forEach(path.split('.'), function(key) { key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key; code += 'if(!s) return s;\n' + 'l=s;\n' + 's=s' + key + ';\n' + 'if(typeof s=="function" && !(s instanceof RegExp)) s = function(){ return l' + key + '.apply(l, arguments); };\n'; if (key.charAt(1) == '$') { // special code for super-imposed functions var name = key.substr(2); code += 'if(!s) {\n' + ' t = angular.Global.typeOf(l);\n' + ' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' + ' if (fn) s = function(){ return fn.apply(l, ' + '[l].concat(Array.prototype.slice.call(arguments, 0))); };\n' + '}\n'; } }); code += 'return s;'; fn = Function('s', code); fn["toString"] = function(){ return code; }; return getterFnCache[path] = fn; } /////////////////////////////////// // TODO(misko): Should this function be public? function compileExpr(expr) { return parser(expr).statements(); } // TODO(misko): Deprecate? Remove! // I think that compilation should be a service. function expressionCompile(exp) { if (isFunction(exp)) return exp; var fn = compileCache[exp]; if (!fn) { fn = compileCache[exp] = parser(exp).statements(); } return fn; } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && template.match(new RegExp(":" + param + "\\W"))) { urlParams[param] = true; } }); } Route.prototype = { url: function(params) { var self = this, url = this.template, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || ""); url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1"); }); url = url.replace(/\/?#$/, ''); var query = []; forEachSorted(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(xhr) { this.xhr = xhr; } ResourceFactory.DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; ResourceFactory.prototype = { route: function(url, paramDefaults, actions){ var self = this; var route = new Route(url); actions = extend({}, ResourceFactory.DEFAULT_ACTIONS, actions); function extractParams(data){ var ids = {}; forEach(paramDefaults || {}, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name){ var isPostOrPut = action.method == 'POST' || action.method == 'PUT'; Resource[name] = function (a1, a2, a3, a4) { var params = {}; var data; var success = noop; var error = null; switch(arguments.length) { case 4: error = a4; success = a3; //fallthrough case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; //fallthrough } else { params = a1; data = a2; success = a3; break; } case 1: if (isFunction(a1)) success = a1; else if (isPostOrPut) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); self.xhr( action.method, route.url(extend({}, extractParams(data), action.params || {}, params)), data, function(status, response) { if (response) { if (action.isArray) { value.length = 0; forEach(response, function(item) { value.push(new Resource(item)); }); } else { copy(response, value); } } (success||noop)(value); }, error || action.verifyCache, action.verifyCache); return value; }; Resource.bind = function(additionalParamDefaults){ return self.route(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; Resource.prototype['$' + name] = function(a1, a2, a3) { var params = extractParams(this), success = noop, error; switch(arguments.length) { case 3: params = a1; success = a2; error = a3; break; case 2: case 1: if (isFunction(a1)) { success = a1; error = a2; } else { params = a1; success = a2 || noop; } case 0: break; default: throw "Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } var data = isPostOrPut ? this : undefined; Resource[name].call(this, params, data, success, error); }; }); return Resource; } }; ////////////////////////////// // Browser ////////////////////////////// var XHR = window.XMLHttpRequest || function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc service * @name angular.service.$browser * @requires $log * * @description * Constructor for the object exposed as $browser service. * * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link angular.mock.service.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} body jQuery wrapped document.body. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, body, XHR, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; ////////////////////////////////////////////////////////////// // XHR API ////////////////////////////////////////////////////////////// var idCounter = 0; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; /** * Executes the `fn` function (supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @workInProgress * @ngdoc method * @name angular.service.$browser#xhr * @methodOf angular.service.$browser * * @param {string} method Requested method (get|post|put|delete|head|json) * @param {string} url Requested url * @param {?string} post Post data to send (null if nothing to post) * @param {function(number, string)} callback Function that will be called on response * @param {object=} header additional HTTP headers to send with XHR. * Standard headers are: * <ul> * <li><tt>Content-Type</tt>: <tt>application/x-www-form-urlencoded</tt></li> * <li><tt>Accept</tt>: <tt>application/json, text/plain, &#42;/&#42;</tt></li> * <li><tt>X-Requested-With</tt>: <tt>XMLHttpRequest</tt></li> * </ul> * * @description * Send ajax request */ self.xhr = function(method, url, post, callback, headers) { outstandingRequestCount ++; if (lowercase(method) == 'json') { var callbackId = ("angular_" + Math.random() + '_' + (idCounter++)).replace(/\d\./, ''); window[callbackId] = function(data) { window[callbackId].data = data; }; var script = self.addJs(url.replace('JSON_CALLBACK', callbackId), null, function() { if (window[callbackId].data) { completeOutstandingRequest(callback, 200, window[callbackId].data); } else { completeOutstandingRequest(callback); } delete window[callbackId]; body[0].removeChild(script); }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // normalize IE bug (http://bugs.jquery.com/ticket/1450) var status = xhr.status == 1223 ? 204 : xhr.status; completeOutstandingRequest(callback, status, xhr.responseText); } }; xhr.send(post || ''); } }; /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addPollFn * @methodOf angular.service.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#url * @methodOf angular.service.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.service.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else history.pushState(null, '', url); } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { return location.href; } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @workInProgress * @ngdoc method * @name angular.service.$browser#onUrlChange * @methodOf angular.service.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.service.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#cookies * @methodOf angular.service.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function (name, value) { var cookieLength, cookieArray, cookie, i, keyValue, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { rawDocument.cookie = escape(name) + '=' + escape(value); cookieLength = name.length + value.length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#defer * @methodOf angular.service.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * THIS DOC IS NOT VISIBLE because ngdocs can't process docs for foo#method.method * * @name angular.service.$browser#defer.cancel * @methodOf angular.service.$browser.defer * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. * * @description * Cancels a defered task identified with `deferId`. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// var hoverListener = noop; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#hover * @methodOf angular.service.$browser * * @description * Set hover listener. * * @param {function(Object, boolean)} listener Function that will be called when a hover event * occurs. */ self.hover = function(listener) { hoverListener = listener; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#bind * @methodOf angular.service.$browser * * @description * Register hover function to real browser */ self.bind = function() { document.bind("mouseover", function(event){ hoverListener(jqLite(msie ? event.srcElement : event.target), true); return true; }); document.bind("mouseleave mouseout click dblclick keypress keyup", function(event){ hoverListener(jqLite(event.target), false); return true; }); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addCss * @methodOf angular.service.$browser * * @param {string} url Url to css file * @description * Adds a stylesheet tag to the head. */ self.addCss = function(url) { var link = jqLite(rawDocument.createElement('link')); link.attr('rel', 'stylesheet'); link.attr('type', 'text/css'); link.attr('href', url); body.append(link); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addJs * @methodOf angular.service.$browser * * @param {string} url Url to js file * @param {string=} domId Optional id for the script tag * * @description * Adds a script tag to the head. */ self.addJs = function(url, domId, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document // // We need addJs to be able to add angular-ie-compat.js which is very special and must remain // part of the DOM so that the embedded images can reference it. jQuery's append implementation // (v1.4.2) fubars it. var script = rawDocument.createElement('script'); script.type = 'text/javascript'; script.src = url; if (domId) script.id = domId; if (msie) { script.onreadystatechange = function() { /loaded|complete/.test(script.readyState) && done && done(); }; } else { if (done) script.onload = script.onerror = done; } body[0].appendChild(script); return script; }; /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = document.find('base').attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href; }; } /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) // Empty Elements - HTML 4.01 var emptyElements = makeMap("area,br,col,hr,img"); // Block Elements - HTML 4.01 var blockElements = makeMap("address,blockquote,center,dd,del,dir,div,dl,dt,"+ "hr,ins,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul"); // Inline Elements - HTML 4.01 var inlineElements = makeMap("a,abbr,acronym,b,bdo,big,br,cite,code,del,dfn,em,font,i,img,"+ "ins,kbd,label,map,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var"); // Elements that you can, intentionally, leave open // (and which close themselves) var closeSelfElements = makeMap("colgroup,dd,dt,li,p,td,tfoot,th,thead,tr"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = extend({}, emptyElements, blockElements, inlineElements, closeSelfElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,href,longdesc,src,usemap"); var validAttrs = extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function(){ return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( closeSelfElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = emptyElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) { var value = doubleQuotedValue || singleQoutedValue || unqoutedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { hiddenPre.innerHTML=value.replace(/</g,"&lt;"); return hiddenPre.innerText || hiddenPre.textContent || ''; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] == true) { out('<'); out(tag); forEach(attrs, function(value, key){ var lkey=lowercase(key); if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = lowercase(tag); if (!ignore && validElements[tag] == true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [hasClass()](http://api.jquery.com/hasClass/) * - [parent()](http://api.jquery.com/parent/) * - [prop()](http://api.jquery.com/prop/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [trigger()](http://api.jquery.com/trigger/) * - [unbind()](http://api.jquery.com/unbind/) * * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite: * * - `scope()` - retrieves the current Angular scope of the element. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = {}, jqName = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return (jqId++); } function getStyle(element) { var current = {}, style = element[0].style, value, name, i; if (typeof style.length == 'number') { for(i = 0; i < style.length; i++) { name = style[i]; current[name] = style[name]; } } else { for (name in style) { value = style[name]; if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false') current[name] = value; } } return current; } /** * Converts dash-separated names to camelCase. Useful for dealing with css properties. */ function camelCase(name) { return name.replace(/\-(\w)/g, function(all, letter, offset){ return (offset == 0 && letter == 'w') ? 'w' : letter.toUpperCase(); }); } ///////////////////////////////////////////// function jqLiteWrap(element) { if (isString(element) && element.charAt(0) != '<') { throw new Error('selectors not implemented'); } return new JQLite(element); } function JQLite(element) { if (element instanceof JQLite) { return element; } else if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteRemoveData(element) { var cacheId = element[jqName], cache = jqCache[cacheId]; if (cache) { forEach(cache.bind || {}, function(fn, type){ removeEventListenerFn(element, type, fn); }); delete jqCache[cacheId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteData(element, key, value) { var cacheId = element[jqName], cache = jqCache[cacheId || -1]; if (isDefined(value)) { if (!cache) { element[jqName] = cacheId = jqNextId(); cache = jqCache[cacheId] = {}; } cache[key] = value; } else { return cache ? cache[key] : null; } } function JQLiteHasClass(element, selector, _) { // the argument '_' is important, since it makes the function have 3 arguments, which // is needed for delegate function to realize the this is a getter. var className = " " + selector + " "; return ((" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1); } function JQLiteRemoveClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. jqLiteWrap(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var SPECIAL_ATTR = makeMap("multiple,selected,checked,disabled,readonly"); forEach({ data: JQLiteData, scope: function(element) { var scope; while (element && !(scope = jqLite(element).data($$scope))) { element = element.parentNode; } return scope; }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ if (SPECIAL_ATTR[name]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, name); } else { element[name] = false; element.removeAttribute(name); } } else { return (element[name] || element.getAttribute(name)) ? name : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { // NodeType == 3 is text node if (element.nodeType == 3) { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } else { if (isUndefined(value)) return element.innerText; element.innerText = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; if ((fn.length == 2 ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { for (key in arg1) { fn(this[i], key, arg1[key]); } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function(element, type, fn){ var bind = JQLiteData(element, 'bind'); if (!bind) JQLiteData(element, 'bind', bind = {}); forEach(type.split(' '), function(type){ var eventHandler = bind[type]; if (!eventHandler) { bind[type] = eventHandler = function(event) { if (!event.preventDefault) { event.preventDefault = function(){ event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented; }; forEach(eventHandler.fns, function(fn){ fn.call(element, event); }); }; eventHandler.fns = []; addEventListenerFn(element, type, eventHandler); } eventHandler.fns.push(fn); }); }, unbind: function(element, type, fn) { var bind = JQLiteData(element, 'bind'); if (!bind) return; //no listeners registered if (isUndefined(type)) { forEach(bind, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete bind[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, bind[type]); delete bind[type]; } else { angularArray.remove(bind[type].fns, fn); } } }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); var angularGlobal = { 'typeOf':function(obj){ if (obj === null) return $null; var type = typeof obj; if (type == $object) { if (obj instanceof Array) return $array; if (isDate(obj)) return $date; if (obj.nodeType == 1) return 'element'; } return type; } }; /** * @ngdoc overview * @name angular.Object * @function * * @description * A namespace for utility functions used to work with JavaScript objects. These functions are * exposed in two ways: * * * __Angular expressions:__ Functions are bound to all objects and augment the Object type. * The names of these methods are prefixed with the '$' character in order to minimize naming * collisions. To call a method, invoke the function without the first argument, for example, * `myObject.$foo(param2)`. * * * __JavaScript code:__ Functions don't augment the Object type and must be invoked as functions * of `angular.Object` as `angular.Object.foo(myObject, param2)`. * * * {@link angular.Object.copy angular.Object.copy()} - Creates a deep copy of the source * parameter. * * {@link angular.Object.equals angular.Object.equals()} - Determines if two objects or values * are equivalent. * * {@link angular.Object.size angular.Object.size()} - Determines the number of elements in * strings, arrays, and objects. */ var angularCollection = { 'copy': copy, 'size': size, 'equals': equals }; var angularObject = { 'extend': extend }; /** * @ngdoc overview * @name angular.Array * * @description * A namespace for utility functions for the manipulation of JavaScript Array objects. * * These functions are exposed in two ways: * * * __Angular expressions:__ Functions are bound to the Array objects and augment the Array type * as array methods. The names of these methods are prefixed with the `$` character to minimize * naming collisions. To call a method, invoke myArrayObject.$foo(params). * * Because Array type is a subtype of the Object type, all angular.Object functions augment * the Array type in Angular expressions as well. * * * __JavaScript code:__ Functions do nor augment the Array type and must be invoked as functions * of `angular.Array` as `angular.Array.foo(myArrayObject, params)`. * * The following APIs are built in to the Angular Array object: * * * {@link angular.Array.add angular.Array.add()} - Optionally adds a new element to an array. * * {@link angular.Array.count angular.Array.count()} - Determines the number of elements in an * array. * * {@link angular.Array.filter angular.Array.filter()} - Returns the subset of elements specified * in the filter as a new array. * * {@link angular.Array.indexOf angular.Array.indexOf()} - Determines the index of an array * value. * * {@link angular.Array.limitTo angular.Array.limitTo()} - Creates a sub-array of an existing * array. * * {@link angular.Array.orderBy angular.Array.orderBy()} - Orders array elements. * * {@link angular.Array.remove angular.Array.remove()} - Removes array elements. * * {@link angular.Array.sum angular.Array.sum()} - Sums the numbers in an array. */ var angularArray = { /** * @ngdoc function * @name angular.Array.indexOf * @function * * @description * Determines the index of a `value` in an `array`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array Array to search. * @param {*} value Value to search for. * @returns {number} The position of the element in `array`. The position is 0-based. * If the value cannot be found, `-1` is returned. * * @example <doc:example> <doc:source> <div ng:init="books = ['Moby Dick', 'Great Gatsby', 'Romeo and Juliet']"></div> <input name='bookName' value='Romeo and Juliet'> <br> Index of '{{bookName}}' in the list {{books}} is <em>{{books.$indexOf(bookName)}}</em>. </doc:source> <doc:scenario> it('should correctly calculate the initial index', function() { expect(binding('books.$indexOf(bookName)')).toBe('2'); }); it('should recalculate', function() { input('bookName').enter('foo'); expect(binding('books.$indexOf(bookName)')).toBe('-1'); input('bookName').enter('Moby Dick'); expect(binding('books.$indexOf(bookName)')).toBe('0'); }); </doc:scenario> </doc:example> */ 'indexOf': indexOf, /** * @ngdoc function * @name angular.Array.sum * @function * * @description * The `sum` function calculates the sum of all numbers in an `array`. If an `expression` is * supplied, `sum` evaluates each element in the `array` with the expression and then returns * the sum of the calculated values. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more info about Angular arrays. * * @param {Array} array The source array. * @param {(string|function())=} expression Angular expression or a function to be evaluated for * each element in `array`. The array element becomes the `this` during the evaluation. * @returns {number} Sum of items in the array. * * @example <doc:example> <doc:source> <table ng:init="invoice= {items:[{qty:10, description:'gadget', cost:9.95}]}"> <tr><th>Qty</th><th>Description</th><th>Cost</th><th>Total</th><th></th></tr> <tr ng:repeat="item in invoice.items"> <td><input name="item.qty" value="1" size="4" ng:required ng:validate="integer"></td> <td><input name="item.description"></td> <td><input name="item.cost" value="0.00" ng:required ng:validate="number" size="6"></td> <td>{{item.qty * item.cost | currency}}</td> <td>[<a href ng:click="invoice.items.$remove(item)">X</a>]</td> </tr> <tr> <td><a href ng:click="invoice.items.$add()">add item</a></td> <td></td> <td>Total:</td> <td>{{invoice.items.$sum('qty*cost') | currency}}</td> </tr> </table> </doc:source> <doc:scenario> //TODO: these specs are lame because I had to work around issues #164 and #167 it('should initialize and calculate the totals', function() { expect(repeater('.doc-example-live table tr', 'item in invoice.items').count()).toBe(3); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(1)). toEqual(['$99.50']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); }); it('should add an entry and recalculate', function() { element('.doc-example-live a:contains("add item")').click(); using('.doc-example-live tr:nth-child(3)').input('item.qty').enter('20'); using('.doc-example-live tr:nth-child(3)').input('item.cost').enter('100'); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(2)). toEqual(['$2,000.00']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$2,099.50'); }); </doc:scenario> </doc:example> */ 'sum':function(array, expression) { var fn = angularFunction.compile(expression); var sum = 0; for (var i = 0; i < array.length; i++) { var value = 1 * fn(array[i]); if (!isNaN(value)){ sum += value; } } return sum; }, /** * @ngdoc function * @name angular.Array.remove * @function * * @description * Modifies `array` by removing an element from it. The element will be looked up using the * {@link angular.Array.indexOf indexOf} function on the `array` and only the first instance of * the element will be removed. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array Array from which an element should be removed. * @param {*} value Element to be removed. * @returns {*} The removed element. * * @example <doc:example> <doc:source> <ul ng:init="tasks=['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']"> <li ng:repeat="task in tasks"> {{task}} [<a href="" ng:click="tasks.$remove(task)">X</a>] </li> </ul> <hr/> tasks = {{tasks}} </doc:source> <doc:scenario> it('should initialize the task list with for tasks', function() { expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(4); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']); }); it('should initialize the task list with for tasks', function() { element('.doc-example-live ul li a:contains("X"):first').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(3); element('.doc-example-live ul li a:contains("X"):last').click(); expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(2); expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')). toEqual(['Read Documentation', 'Check out demos']); }); </doc:scenario> </doc:example> */ 'remove':function(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; }, /** * @ngdoc function * @name angular.Array.filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng:init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input name="searchText"/> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(searchText)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input name="search.$"/> <br> Name only <input name="search.name"/><br> Phone only <input name="search.phone"/><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(search)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ 'filter':function(array, expression) { var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function(){ var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function(){ var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }, /** * @ngdoc function * @name angular.Array.add * @function * * @description * The `add` function in Angualar is similar to JavaScript's `Array#push` method in that it * appends a new element to an array. Angular's function differs from the JavaScript method in * that specifying a value for the function is optional and the default for the function is an * empty object. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array The array to be expanded. * @param {*=} [value={}] The value to be appended. * @returns {Array} The expanded array. * * @TODO simplify the example. * * @example * This example shows how you can use the `$add` method to populate an initially empty array * with objects created from user input. <doc:example> <doc:source> [<a href="" ng:click="people.$add()">add empty</a>] [<a href="" ng:click="people.$add({name:'John', sex:'male'})">add 'John'</a>] [<a href="" ng:click="people.$add({name:'Mary', sex:'female'})">add 'Mary'</a>] <ul ng:init="people=[]"> <li ng:repeat="person in people"> <input name="person.name"> <select name="person.sex"> <option value="">--chose one--</option> <option>male</option> <option>female</option> </select> [<a href="" ng:click="people.$remove(person)">X</a>] </li> </ul> <pre>people = {{people}}</pre> </doc:source> <doc:scenario> beforeEach(function() { expect(binding('people')).toBe('people = []'); }); it('should create an empty record when "add empty" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); expect(binding('people')).toBe('people = [{\n "name":"",\n "sex":null}]'); }); it('should create a "John" record when "add \'John\'" is clicked', function() { element('.doc-example-live a:contains("add \'John\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"John",\n "sex":"male"}]'); }); it('should create a "Mary" record when "add \'Mary\'" is clicked', function() { element('.doc-example-live a:contains("add \'Mary\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"Mary",\n "sex":"female"}]'); }); it('should delete a record when "X" is clicked', function() { element('.doc-example-live a:contains("add empty")').click(); element('.doc-example-live li a:contains("X"):first').click(); expect(binding('people')).toBe('people = []'); }); </doc:scenario> </doc:example> */ 'add':function(array, value) { array.push(isUndefined(value)? {} : value); return array; }, /** * @ngdoc function * @name angular.Array.count * @function * * @description * Determines the number of elements in an array. Provides an option for counting only those * elements for which a specified `condition` evaluates to `true`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array The array containing the elements to be counted. * @param {(function()|string)=} condition A function to be evaluated or * an Angular expression to be compiled and evaluated. The element being * iterated over is exposed to the `condition` as `this`. * @returns {number} Number of elements in the array. If a `condition` is specified, returns * the number of elements whose `condition` evaluates to `true`. * * @example <doc:example> <doc:source> <pre ng:init="items = [{name:'knife', points:1}, {name:'fork', points:3}, {name:'spoon', points:1}]"></pre> <ul> <li ng:repeat="item in items"> {{item.name}}: points= <input type="text" name="item.points"/> <!-- id="item{{$index}} --> </li> </ul> <p>Number of items which have one point: <em>{{ items.$count('points==1') }}</em></p> <p>Number of items which have more than one point: <em>{{items.$count('points&gt;1')}}</em></p> </doc:source> <doc:scenario> it('should calculate counts', function() { expect(binding('items.$count(\'points==1\')')).toEqual('2'); expect(binding('items.$count(\'points>1\')')).toEqual('1'); }); it('should recalculate when updated', function() { using('.doc-example-live li:first-child').input('item.points').enter('23'); expect(binding('items.$count(\'points==1\')')).toEqual('1'); expect(binding('items.$count(\'points>1\')')).toEqual('2'); }); </doc:scenario> </doc:example> */ 'count':function(array, condition) { if (!condition) return array.length; var fn = angularFunction.compile(condition), count = 0; forEach(array, function(value){ if (fn(value)) { count ++; } }); return count; }, /** * @ngdoc function * @name angular.Array.orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more informaton about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <div ng:init="friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]"></div> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng:click="predicate=''">unsorted</a> ] <table ng:init="predicate='-age'"> <tr> <th><a href="" ng:click="predicate = 'name'; reverse=false">Name</a> (<a href ng:click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng:click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng:click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng:repeat="friend in friends.$orderBy(predicate, reverse)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('Sorting predicate = -age; reverse = '); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ 'orderBy':function(array, sortPredicate, reverseOrder) { if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = expressionCompile(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }, /** * @ngdoc function * @name angular.Array.limitTo * @function * * @description * Creates a new array containing only a specified number of elements in an array. The elements * are taken from either the beginning or the end of the source array, as specified by the * value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.Array} for more information about Angular arrays. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the `limit` number is * positive, `limit` number of items from the beginning of the source array are copied. * If the number is negative, `limit` number of items from the end of the source array are * copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` * elements. * * @example <doc:example> <doc:source> <div ng:init="numbers = [1,2,3,4,5,6,7,8,9]"> Limit [1,2,3,4,5,6,7,8,9] to: <input name="limit" value="3"/> <p>Output: {{ numbers.$limitTo(limit) | json }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[name=limit]').val()).toBe('3'); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[7,8,9]'); }); it('should not exceed the maximum size of input array', function() { input('limit').enter(100); expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3,4,5,6,7,8,9]'); }); </doc:scenario> </doc:example> */ limitTo: function(array, limit) { limit = parseInt(limit, 10); var out = [], i, n; // check that array is iterable if (!array || !(array instanceof Array)) return out; // if abs(limit) exceeds maximum length, trim it if (limit > array.length) limit = array.length; else if (limit < -array.length) limit = -array.length; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } }; var R_ISO8061_STR = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/; var angularString = { 'quote':function(string) { return '"' + string.replace(/\\/g, '\\\\'). replace(/"/g, '\\"'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/\t/g, '\\t'). replace(/\v/g, '\\v') + '"'; }, 'quoteUnicode':function(string) { var str = angular['String']['quote'](string); var chars = []; for ( var i = 0; i < str.length; i++) { var ch = str.charCodeAt(i); if (ch < 128) { chars.push(str.charAt(i)); } else { var encode = "000" + ch.toString(16); chars.push("\\u" + encode.substring(encode.length - 4)); } } return chars.join(''); }, /** * Tries to convert input to date and if successful returns the date, otherwise returns the * input. * * @param {string} string * @return {(Date|string)} */ 'toDate':function(string){ var match; if (isString(string) && (match = string.match(R_ISO8061_STR))){ var date = new Date(0); date.setUTCFullYear(match[1], match[2] - 1, match[3]); date.setUTCHours(match[4]||0, match[5]||0, match[6]||0, match[7]||0); return date; } return string; } }; var angularDate = { 'toString':function(date){ if (!date) return date; var isoString = date.toISOString ? date.toISOString() : ''; return (isoString.length==24) ? isoString : padNumber(date.getUTCFullYear(), 4) + '-' + padNumber(date.getUTCMonth() + 1, 2) + '-' + padNumber(date.getUTCDate(), 2) + 'T' + padNumber(date.getUTCHours(), 2) + ':' + padNumber(date.getUTCMinutes(), 2) + ':' + padNumber(date.getUTCSeconds(), 2) + '.' + padNumber(date.getUTCMilliseconds(), 3) + 'Z'; } }; var angularFunction = { 'compile': function(expression) { if (isFunction(expression)){ return expression; } else if (expression){ return expressionCompile(expression); } else { return identity; } } }; /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either call $hashKey function on object or assign unique hashKey id. * * @param obj * @returns {String} hash string such that the same input will have the same hash string */ function hashKey(obj) { var objType = typeof obj; var key = obj; if (objType == 'object') { if (typeof (key = obj.$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$hashKey(); } else if (key === undefined) { key = obj.$hashKey = nextUid(); } } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(){} HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type * @returns old value if any */ put: function(key, value) { var _key = hashKey(key); var oldValue = this[_key]; this[_key] = value; return oldValue; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key * @returns value associated with key before it was removed */ remove: function(key) { var _key = hashKey(key); var value = this[_key]; delete this[_key]; return value; } }; function defineApi(dst, chain){ angular[dst] = angular[dst] || {}; forEach(chain, function(parent){ extend(angular[dst], parent); }); } defineApi('Global', [angularGlobal]); defineApi('Collection', [angularGlobal, angularCollection]); defineApi('Array', [angularGlobal, angularCollection, angularArray]); defineApi('Object', [angularGlobal, angularCollection, angularObject]); defineApi('String', [angularGlobal, angularString]); defineApi('Date', [angularGlobal, angularDate]); //IE bug angular.Date.toString = angularDate.toString; defineApi('Function', [angularGlobal, angularCollection, angularFunction]); /** * @workInProgress * @ngdoc overview * @name angular.filter * @description * * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * Following is the list of built-in angular filters: * * * {@link angular.filter.currency currency} * * {@link angular.filter.date date} * * {@link angular.filter.html html} * * {@link angular.filter.json json} * * {@link angular.filter.linky linky} * * {@link angular.filter.lowercase lowercase} * * {@link angular.filter.number number} * * {@link angular.filter.uppercase uppercase} * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @workInProgress * @ngdoc filter * @name angular.filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * @css ng-format-negative * When the value is negative, this css class is applied to the binding making it (by default) red. * * @example <doc:example> <doc:source> <input type="text" name="amount" value="1234.56"/> <br/> default currency symbol ($): {{amount | currency}}<br/> custom currency identifier (USD$): {{amount | currency:"USD$"}} </doc:source> <doc:scenario> it('should init with 1234.56', function(){ expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function(){ input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); expect(element('.doc-example-live .ng-binding').prop('className')). toMatch(/ng-format-negative/); }); </doc:scenario> </doc:example> */ angularFilter.currency = function(amount, currencySymbol){ var formats = this.$service('$locale').NUMBER_FORMATS; this.$element.toggleClass('ng-format-negative', amount < 0); if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> Enter number: <input name='val' value='1234.56789' /><br/> Default formatting: {{val | number}}<br/> No fractions: {{val | number:0}}<br/> Negative number: {{-val | number:4}} </doc:source> <doc:scenario> it('should format numbers', function(){ expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function(){ input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ var DECIMAL_SEP = '.'; angularFilter.number = function(number, fractionSize) { var formats = this.$service('$locale').NUMBER_FORMATS; return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; if (numStr.indexOf('e') !== -1) { formatedText = numStr; } else { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var GET_TIME_ZONE = /[A-Z]{3}(?![+\-])/, DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, OPERA_TOSTRING_PATTERN = /^[\d].*Z$/, NUMBER_STRING = /^\d+$/; /** * @workInProgress * @ngdoc filter * @name angular.filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `format` string can also be one of the following predefined * {@link guide/dev_guide.i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ). * @param {string=} format Formatting rules (see Description). If not specified, * Date#toLocaleDateString is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng:non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/> </doc:source> <doc:scenario> it('should format date', function(){ expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ angularFilter.date = function(date, format) { var $locale = this.$service('$locale'); format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = parseInt(date, 10); } else { date = angularString.toDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } var text = date.toLocaleDateString(), fn; if (format && isString(format)) { text = ''; var parts = [], match; while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); } return text; }; /** * @workInProgress * @ngdoc filter * @name angular.filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * @css ng-monospace Always applied to the encapsulating element. * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding('| json')).toBe('{\n "name":"value"}'); }); </doc:scenario> </doc:example> * */ angularFilter.json = function(object) { this.$element.addClass("ng-monospace"); return toJson(object, true); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.lowercase * @function * * @see angular.lowercase */ angularFilter.lowercase = lowercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.uppercase * @function * * @see angular.uppercase */ angularFilter.uppercase = uppercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.html * @function * * @description * Prevents the input from getting escaped by angular. By default the input is sanitized and * inserted into the DOM as is. * * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * If you hate your users, you may call the filter with optional 'unsafe' argument, which bypasses * the html sanitizer, but makes your application vulnerable to XSS and other attacks. Using this * option is strongly discouraged and should be used only if you absolutely trust the input being * filtered and you can't get the content through the sanitizer. * * @param {string} html Html input. * @param {string=} option If 'unsafe' then do not sanitize the HTML input. * @returns {string} Sanitized or raw html. * * @example <doc:example> <doc:source> Snippet: <textarea name="snippet" cols="60" rows="3"> &lt;p style="color:blue"&gt;an html &lt;em onmouseover="this.textContent='PWN3D!'"&gt;click here&lt;/em&gt; snippet&lt;/p&gt;</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng:bind="snippet | html"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | html"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng:bind="snippet | html:'unsafe'"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet | html:'unsafe'"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should sanitize the html snippet ', function(){ expect(using('#html-filter').binding('snippet | html')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should escape snippet without any filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function(){ input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet | html')).toBe('new <b>text</b>'); expect(using('#escaped-html').binding('snippet')).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).toBe('new <b>text</b>'); }); </doc:scenario> </doc:example> */ angularFilter.html = function(html, option){ return new HTML(html, option); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * @param {string} text Input text. * @returns {string} Html-linkified text. * * @example <doc:example> <doc:source> Snippet: <textarea name="snippet" cols="60" rows="3"> Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, another@somewhere.org, and one more: ftp://127.0.0.1/.</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng:bind="snippet | linky"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | linky"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> </table> </doc:source> <doc:scenario> it('should linkify the snippet with urls', function(){ expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:\n' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,\n' + '<a href="mailto:us@somewhere.org">us@somewhere.org</a>,\n' + '<a href="mailto:another@somewhere.org">another@somewhere.org</a>,\n' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:us@somewhere.org,\n" + "another@somewhere.org,\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function(){ input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); </doc:scenario> </doc:example> */ var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/, MAILTO_REGEXP = /^mailto:/; angularFilter.linky = function(text) { if (!text) return text; var match; var raw = text; var html = []; var writer = htmlSanitizeWriter(html); var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2] == match[3]) url = 'mailto:' + url; i = match.index; writer.chars(raw.substr(0, i)); writer.start('a', {href:url}); writer.chars(match[0].replace(MAILTO_REGEXP, '')); writer.end('a'); raw = raw.substring(i + match[0].length); } writer.chars(raw); return new HTML(html.join('')); }; /** * @workInProgress * @ngdoc overview * @name angular.formatter * @description * * Formatters are used for translating data formats between those used for display and those used * for storage. * * Following is the list of built-in angular formatters: * * * {@link angular.formatter.boolean boolean} - Formats user input in boolean format * * {@link angular.formatter.json json} - Formats user input in JSON format * * {@link angular.formatter.list list} - Formats user input string as an array * * {@link angular.formatter.number number} - Formats user input strings as a number * * {@link angular.formatter.trim trim} - Trims extras spaces from end of user input * * For more information about how angular formatters work, and how to create your own formatters, * see {@link guide/dev_guide.templates.formatters Understanding Angular Formatters} in the angular * Developer Guide. */ function formatter(format, parse) {return {'format':format, 'parse':parse || format};} function toString(obj) { return (isDefined(obj) && obj !== null) ? "" + obj : obj; } var NUMBER = /^\s*[-+]?\d*(\.\d*)?\s*$/; angularFormatter.noop = formatter(identity, identity); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.json * * @description * Formats the user input as JSON text. * * @returns {?string} A JSON string representation of the model. * * @example <doc:example> <doc:source> <div ng:init="data={name:'misko', project:'angular'}"> <input type="text" size='50' name="data" ng:format="json"/> <pre>data={{data}}</pre> </div> </doc:source> <doc:scenario> it('should format json', function(){ expect(binding('data')).toEqual('data={\n \"name\":\"misko\",\n \"project\":\"angular\"}'); input('data').enter('{}'); expect(binding('data')).toEqual('data={\n }'); }); </doc:scenario> </doc:example> */ angularFormatter.json = formatter(toJson, function(value){ return fromJson(value || 'null'); }); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.boolean * * @description * Use boolean formatter if you wish to store the data as boolean. * * @returns {boolean} Converts to `true` unless user enters (blank), `f`, `false`, `0`, `no`, `[]`. * * @example <doc:example> <doc:source> Enter truthy text: <input type="text" name="value" ng:format="boolean" value="no"/> <input type="checkbox" name="value"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format boolean', function(){ expect(binding('value')).toEqual('value=false'); input('value').enter('truthy'); expect(binding('value')).toEqual('value=true'); }); </doc:scenario> </doc:example> */ angularFormatter['boolean'] = formatter(toString, toBoolean); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.number * * @description * Use number formatter if you wish to convert the user entered string to a number. * * @returns {number} Number from the parsed string. * * @example <doc:example> <doc:source> Enter valid number: <input type="text" name="value" ng:format="number" value="1234"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format numbers', function(){ expect(binding('value')).toEqual('value=1234'); input('value').enter('5678'); expect(binding('value')).toEqual('value=5678'); }); </doc:scenario> </doc:example> */ angularFormatter.number = formatter(toString, function(obj){ if (obj == null || NUMBER.exec(obj)) { return obj===null || obj === '' ? null : 1*obj; } else { throw "Not a number"; } }); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.list * * @description * Use list formatter if you wish to convert the user entered string to an array. * * @returns {Array} Array parsed from the entered string. * * @example <doc:example> <doc:source> Enter a list of items: <input type="text" name="value" ng:format="list" value=" chair ,, table"/> <input type="text" name="value" ng:format="list"/> <pre>value={{value}}</pre> </doc:source> <doc:scenario> it('should format lists', function(){ expect(binding('value')).toEqual('value=["chair","table"]'); this.addFutureAction('change to XYZ', function($window, $document, done){ $document.elements('.doc-example-live :input:last').val(',,a,b,').trigger('change'); done(); }); expect(binding('value')).toEqual('value=["a","b"]'); }); </doc:scenario> </doc:example> */ angularFormatter.list = formatter( function(obj) { return obj ? obj.join(", ") : obj; }, function(value) { var list = []; forEach((value || '').split(','), function(item){ item = trim(item); if (item) list.push(item); }); return list; } ); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.trim * * @description * Use trim formatter if you wish to trim extra spaces in user text. * * @returns {String} Trim excess leading and trailing space. * * @example <doc:example> <doc:source> Enter text with leading/trailing spaces: <input type="text" name="value" ng:format="trim" value=" book "/> <input type="text" name="value" ng:format="trim"/> <pre>value={{value|json}}</pre> </doc:source> <doc:scenario> it('should format trim', function(){ expect(binding('value')).toEqual('value="book"'); this.addFutureAction('change to XYZ', function($window, $document, done){ $document.elements('.doc-example-live :input:last').val(' text ').trigger('change'); done(); }); expect(binding('value')).toEqual('value="text"'); }); </doc:scenario> </doc:example> */ angularFormatter.trim = formatter( function(obj) { return obj ? trim("" + obj) : ""; } ); /** * @workInProgress * @ngdoc overview * @name angular.validator * @description * * Most of the built-in angular validators are used to check user input against defined types or * patterns. You can easily create your own custom validators as well. * * Following is the list of built-in angular validators: * * * {@link angular.validator.asynchronous asynchronous()} - Provides asynchronous validation via a * callback function. * * {@link angular.validator.date date()} - Checks user input against default date format: * "MM/DD/YYYY" * * {@link angular.validator.email email()} - Validates that user input is a well-formed email * address. * * {@link angular.validator.integer integer()} - Validates that user input is an integer * * {@link angular.validator.json json()} - Validates that user input is valid JSON * * {@link angular.validator.number number()} - Validates that user input is a number * * {@link angular.validator.phone phone()} - Validates that user input matches the pattern * "1(123)123-1234" * * {@link angular.validator.regexp regexp()} - Restricts valid input to a specified regular * expression pattern * * {@link angular.validator.url url()} - Validates that user input is a well-formed URL. * * For more information about how angular validators work, and how to create your own validators, * see {@link guide/dev_guide.templates.validators Understanding Angular Validators} in the angular * Developer Guide. */ extend(angularValidator, { 'noop': function() { return null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.regexp * @description * Use regexp validator to restrict the input to any Regular Expression. * * @param {string} value value to validate * @param {string|regexp} expression regular expression. * @param {string=} msg error message to display. * @css ng-validation-error * * @example <doc:example> <doc:source> <script> function Cntl(){ this.ssnRegExp = /^\d\d\d-\d\d-\d\d\d\d$/; } </script> Enter valid SSN: <div ng:controller="Cntl"> <input name="ssn" value="123-45-6789" ng:validate="regexp:ssnRegExp" > </div> </doc:source> <doc:scenario> it('should invalidate non ssn', function(){ var textBox = element('.doc-example-live :input'); expect(textBox.prop('className')).not().toMatch(/ng-validation-error/); expect(textBox.val()).toEqual('123-45-6789'); input('ssn').enter('123-45-67890'); expect(textBox.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'regexp': function(value, regexp, msg) { if (!value.match(regexp)) { return msg || "Value does not match expected format " + regexp + "."; } else { return null; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.number * @description * Use number validator to restrict the input to numbers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example <doc:example> <doc:source> Enter number: <input name="n1" ng:validate="number" > <br> Enter number greater than 10: <input name="n2" ng:validate="number:10" > <br> Enter number between 100 and 200: <input name="n3" ng:validate="number:100:200" > <br> </doc:source> <doc:scenario> it('should invalidate number', function(){ var n1 = element('.doc-example-live :input[name=n1]'); expect(n1.prop('className')).not().toMatch(/ng-validation-error/); input('n1').enter('1.x'); expect(n1.prop('className')).toMatch(/ng-validation-error/); var n2 = element('.doc-example-live :input[name=n2]'); expect(n2.prop('className')).not().toMatch(/ng-validation-error/); input('n2').enter('9'); expect(n2.prop('className')).toMatch(/ng-validation-error/); var n3 = element('.doc-example-live :input[name=n3]'); expect(n3.prop('className')).not().toMatch(/ng-validation-error/); input('n3').enter('201'); expect(n3.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'number': function(value, min, max) { var num = 1 * value; if (num == value) { if (typeof min != $undefined && num < min) { return "Value can not be less than " + min + "."; } if (typeof min != $undefined && num > max) { return "Value can not be greater than " + max + "."; } return null; } else { return "Not a number"; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.integer * @description * Use number validator to restrict the input to integers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example <doc:example> <doc:source> Enter integer: <input name="n1" ng:validate="integer" > <br> Enter integer equal or greater than 10: <input name="n2" ng:validate="integer:10" > <br> Enter integer between 100 and 200 (inclusive): <input name="n3" ng:validate="integer:100:200" > <br> </doc:source> <doc:scenario> it('should invalidate integer', function(){ var n1 = element('.doc-example-live :input[name=n1]'); expect(n1.prop('className')).not().toMatch(/ng-validation-error/); input('n1').enter('1.1'); expect(n1.prop('className')).toMatch(/ng-validation-error/); var n2 = element('.doc-example-live :input[name=n2]'); expect(n2.prop('className')).not().toMatch(/ng-validation-error/); input('n2').enter('10.1'); expect(n2.prop('className')).toMatch(/ng-validation-error/); var n3 = element('.doc-example-live :input[name=n3]'); expect(n3.prop('className')).not().toMatch(/ng-validation-error/); input('n3').enter('100.1'); expect(n3.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ 'integer': function(value, min, max) { var numberError = angularValidator['number'](value, min, max); if (numberError) return numberError; if (!("" + value).match(/^\s*[\d+]*\s*$/) || value != Math.round(value)) { return "Not a whole number"; } return null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.date * @description * Use date validator to restrict the user input to a valid date * in format in format MM/DD/YYYY. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid date: <input name="text" value="1/1/2009" ng:validate="date" > </doc:source> <doc:scenario> it('should invalidate date', function(){ var n1 = element('.doc-example-live :input'); expect(n1.prop('className')).not().toMatch(/ng-validation-error/); input('text').enter('123/123/123'); expect(n1.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'date': function(value) { var fields = /^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(value); var date = fields ? new Date(fields[3], fields[1]-1, fields[2]) : 0; return (date && date.getFullYear() == fields[3] && date.getMonth() == fields[1]-1 && date.getDate() == fields[2]) ? null : "Value is not a date. (Expecting format: 12/31/2009)."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.email * @description * Use email validator if you wist to restrict the user input to a valid email. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid email: <input name="text" ng:validate="email" value="me@example.com"> </doc:source> <doc:scenario> it('should invalidate email', function(){ var n1 = element('.doc-example-live :input'); expect(n1.prop('className')).not().toMatch(/ng-validation-error/); input('text').enter('a@b.c'); expect(n1.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'email': function(value) { if (value.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)) { return null; } return "Email needs to be in username@host.com format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.phone * @description * Use phone validator to restrict the input phone numbers. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid phone number: <input name="text" value="1(234)567-8901" ng:validate="phone" > </doc:source> <doc:scenario> it('should invalidate phone', function(){ var n1 = element('.doc-example-live :input'); expect(n1.prop('className')).not().toMatch(/ng-validation-error/); input('text').enter('+12345678'); expect(n1.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'phone': function(value) { if (value.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)) { return null; } if (value.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)) { return null; } return "Phone number needs to be in 1(987)654-3210 format in North America " + "or +999 (123) 45678 906 internationally."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.url * @description * Use phone validator to restrict the input URLs. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> Enter valid URL: <input name="text" value="http://example.com/abc.html" size="40" ng:validate="url" > </doc:source> <doc:scenario> it('should invalidate url', function(){ var n1 = element('.doc-example-live :input'); expect(n1.prop('className')).not().toMatch(/ng-validation-error/); input('text').enter('abc://server/path'); expect(n1.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'url': function(value) { if (value.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)) { return null; } return "URL needs to be in http://server[:port]/path format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.json * @description * Use json validator if you wish to restrict the user input to a valid JSON. * * @param {string} value value to validate * @css ng-validation-error * * @example <doc:example> <doc:source> <textarea name="json" cols="60" rows="5" ng:validate="json"> {name:'abc'} </textarea> </doc:source> <doc:scenario> it('should invalidate json', function(){ var n1 = element('.doc-example-live :input'); expect(n1.prop('className')).not().toMatch(/ng-validation-error/); input('json').enter('{name}'); expect(n1.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ 'json': function(value) { try { fromJson(value); return null; } catch (e) { return e.toString(); } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.asynchronous * @description * Use asynchronous validator if the validation can not be computed * immediately, but is provided through a callback. The widget * automatically shows a spinning indicator while the validity of * the widget is computed. This validator caches the result. * * @param {string} value value to validate * @param {function(inputToValidate,validationDone)} validate function to call to validate the state * of the input. * @param {function(data)=} [update=noop] function to call when state of the * validator changes * * @paramDescription * The `validate` function (specified by you) is called as * `validate(inputToValidate, validationDone)`: * * * `inputToValidate`: value of the input box. * * `validationDone`: `function(error, data){...}` * * `error`: error text to display if validation fails * * `data`: data object to pass to update function * * The `update` function is optionally specified by you and is * called by <angular/> on input change. Since the * asynchronous validator caches the results, the update * function can be called without a call to `validate` * function. The function is called as `update(data)`: * * * `data`: data object as passed from validate function * * @css ng-input-indicator-wait, ng-validation-error * * @example <doc:example> <doc:source> <script> function MyCntl(){ this.myValidator = function (inputToValidate, validationDone) { setTimeout(function(){ validationDone(inputToValidate.length % 2); }, 500); } } </script> This input is validated asynchronously: <div ng:controller="MyCntl"> <input name="text" ng:validate="asynchronous:myValidator"> </div> </doc:source> <doc:scenario> it('should change color in delayed way', function(){ var textBox = element('.doc-example-live :input'); expect(textBox.prop('className')).not().toMatch(/ng-input-indicator-wait/); expect(textBox.prop('className')).not().toMatch(/ng-validation-error/); input('text').enter('X'); expect(textBox.prop('className')).toMatch(/ng-input-indicator-wait/); sleep(.6); expect(textBox.prop('className')).not().toMatch(/ng-input-indicator-wait/); expect(textBox.prop('className')).toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> * */ /* * cache is attached to the element * cache: { * inputs : { * 'user input': { * response: server response, * error: validation error * }, * current: 'current input' * } * } * */ 'asynchronous': function(input, asynchronousFn, updateFn) { if (!input) return; var scope = this; var element = scope.$element; var cache = element.data('$asyncValidator'); if (!cache) { element.data('$asyncValidator', cache = {inputs:{}}); } cache.current = input; var inputState = cache.inputs[input], $invalidWidgets = scope.$service('$invalidWidgets'); if (!inputState) { cache.inputs[input] = inputState = { inFlight: true }; $invalidWidgets.markInvalid(scope.$element); element.addClass('ng-input-indicator-wait'); asynchronousFn(input, function(error, data) { inputState.response = data; inputState.error = error; inputState.inFlight = false; if (cache.current == input) { element.removeClass('ng-input-indicator-wait'); $invalidWidgets.markValid(element); } element.data($$validate)(); }); } else if (inputState.inFlight) { // request in flight, mark widget invalid, but don't show it to user $invalidWidgets.markInvalid(scope.$element); } else { (updateFn||noop)(inputState.response); } return inputState.error; } }); /** * @workInProgress * @ngdoc service * @name angular.service.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ angularServiceInject('$cookieStore', function($store) { return { /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#get * @methodOf angular.service.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return fromJson($store[key]); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#put * @methodOf angular.service.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $store[key] = toJson(value); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#remove * @methodOf angular.service.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $store[key]; } }; }, ['$cookies']); /** * @workInProgress * @ngdoc service * @name angular.service.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example */ angularServiceInject('$cookies', function($browser) { var rootScope = this, cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. this.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push(){ var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!isString(value)) { if (isDefined(lastCookies[name])) { cookies[name] = lastCookies[name]; } else { delete cookies[name]; } } else if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }, ['$browser']); /** * @workInProgress * @ngdoc service * @name angular.service.$defer * @requires $browser * * @description * Delegates to {@link angular.service.$browser $browser.defer}, but wraps the `fn` function * into a try/catch block and delegates any exceptions to * {@link angular.service.$exceptionHandler $exceptionHandler} service. * * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. */ angularServiceInject('$defer', function($browser) { var scope = this; return function(fn, delay) { $browser.defer(function() { scope.$apply(fn); }, delay); }; }, ['$browser']); /** * @workInProgress * @ngdoc service * @name angular.service.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ angularServiceInject("$document", function(window){ return jqLite(window.document); }, ['$window']); /** * @workInProgress * @ngdoc service * @name angular.service.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overriden by * {@link angular.mock.service.$exceptionHandler mock $exceptionHandler} * * @example */ var $exceptionHandlerFactory; //reference to be used only in tests angularServiceInject('$exceptionHandler', $exceptionHandlerFactory = function($log){ return function(e) { $log.error(e); }; }, ['$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$hover * @requires $browser * @requires $document * * @description * * @example */ angularServiceInject("$hover", function(browser, document) { var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body); browser.hover(function(element, show){ if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) { if (!tooltip) { tooltip = { callout: jqLite('<div id="ng-callout"></div>'), arrow: jqLite('<div></div>'), title: jqLite('<div class="ng-title"></div>'), content: jqLite('<div class="ng-content"></div>') }; tooltip.callout.append(tooltip.arrow); tooltip.callout.append(tooltip.title); tooltip.callout.append(tooltip.content); body.append(tooltip.callout); } var docRect = body[0].getBoundingClientRect(), elementRect = element[0].getBoundingClientRect(), leftSpace = docRect.right - elementRect.right - arrowWidth; tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."); tooltip.content.text(error); if (leftSpace < width) { tooltip.arrow.addClass('ng-arrow-right'); tooltip.arrow.css({left: (width + 1)+'px'}); tooltip.callout.css({ position: 'fixed', left: (elementRect.left - arrowWidth - width - 4) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } else { tooltip.arrow.addClass('ng-arrow-left'); tooltip.callout.css({ position: 'fixed', left: (elementRect.right + arrowWidth) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } } else if (tooltip) { tooltip.callout.remove(); tooltip = null; } }); }, ['$browser', '$document'], true); /** * @workInProgress * @ngdoc service * @name angular.service.$invalidWidgets * * @description * Keeps references to all invalid widgets found during validation. * Can be queried to find whether there are any invalid widgets currently displayed. * * @example */ angularServiceInject("$invalidWidgets", function(){ var invalidWidgets = []; /** Remove an element from the array of invalid widgets */ invalidWidgets.markValid = function(element){ var index = indexOf(invalidWidgets, element); if (index != -1) invalidWidgets.splice(index, 1); }; /** Add an element to the array of invalid widgets */ invalidWidgets.markInvalid = function(element){ var index = indexOf(invalidWidgets, element); if (index === -1) invalidWidgets.push(element); }; /** Return count of all invalid widgets that are currently visible */ invalidWidgets.visible = function() { var count = 0; forEach(invalidWidgets, function(widget){ count = count + (isVisible(widget) ? 1 : 0); }); return count; }; /* At the end of each eval removes all invalid widgets that are not part of the current DOM. */ this.$watch(function() { for(var i = 0; i < invalidWidgets.length;) { var widget = invalidWidgets[i]; if (isOrphan(widget[0])) { invalidWidgets.splice(i, 1); if (widget.dealoc) widget.dealoc(); } else { i++; } } }); /** * Traverses DOM element's (widget's) parents and considers the element to be an orphan if one of * it's parents isn't the current window.document. */ function isOrphan(widget) { if (widget == window.document) return false; var parent = widget.parentNode; return !parent || isOrphan(parent); } return invalidWidgets; }); var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = PATH_MATCH, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function matchUrl(url, obj) { var match = URL_MATCH.exec(url), match = { protocol: match[1], host: match[3], port: parseInt(match[5]) || DEFAULT_PORTS[match[1]] || null, path: match[6] || '/', search: match[8], hash: match[10] }; if (obj) { obj.$$protocol = match.protocol; obj.$$host = match.host; obj.$$port = match.port; } return match; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } function pathPrefixFromBase(basePath) { return basePath.substr(0, basePath.lastIndexOf('/')); } function convertToHtml5Url(url, basePath, hashPrefix) { var match = matchUrl(url); // already html5 url if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || match.hash.indexOf(hashPrefix) != 0) { return url; // convert hashbang url -> html5 url } else { return composeProtocolHostPort(match.protocol, match.host, match.port) + pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); } } function convertToHashbangUrl(url, basePath, hashPrefix) { var match = matchUrl(url); // already hashbang url if (decodeURIComponent(match.path) == basePath) { return url; // convert html5 url -> hashbang url } else { var search = match.search && '?' + match.search || '', hash = match.hash && '#' + match.hash || '', pathPrefix = pathPrefixFromBase(basePath), path = match.path.substr(pathPrefix.length); if (match.path.indexOf(pathPrefix) != 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + '#' + hashPrefix + path + search + hash; } } /** * LocationUrl represents an url * This object is exposed as $location service when html5 is enabled and supported * * @constructor * @param {string} url Html5 url * @param {string} pathPrefix */ function LocationUrl(url, pathPrefix) { pathPrefix = pathPrefix || ''; /** * Parse given html5 (regular) url string into properties * @param {string} url Html5 url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.path.indexOf(pathPrefix) != 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); this.$$search = parseKeyValue(match.search); this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; this.$$compose(); }, /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + pathPrefix + this.$$url; }; this.$$parse(url); } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} url Legacy url * @param {string} hashPrefix Prefix for hash part (containing path and search) */ function LocationHashbangUrl(url, hashPrefix) { var basePath; /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.hash && match.hash.indexOf(hashPrefix) != 0) { throw 'Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'; } basePath = match.path + (match.search ? '?' + match.search : ''); match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); if (match[1]) { this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); } else { this.$$path = ''; } this.$$search = parseKeyValue(match[3]); this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); }; this.$$parse(url); } LocationUrl.prototype = LocationHashbangUrl.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name angular.service.$location#absUrl * @methodOf angular.service.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name angular.service.$location#url * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); this.path(decodeURIComponent(match[1] || '')).search(match[3] || '') .hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name angular.service.$location#protocol * @methodOf angular.service.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name angular.service.$location#host * @methodOf angular.service.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} */ host: locationGetter('$$host'), /** * @ngdoc method * @name angular.service.$location#port * @methodOf angular.service.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} */ port: locationGetter('$$port'), /** * @ngdoc method * @name angular.service.$location#path * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name angular.service.$location#search * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search part - string or hash object * @return {string} */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = encodeUriQuery(paramValue); } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name angular.service.$location#hash * @methodOf angular.service.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name angular.service.$location#replace * @methodOf angular.service.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc service * @name angular.service.$location * * @requires $browser * @requires $sniffer * @requires $config * @requires $document * * @description * The $location service parses the URL in the browser address bar (based on the {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular Services: Using $location} */ angularServiceInject('$location', function($browser, $sniffer, $config, $document) { var scope = this, currentUrl, basePath = $browser.baseHref() || '/', pathPrefix = pathPrefixFromBase(basePath), hashPrefix = $config.hashPrefix || '', initUrl = $browser.url(); if ($config.html5Mode) { if ($sniffer.history) { currentUrl = new LocationUrl(convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix); } else { currentUrl = new LocationHashbangUrl(convertToHashbangUrl(initUrl, basePath, hashPrefix), hashPrefix); } // link rewriting var u = currentUrl, absUrlPrefix = composeProtocolHostPort(u.protocol(), u.host(), u.port()) + pathPrefix; $document.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (uppercase(event.target.nodeName) != 'A' || event.ctrlKey || event.which == 2) return; var elm = jqLite(event.target), href = elm.attr('href'); if (!href || isDefined(elm.attr('ng:ext-link')) || elm.attr('target')) return; // remove same domain from full url links (IE7 always returns full hrefs) href = href.replace(absUrlPrefix, ''); // link to different domain (or base path) if (href.substr(0, 4) == 'http') return; // remove pathPrefix from absolute links href = href.indexOf(pathPrefix) === 0 ? href.substr(pathPrefix.length) : href; currentUrl.url(href); scope.$apply(); event.preventDefault(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; }); } else { currentUrl = new LocationHashbangUrl(initUrl, hashPrefix); } // rewrite hashbang url <> html5 url if (currentUrl.absUrl() != initUrl) { $browser.url(currentUrl.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if (currentUrl.absUrl() != newUrl) { currentUrl.$$parse(newUrl); scope.$apply(); } }); // update browser var changeCounter = 0; scope.$watch(function() { if ($browser.url() != currentUrl.absUrl()) { changeCounter++; scope.$evalAsync(function() { $browser.url(currentUrl.absUrl(), currentUrl.$$replace); currentUrl.$$replace = false; }); } return changeCounter; }); return currentUrl; }, ['$browser', '$sniffer', '$locationConfig', '$document']); angular.service('$locationConfig', function() { return { html5Mode: false, hashPrefix: '' }; }); /** * @workInProgress * @ngdoc service * @name angular.service.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <doc:example> <doc:source> <script> function LogCtrl($log) { this.$log = $log; } </script> <div ng:controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" name="message" value="Hello World!"/> <button ng:click="$log.log(message)">log</button> <button ng:click="$log.warn(message)">warn</button> <button ng:click="$log.info(message)">info</button> <button ng:click="$log.error(message)">error</button> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ var $logFactory; //reference to be used only in tests angularServiceInject("$log", $logFactory = function($window){ return { /** * @workInProgress * @ngdoc method * @name angular.service.$log#log * @methodOf angular.service.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#warn * @methodOf angular.service.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#info * @methodOf angular.service.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#error * @methodOf angular.service.$log * * @description * Write an error message */ error: consoleLog('error') }; function consoleLog(type) { var console = $window.console || {}; var logFn = console[type] || console.log || noop; if (logFn.apply) { return function(){ var args = []; forEach(arguments, function(arg){ args.push(formatError(arg)); }); return logFn.apply(console, args); }; } else { // we are IE, in which case there is nothing we can do return logFn; } } }, ['$window']); /** * @workInProgress * @ngdoc service * @name angular.service.$resource * @requires $xhr.cache * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link angular.service.$xhr $xhr} service or * raw XMLHttpRequest. * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the following format: * * {action1: {method:?, params:?, isArray:?, verifyCache:?}, * action2: {method:?, params:?, isArray:?, verifyCache:?}, * ...} * * Where: * * - `action` – {string} – The name of action. This name becomes the name of the method on your * resource object. * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSON` (also known as JSONP). * - `params` – {object=} – Optional set of pre-bound parameters for this action. * - isArray – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * - verifyCache – {boolean=} – If true then whenever cache hit occurs, the object is returned and * an async request will be made to the server and the resources as well as the cache will be * updated when the response is received. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link angular.service.$xhr} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class `save`, `remove` and `delete` actions are available on it as * methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read, * update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function(){ user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` * - non-GET "class" actions: `Resource.action(postData, [parameters], [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(); // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$xhr` on the `url` template with the given `method` and `params`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function(){ user.abc = true; user.$save(); }); </pre> * * It's worth noting that the success callback for `get`, `query` and other method gets passed * in the response that came from the server, so one could rewrite the above example as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u){ u.abc = true; u.$save(); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source jsfiddle="false"> <script> function BuzzController($resource) { this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSON', params:{visibility:'@self'}}, replies: {method:'JSON', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng:controller="BuzzController"> <input name="userId" value="googlebuzz"/> <button ng:click="fetch()">fetch</button> <hr/> <div ng:repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng:click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng:repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$resource', function($xhr){ var resource = new ResourceFactory($xhr); return bind(resource, resource.route); }, ['$xhr.cache']); /** * @workInProgress * @ngdoc service * @name angular.service.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * @property {Array.<Object>} routes Array of all configured routes. * * @description * Watches `$location.url()` and tries to map the path to an existing route * definition. It is used for deep-linking URLs to controllers and views (HTML partials). * * The `$route` service is typically used in conjunction with {@link angular.widget.ng:view ng:view} * widget and the {@link angular.service.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the <tt>$route</tt> to match a route against the URL, and the <tt>[[ng:include]]</tt> pulls in the partial. <doc:example> <doc:source jsfiddle="false"> <script> function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; $route.when('/Book/:bookId', {template: 'examples/book.html', controller: BookCntl}); $route.when('/Book/:bookId/ch/:chapterId', {template: 'examples/chapter.html', controller: ChapterCntl}); } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </script> <div ng:controller="MainCntl"> Choose: <a href="#/Book/Moby">Moby</a> | <a href="#/Book/Moby/ch/1">Moby: Ch1</a> | <a href="#/Book/Gatsby">Gatsby</a> | <a href="#/Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a><br/> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> <hr /> <ng:view></ng:view> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject('$route', function($location, $routeParams) { /** * @workInProgress * @ngdoc event * @name angular.service.$route#$beforeRouteChange * @eventOf angular.service.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. * * @param {Route} next Future route information. * @param {Route} current Current route information. * * The `Route` object extends the route definition with the following properties. * * * `scope` - The instance of the route controller. * * `params` - The current {@link angular.service.$routeParams params}. * */ /** * @workInProgress * @ngdoc event * @name angular.service.$route#$afterRouteChange * @eventOf angular.service.$route * @eventType broadcast on root scope * @description * Broadcasted after a route change. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. * * The `Route` object extends the route definition with the following properties. * * * `scope` - The instance of the route controller. * * `params` - The current {@link angular.service.$routeParams params}. * */ /** * @workInProgress * @ngdoc event * @name angular.service.$route#$routeUpdate * @eventOf angular.service.$route * @eventType emit on the current route scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var routes = {}, matcher = switchRouteMatcher, parentScope = this, rootScope = this, dirty = 0, forceReload = false, $route = { routes: routes, /** * @workInProgress * @ngdoc method * @name angular.service.$route#parent * @methodOf angular.service.$route * * @param {Scope} [scope=rootScope] Scope to be used as parent for newly created * `$route.current.scope` scopes. * * @description * Sets a scope to be used as the parent scope for scopes created on route change. If not * set, defaults to the root scope. */ parent: function(scope) { if (scope) parentScope = scope; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#when * @methodOf angular.service.$route * * @param {string} path Route path (matched against `$location.hash`) * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{function()=}` – Controller fn that should be associated with newly * created scope. * - `template` – `{string=}` – path to an html template that should be used by * {@link angular.widget.ng:view ng:view} or * {@link angular.widget.ng:include ng:include} widgets. * - `redirectTo` – {(string|function())=} – value to update * {@link angular.service.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route template. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to false and url in the browser changes, then * $routeUpdate event is emited on the current route scope. You can use this event to * react to {@link angular.service.$routeParams} changes: * * function MyCtrl($route, $routeParams) { * this.$on('$routeUpdate', function() { * // do stuff with $routeParams * }); * } * * @returns {Object} route object * * @description * Adds a new route definition to the `$route` service. */ when: function (path, route) { var routeDef = routes[path]; if (!routeDef) routeDef = routes[path] = {reloadOnSearch: true}; if (route) extend(routeDef, route); // TODO(im): what the heck? merge two route definitions? dirty++; return routeDef; }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#otherwise * @methodOf angular.service.$route * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. */ otherwise: function(params) { $route.when(null, params); }, /** * @workInProgress * @ngdoc method * @name angular.service.$route#reload * @methodOf angular.service.$route * * @description * Causes `$route` service to reload (and recreate the `$route.current` scope) upon the next * eval even if {@link angular.service.$location $location} hasn't changed. */ reload: function() { dirty++; forceReload = true; } }; this.$watch(function() { return dirty + $location.url(); }, updateRoute); return $route; ///////////////////////////////////////////////////// function switchRouteMatcher(on, when) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param) { if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$route === last.$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { $route.current = next; copy(next.params, $routeParams); last.scope && last.scope.$emit('$routeUpdate'); } else { forceReload = false; rootScope.$broadcast('$beforeRouteChange', next, last); last && last.scope && last.scope.$destroy(); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } else { copy(next.params, $routeParams); next.scope = parentScope.$new(next.controller); } } rootScope.$broadcast('$afterRouteChange', next, last); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = matcher($location.path(), path))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parametrs */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }, ['$location', '$routeParams']); /** * @workInProgress * @ngdoc service * @name angular.service.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link angular.service.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link angular.service.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ angularService('$routeParams', function(){ return {}; }); /** * @workInProgress * @ngdoc service * @name angular.service.$sniffer * @requires $window * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * * @description * This is very simple implementation of testing browser's features. */ angularServiceInject('$sniffer', function($window) { if ($window.Modernizr) return $window.Modernizr; return { history: !!($window.history && $window.history.pushState), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!$window.document.documentMode || $window.document.documentMode > 7) }; }, ['$window']); /** * @workInProgress * @ngdoc service * @name angular.service.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng:init="$window = $service('$window'); greeting='Hello World!'" type="text" name="greeting" /> <button ng:click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angularServiceInject("$window", bind(window, identity, window)); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.bulk * @requires $xhr * @requires $xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr.bulk', function($xhr, $error, $log){ var requests = [], scope = this; function bulkXHR(method, url, post, success, error) { if (isFunction(post)) { error = success; success = post; post = null; } var currentQueue; forEach(bulkXHR.urls, function(queue){ if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) { currentQueue = queue; } }); if (currentQueue) { if (!currentQueue.requests) currentQueue.requests = []; var request = { method: method, url: url, data: post, success: success}; if (error) request.error = error; currentQueue.requests.push(request); } else { $xhr(method, url, post, success, error); } } bulkXHR.urls = {}; bulkXHR.flush = function(success, errorback) { assertArgFn(success = success || noop, 0); assertArgFn(errorback = errorback || noop, 1); forEach(bulkXHR.urls, function(queue, url) { var currentRequests = queue.requests; if (currentRequests && currentRequests.length) { queue.requests = []; queue.callbacks = []; $xhr('POST', url, {requests: currentRequests}, function(code, response) { forEach(response, function(response, i) { try { if (response.status == 200) { (currentRequests[i].success || noop)(response.status, response.response); } else if (isFunction(currentRequests[i].error)) { currentRequests[i].error(response.status, response.response); } else { $error(currentRequests[i], response); } } catch(e) { $log.error(e); } }); success(); }, function(code, response) { forEach(currentRequests, function(request, i) { try { if (isFunction(request.error)) { request.error(code, response); } else { $error(request, response); } } catch(e) { $log.error(e); } }); noop(); }); } }); }; this.$watch(function(){ bulkXHR.flush(); }); return bulkXHR; }, ['$xhr', '$xhr.error', '$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.cache * @function * * @requires $xhr.bulk * @requires $defer * @requires $xhr.error * @requires $log * * @description * Acts just like the {@link angular.service.$xhr $xhr} service but caches responses for `GET` * requests. All cache misses are delegated to the $xhr service. * * @property {function()} delegate Function to delegate all the cache misses to. Defaults to * the {@link angular.service.$xhr $xhr} service. * @property {object} data The hashmap where all cached entries are stored. * * @param {string} method HTTP method. * @param {string} url Destination URL. * @param {(string|Object)=} post Request body. * @param {function(number, (string|Object))} success Response success callback. * @param {function(number, (string|Object))=} error Response error callback. * @param {boolean=} [verifyCache=false] If `true` then a result is immediately returned from cache * (if present) while a request is sent to the server for a fresh response that will update the * cached entry. The `success` function will be called when the response is received. * @param {boolean=} [sync=false] in case of cache hit execute `success` synchronously. */ angularServiceInject('$xhr.cache', function($xhr, $defer, $error, $log) { var inflight = {}, self = this; function cache(method, url, post, success, error, verifyCache, sync) { if (isFunction(post)) { if (!isFunction(success)) { verifyCache = success; sync = error; error = null; } else { sync = verifyCache; verifyCache = error; error = success; } success = post; post = null; } else if (!isFunction(error)) { sync = verifyCache; verifyCache = error; error = null; } if (method == 'GET') { var data, dataCached; if ((dataCached = cache.data[url])) { if (sync) { success(200, copy(dataCached.value)); } else { $defer(function() { success(200, copy(dataCached.value)); }); } if (!verifyCache) return; } if ((data = inflight[url])) { data.successes.push(success); data.errors.push(error); } else { inflight[url] = {successes: [success], errors: [error]}; cache.delegate(method, url, post, function(status, response) { if (status == 200) cache.data[url] = {value: response}; var successes = inflight[url].successes; delete inflight[url]; forEach(successes, function(success) { try { (success||noop)(status, copy(response)); } catch(e) { $log.error(e); } }); }, function(status, response) { var errors = inflight[url].errors, successes = inflight[url].successes; delete inflight[url]; forEach(errors, function(error, i) { try { if (isFunction(error)) { error(status, copy(response)); } else { $error( {method: method, url: url, data: post, success: successes[i]}, {status: status, body: response}); } } catch(e) { $log.error(e); } }); }); } } else { cache.data = {}; cache.delegate(method, url, post, success, error); } } cache.data = {}; cache.delegate = $xhr; return cache; }, ['$xhr.bulk', '$defer', '$xhr.error', '$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.error * @function * @requires $log * * @description * Error handler for {@link angular.service.$xhr $xhr service}. An application can replaces this * service with one specific for the application. The default implementation logs the error to * {@link angular.service.$log $log.error}. * * @param {Object} request Request object. * * The object has the following properties * * - `method` – `{string}` – The http request method. * - `url` – `{string}` – The request destination. * - `data` – `{(string|Object)=} – An optional request body. * - `success` – `{function()}` – The success callback function * * @param {Object} response Response object. * * The response object has the following properties: * * - status – {number} – Http status code. * - body – {string|Object} – Body of the response. * * @example <doc:example> <doc:source> fetch a non-existent file and log an error in the console: <button ng:click="$service('$xhr')('GET', '/DOESNT_EXIST')">fetch</button> </doc:source> </doc:example> */ angularServiceInject('$xhr.error', function($log){ return function(request, response){ $log.error('ERROR: XHR: ' + request.url, request, response); }; }, ['$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr * @function * @requires $browser $xhr delegates all XHR requests to the `$browser.xhr()`. A mock version * of the $browser exists which allows setting expectations on XHR requests * in your tests * @requires $xhr.error $xhr delegates all non `2xx` response code to this service. * @requires $log $xhr delegates all exceptions to `$log.error()`. * * @description * Generates an XHR request. The $xhr service delegates all requests to * {@link angular.service.$browser $browser.xhr()} and adds error handling and security features. * While $xhr service provides nicer api than raw XmlHttpRequest, it is still considered a lower * level api in angular. For a higher level abstraction that utilizes `$xhr`, please check out the * {@link angular.service.$resource $resource} service. * * # Error handling * If no `error callback` is specified, XHR response with response code other then `2xx` will be * delegated to {@link angular.service.$xhr.error $xhr.error}. The `$xhr.error` can intercept the * request and process it in application specific way, or resume normal execution by calling the * request `success` method. * * # HTTP Headers * The $xhr service will automatically add certain http headers to all requests. These defaults can * be fully configured by accessing the `$xhr.defaults.headers` configuration object, which * currently contains this default configuration: * * - `$xhr.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, *\/*` * - `X-Requested-With: XMLHttpRequest` * - `$xhr.defaults.headers.post` (header defaults for HTTP POST requests): * - `Content-Type: application/x-www-form-urlencoded` * * To add or overwrite these defaults, simple add or remove a property from this configuration * object. To add headers for an HTTP method other than POST, simple create a new object with name * equal to the lowercased http method name, e.g. `$xhr.defaults.headers.get['My-Header']='value'`. * * * # Security Considerations * When designing web applications your design needs to consider security threats from * {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} and {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}. * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which an * unauthorized site can gain your user's private data. Angular provides following mechanism to * counter XSRF. When performing XHR requests, the $xhr service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the server * can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure that only * JavaScript running on your domain could have read the token. The token must be unique for each * user and must be verifiable by the server (to prevent the JavaScript making up its own tokens). * We recommend that the token is a digest of your site's authentication cookie with * {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * @param {string} method HTTP method to use. Valid values are: `GET`, `POST`, `PUT`, `DELETE`, and * `JSON`. `JSON` is a special case which causes a * [JSONP](http://en.wikipedia.org/wiki/JSON#JSONP) cross domain request using script tag * insertion. * @param {string} url Relative or absolute URL specifying the destination of the request. For * `JSON` requests, `url` should include `JSON_CALLBACK` string to be replaced with a name of an * angular generated callback function. * @param {(string|Object)=} post Request content as either a string or an object to be stringified * as JSON before sent to the server. * @param {function(number, (string|Object))} success A function to be called when the response is * received. The success function will be called with: * * - {number} code [HTTP status code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) of * the response. This will currently always be 200, since all non-200 responses are routed to * {@link angular.service.$xhr.error} service (or custom error callback). * - {string|Object} response Response object as string or an Object if the response was in JSON * format. * @param {function(number, (string|Object))} error A function to be called if the response code is * not 2xx.. Accepts the same arguments as success, above. * * @example <doc:example> <doc:source jsfiddle="false"> <script> function FetchCntl($xhr) { var self = this; this.fetch = function() { self.code = null; self.response = null; $xhr(self.method, self.url, function(code, response) { self.code = code; self.response = response; }, function(code, response) { self.code = code; self.response = response || "Request failed"; }); }; this.updateModel = function(method, url) { self.method = method; self.url = url; }; } FetchCntl.$inject = ['$xhr']; </script> <div ng:controller="FetchCntl"> <select name="method"> <option>GET</option> <option>JSON</option> </select> <input type="text" name="url" value="index.html" size="80"/> <button ng:click="fetch()">fetch</button><br> <button ng:click="updateModel('GET', 'index.html')">Sample GET</button> <button ng:click="updateModel('JSON', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng:click="updateModel('JSON', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>code={{code}}</pre> <pre>response={{response}}</pre> </div> </doc:source> <doc:scenario> it('should make xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code=200'); expect(binding('response')).toMatch(/angularjs.org/); }); it('should make JSONP request to the angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code=200'); expect(binding('response')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('code')).toBe('code='); expect(binding('response')).toBe('response=Request failed'); }); </doc:scenario> </doc:example> */ angularServiceInject('$xhr', function($browser, $error, $log){ var rootScope = this; var xhrHeaderDefaults = { common: { "Accept": "application/json, text/plain, */*", "X-Requested-With": "XMLHttpRequest" }, post: {'Content-Type': 'application/x-www-form-urlencoded'}, get: {}, // all these empty properties are needed so that client apps can just do: head: {}, // $xhr.defaults.headers.head.foo="bar" without having to create head object put: {}, // it also means that if we add a header for these methods in the future, it 'delete': {}, // won't be easily silently lost due to an object assignment. patch: {} }; function xhr(method, url, post, success, error) { if (isFunction(post)) { error = success; success = post; post = null; } if (post && isObject(post)) { post = toJson(post); } $browser.xhr(method, url, post, function(code, response){ try { if (isString(response)) { if (response.match(/^\)\]\}',\n/)) response=response.substr(6); if (/^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { response = fromJson(response, true); } } rootScope.$apply(function(){ if (200 <= code && code < 300) { success(code, response); } else if (isFunction(error)) { error(code, response); } else { $error( {method: method, url: url, data: post, success: success}, {status: code, body: response}); } }); } catch (e) { $log.error(e); } }, extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, xhrHeaderDefaults.common, xhrHeaderDefaults[lowercase(method)])); } xhr.defaults = {headers: xhrHeaderDefaults}; return xhr; }, ['$browser', '$xhr.error', '$log']); /** * @ngdoc service * @name angular.service.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ angularServiceInject('$locale', function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }); /** * @ngdoc overview * @name angular.directive * @description * * Angular directives create custom attributes for DOM elements. A directive can modify the * behavior of the element in which it is specified. Do not use directives to add elements to the * DOM; instead, use {@link angular.widget widgets} to add DOM elements. * * Following is the list of built-in Angular directives: * * * {@link angular.directive.ng:autobind ng:autobind} - An Angular bootstrap parameter that can * act as a directive. * * {@link angular.directive.ng:bind ng:bind} - Creates a data-binding between an HTML text value * and a data model. * * {@link angular.directive.ng:bind-attr ng:bind-attr} - Creates a data-binding in a way similar * to `ng:bind`, but uses JSON key / value pairs to do so. * * {@link angular.directive.ng:bind-template ng:bind-template} - Replaces the text value of an * element with a specified template. * * {@link angular.directive.ng:change ng:change} - Executes an expression when the value of an * input widget changes. * * {@link angular.directive.ng:class ng:class} - Conditionally set a CSS class on an element. * * {@link angular.directive.ng:class-even ng:class-even} - Like `ng:class`, but works in * conjunction with {@link angular.widget.@ng:repeat} to affect even rows in a collection. * * {@link angular.directive.ng:class-odd ng:class-odd} - Like `ng:class`, but works with {@link * angular.widget.@ng:repeat} to affect odd rows. * * {@link angular.directive.ng:click ng:click} - Executes custom behavior when an element is * clicked. * * {@link angular.directive.ng:controller ng:controller} - Creates a scope object linked to the * DOM element and assigns behavior to the scope. * * {@link angular.directive.ng:hide ng:hide} - Conditionally hides a portion of HTML. * * {@link angular.directive.ng:href ng:href} - Places an href in the Angular namespace. * * {@link angular.directive.ng:init} - Initialization tasks run before a template is executed. * * {@link angular.directive.ng:show ng:show} - Conditionally displays a portion of HTML. * * {@link angular.directive.ng:src ng:src} - Places a `src` attribute into the Angular namespace. * * {@link angular.directive.ng:style ng:style} - Conditionally set CSS styles on an element. * * {@link angular.directive.ng:submit} - Binds Angular expressions to `onSubmit` events. * * For more information about how Angular directives work, and to learn how to create your own * directives, see {@link guide/dev_guide.compiler.directives Understanding Angular Directives} in * the Angular Developer Guide. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:init * * @description * The `ng:init` attribute specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <div ng:init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function(){ expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ angularDirective("ng:init", function(expression){ return function(element){ this.$eval(expression); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:controller * * @description * The `ng:controller` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ng:controller` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link angular.service.$route}` * service. * * @element ANY * @param {expression} expression Name of a globally accessible constructor function or an * {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script type="text/javascript"> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; } SettingsController.prototype = { greet: function(){ alert(this.name); }, addContact: function(){ this.contacts.push({type:'email', value:'yourname@example.org'}); }, removeContact: function(contactToRemove) { angular.Array.remove(this.contacts, contactToRemove); }, clearContact: function(contact) { contact.type = 'phone'; contact.value = ''; } }; </script> <div ng:controller="SettingsController"> Name: <input type="text" name="name"/> [ <a href="" ng:click="greet()">greet</a> ]<br/> Contact: <ul> <li ng:repeat="contact in contacts"> <select name="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" name="contact.value"/> [ <a href="" ng:click="clearContact(contact)">clear</a> | <a href="" ng:click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng:click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function(){ expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li[ng\\:repeat-index="0"] input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li[ng\\:repeat-index="1"] input').val()) .toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li[ng\\:repeat-index="2"] input').val()) .toBe('yourname@example.org'); }); </doc:scenario> </doc:example> */ angularDirective("ng:controller", function(expression){ this.scope(function(scope){ var Controller = getter(scope, expression, true) || getter(window, expression, true); assertArgFn(Controller, expression); return Controller; }); return noop; }); /** * @ngdoc directive * @name angular.directive.ng:bind * * @description * The `ng:bind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ng:bind` directly, but instead you use the double curly markup like * `{{ expression }}` and let the Angular compiler transform it to * `<span ng:bind="expression"></span>` when the template is compiled. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> Enter name: <input type="text" name="name" value="Whirled"> <br> Hello <span ng:bind="name"></span>! </doc:source> <doc:scenario> it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind", function(expression, element){ element.addClass('ng-binding'); var exprFn = parser(expression).statements(); return function(element) { var lastValue = noop, lastError = noop; this.$watch(function(scope) { // TODO(misko): remove error handling https://github.com/angular/angular.js/issues/347 var error, value, html, isHtml, isDomElement, hadOwnElement = scope.hasOwnProperty('$element'), oldElement = scope.$element; // TODO(misko): get rid of $element https://github.com/angular/angular.js/issues/348 scope.$element = element; try { value = exprFn(scope); } catch (e) { scope.$service('$exceptionHandler')(e); error = formatError(e); } finally { if (hadOwnElement) { scope.$element = oldElement; } else { delete scope.$element; } } // If we are HTML, then save the raw HTML data so that we don't // recompute sanitization since that is expensive. // TODO: turn this into a more generic way to compute this if ((isHtml = (value instanceof HTML))) value = (html = value).html; if (lastValue === value && lastError == error) return; isDomElement = isElement(value); if (!isHtml && !isDomElement && isObject(value)) { value = toJson(value, true); } if (value != lastValue || error != lastError) { lastValue = value; lastError = error; elementError(element, NG_EXCEPTION, error); if (error) value = error; if (isHtml) { element.html(html.get()); } else if (isDomElement) { element.html(''); element.append(value); } else { element.text(value == undefined ? '' : value); } } }); }; }); var bindTemplateCache = {}; function compileBindTemplate(template){ var fn = bindTemplateCache[template]; if (!fn) { var bindings = []; forEach(parseBindings(template), function(text){ var exp = binding(text); bindings.push(exp ? function(scope, element) { var error, value; try { value = scope.$eval(exp); } catch(e) { scope.$service('$exceptionHandler')(e); error = toJson(e); } elementError(element, NG_EXCEPTION, error); return error ? error : value; } : function() { return text; }); }); bindTemplateCache[template] = fn = function(scope, element, prettyPrintJson) { var parts = [], hadOwnElement = scope.hasOwnProperty('$element'), oldElement = scope.$element; // TODO(misko): get rid of $element scope.$element = element; try { for (var i = 0; i < bindings.length; i++) { var value = bindings[i](scope, element); if (isElement(value)) value = ''; else if (isObject(value)) value = toJson(value, prettyPrintJson); parts.push(value); } return parts.join(''); } finally { if (hadOwnElement) { scope.$element = oldElement; } else { delete scope.$element; } } }; } return fn; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind-template * * @description * The `ng:bind-template` attribute specifies that the element * text should be replaced with the template in ng:bind-template. * Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> Salutation: <input type="text" name="salutation" value="Hello"><br/> Name: <input type="text" name="name" value="World"><br/> <pre ng:bind-template="{{salutation}} {{name}}!"></pre> </doc:source> <doc:scenario> it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Hello World!'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Greetings user!'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-template", function(expression, element){ element.addClass('ng-binding'); var templateFn = compileBindTemplate(expression); return function(element) { var lastValue; this.$watch(function(scope) { var value = templateFn(scope, element, true); if (value != lastValue) { element.text(value); lastValue = value; } }); }; }); var REMOVE_ATTRIBUTES = { 'disabled':'disabled', 'readonly':'readOnly', 'checked':'checked', 'selected':'selected', 'multiple':'multiple' }; /** * @ngdoc directive * @name angular.directive.ng:bind-attr * * @description * The `ng:bind-attr` attribute specifies that a * {@link guide/dev_guide.templates.databinding databinding} should be created between a particular * element attribute and a given expression. Unlike `ng:bind`, the `ng:bind-attr` contains one or * more JSON key value pairs; each pair specifies an attribute and the * {@link guide/dev_guide.expressions expression} to which it will be mapped. * * Instead of writing `ng:bind-attr` statements in your HTML, you can use double-curly markup to * specify an <tt ng:non-bindable>{{expression}}</tt> for the value of an attribute. * At compile time, the attribute is translated into an `<span ng:bind-attr="{attr:expression}"/>` * * The following HTML snippet shows how to specify `ng:bind-attr`: * <pre> * <a href="http://www.google.com/search?q={{query}}">Google</a> * </pre> * * During compilation, the snippet gets translated to the following: * <pre> * <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a> * </pre> * * @element ANY * @param {string} attribute_json one or more JSON key-value pairs representing * the attributes to replace with expressions. Each key matches an attribute * which needs to be replaced. Each value is a text template of * the attribute with the embedded * <tt ng:non-bindable>{{expression}}</tt>s. Any number of * key-value pairs can be specified. * * @example * Enter a search string in the Live Preview text box and then click "Google". The search executes instantly. <doc:example> <doc:source> Google for: <input type="text" name="query" value="AngularJS"/> <a href="http://www.google.com/search?q={{query}}">Google</a> </doc:source> <doc:scenario> it('should check ng:bind-attr', function(){ expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=AngularJS'); using('.doc-example-live').input('query').enter('google'); expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=google'); }); </doc:scenario> </doc:example> */ angularDirective("ng:bind-attr", function(expression){ return function(element){ var lastValue = {}; this.$watch(function(scope){ var values = scope.$eval(expression); for(var key in values) { var value = compileBindTemplate(values[key])(scope, element), specialName = REMOVE_ATTRIBUTES[lowercase(key)]; if (lastValue[key] !== value) { lastValue[key] = value; if (specialName) { if (toBoolean(value)) { element.attr(specialName, specialName); element.attr('ng-' + specialName, value); } else { element.removeAttr(specialName); element.removeAttr('ng-' + specialName); } (element.data($$validate)||noop)(); } else { element.attr(key, value); } } } }); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:click * * @description * The ng:click allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon * click. * * @example <doc:example> <doc:source> <button ng:click="count = count + 1" ng:init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng:click', function(){ expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. * * TODO: maybe we should consider allowing users to control event propagation in the future. */ angularDirective("ng:click", function(expression, element){ return function(element){ var self = this; element.bind('click', function(event){ self.$apply(expression); event.stopPropagation(); }); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:submit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <form ng:submit="list.push(text);text='';" ng:init="list=[]"> Enter text and hit enter: <input type="text" name="text" value="hello"/> <input type="submit" id="submit" value="Submit" /> </form> <pre>list={{list}}</pre> </doc:source> <doc:scenario> it('should check ng:submit', function(){ expect(binding('list')).toBe('list=[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('list=["hello"]'); }); </doc:scenario> </doc:example> */ angularDirective("ng:submit", function(expression, element) { return function(element) { var self = this; element.bind('submit', function(event) { self.$apply(expression); event.preventDefault(); }); }; }); function ngClass(selector) { return function(expression, element) { return function(element) { this.$watch(expression, function(scope, newVal, oldVal) { if (selector(scope.$index)) { element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); } }); }; }; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class * * @description * The `ng:class` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the classes * new classes are added. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myVar='ng-input-indicator-wait'"> <input type="button" value="clear" ng:click="myVar=''"> <br> <span ng:class="myVar">Sample Text &nbsp;&nbsp;&nbsp;&nbsp;</span> </doc:source> <doc:scenario> it('should check ng:class', function(){ expect(element('.doc-example-live span').prop('className')).not(). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class", ngClass(function(){return true;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-odd * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * {@link angular.directive.ng:class ng:class}, except it works in conjunction with `ng:repeat` and * takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.widget.@ng:repeat ng:repeat}. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').prop('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-odd", ngClass(function(i){return i % 2 === 0;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-even * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * {@link angular.directive.ng:class ng:class}, except it works in conjunction with `ng:repeat` and * takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.widget.@ng:repeat ng:repeat}. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').prop('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/ng-input-indicator-wait/); }); </doc:scenario> </doc:example> */ angularDirective("ng:class-even", ngClass(function(i){return i % 2 === 1;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:show * * @description * The `ng:show` and `ng:hide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng:hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:show", function(expression, element){ return function(element){ this.$watch(expression, function(scope, value){ element.css('display', toBoolean(value) ? '' : 'none'); }); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:hide * * @description * The `ng:hide` and `ng:show` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression If the {@link guide/dev_guide.expressions expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ angularDirective("ng:hide", function(expression, element){ return function(element){ this.$watch(expression, function(scope, value){ element.css('display', toBoolean(value) ? 'none' : ''); }); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:style * * @description * The ng:style allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} expression {@link guide/dev_guide.expressions Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <doc:example> <doc:source> <input type="button" value="set" ng:click="myStyle={color:'red'}"> <input type="button" value="clear" ng:click="myStyle={}"> <br/> <span ng:style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </doc:source> <doc:scenario> it('should check ng:style', function(){ expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </doc:scenario> </doc:example> */ angularDirective("ng:style", function(expression, element){ // TODO(i): this is inefficient (runs on every $digest) and obtrusive (overrides 3rd part css) // we should change it in a similar way as I changed ng:class return function(element){ var resetStyle = getStyle(element); this.$watch(function(scope){ var style = scope.$eval(expression) || {}, key, mergedStyle = {}; for(key in style) { if (resetStyle[key] === undefined) resetStyle[key] = ''; mergedStyle[key] = style[key]; } for(key in resetStyle) { mergedStyle[key] = mergedStyle[key] || resetStyle[key]; } element.css(mergedStyle); }); }; }); /** * @ngdoc directive * @name angular.directive.ng:cloak * * @description * The `ng:cloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * prefered in order to benefit from progressive rendering of the browser view. * * `ng:cloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], .ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng:cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ng:cloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ng-cloak` in addition to `ng:cloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng:cloak>{{ 'hello' }}</div> <div id="template2" ng:cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng:cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng:cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ angularDirective("ng:cloak", function(expression, element) { element.removeAttr('ng:cloak'); element.removeClass('ng-cloak'); }); /** * @ngdoc overview * @name angular.markup * @description * * Angular markup transforms the content of DOM elements or portions of the content into other * text or DOM elements for further compilation. * * Markup extensions do not themselves produce linking functions. Think of markup as a way to * produce shorthand for a {@link angular.widget widget} or a {@link angular.directive directive}. * * The most prominent example of a markup in Angular is the built-in, double curly markup * `{{expression}}`, which is shorthand for `<span ng:bind="expression"></span>`. * * Create custom markup like this: * * <pre> * angular.markup('newMarkup', function(text, textNode, parentElement){ * //tranformation code * }); * </pre> * * For more information, see {@link guide/dev_guide.compiler.markup Understanding Angular Markup} * in the Angular Developer Guide. */ /** * @ngdoc overview * @name angular.attrMarkup * @description * * Attribute markup allows you to modify the state of an attribute's text. * * Attribute markup extends the Angular complier in a way similar to {@link angular.markup}, * which allows you to modify the content of a node. * * The most prominent example of an attribute markup in Angular is the built-in double curly markup * which is a shorthand for {@link angular.directive.ng:bind-attr ng:bind-attr}. * * ## Example * * <pre> * angular.attrMarkup('newAttrMarkup', function(attrValue, attrName, element){ * //tranformation code * }); * </pre> * * For more information about Angular attribute markup, see {@link guide/dev_guide.compiler.markup * Understanding Angular Markup} in the Angular Developer Guide. */ function parseBindings(string) { var results = []; var lastIndex = 0; var index; while((index = string.indexOf('{{', lastIndex)) > -1) { if (lastIndex < index) results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; index = string.indexOf('}}', index); index = index < 0 ? string.length : index + 2; results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; } if (lastIndex != string.length) results.push(string.substr(lastIndex, string.length - lastIndex)); return results.length === 0 ? [ string ] : results; } function binding(string) { var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); return binding ? binding[1] : null; } function hasBindings(bindings) { return bindings.length > 1 || binding(bindings[0]) !== null; } angularTextMarkup('{{}}', function(text, textNode, parentElement) { var bindings = parseBindings(text), self = this; if (hasBindings(bindings)) { if (isLeafNode(parentElement[0])) { parentElement.attr('ng:bind-template', text); } else { var cursor = textNode, newElement; forEach(parseBindings(text), function(text){ var exp = binding(text); if (exp) { newElement = jqLite('<span>'); newElement.attr('ng:bind', exp); } else { newElement = jqLite(document.createTextNode(text)); } if (msie && text.charAt(0) == ' ') { newElement = jqLite('<span>&nbsp;</span>'); var nbsp = newElement.html(); newElement.text(text.substr(1)); newElement.html(nbsp + newElement.html()); } cursor.after(newElement); cursor = newElement; }); textNode.remove(); } } }); /** * This tries to normalize the behavior of value attribute across browsers. If value attribute is * not specified, then specify it to be that of the text. */ angularTextMarkup('option', function(text, textNode, parentElement){ if (lowercase(nodeName_(parentElement)) == 'option') { if (msie <= 7) { // In IE7 The issue is that there is no way to see if the value was specified hence // we have to resort to parsing HTML; htmlParser(parentElement[0].outerHTML, { start: function(tag, attrs) { if (isUndefined(attrs.value)) { parentElement.attr('value', text); } } }); } else if (parentElement[0].getAttribute('value') == null) { // jQuery does normalization on 'value' so we have to bypass it. parentElement.attr('value', text); } } }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:href * * @description * Using <angular/> markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ng:href` solves this problem by placing the `href` in the * `ng:` namespace. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng:href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input name="value" /><br /> <a id="link-1" href ng:click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng:click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng:href="/{{'123'}}" ng:ext-link>link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng:click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng:click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng:href="/{{value}}" ng:ext-link>link</a> (link, change hash) </doc:source> <doc:scenario> it('should execute ng:click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng:click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng:click and change url when ng:href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().location().path()).toEqual('/123'); }); it('should execute ng:click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(""); }); it('should execute ng:click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(undefined); }); it('should only change url when only ng:href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe("/6"); element('#link-6').click(); expect(browser().location().path()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:src * * @description * Using <angular/> markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until <angular/> replaces the expression inside * `{{hash}}`. The `ng:src` attribute solves this problem by placing * the `src` attribute in the `ng:` namespace. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng:src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:disabled * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng:init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:disabled. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" name="checked"><br/> <button name="button" ng:disabled="{{checked}}">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:checked * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:checked. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" name="master"><br/> <input id="checkSlave" type="checkbox" ng:checked="{{master}}"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:multiple * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:multiple. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" name="checked"><br/> <select id="select" ng:multiple="{{checked}}"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:readonly * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:readonly. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" name="checked"><br/> <input type="text" ng:readonly="{{checked}}" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:selected * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce ng:selected. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" name="checked"><br/> <select> <option>Hello!</option> <option id="greet" ng:selected="{{checked}}">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * @element ANY * @param {template} template any string which can contain '{{}}' markup. */ var NG_BIND_ATTR = 'ng:bind-attr'; var SPECIAL_ATTRS = {}; forEach('src,href,checked,disabled,multiple,readonly,selected'.split(','), function(name) { SPECIAL_ATTRS['ng:' + name] = name; }); angularAttrMarkup('{{}}', function(value, name, element){ // don't process existing attribute markup if (angularDirective(name) || angularDirective("@" + name)) return; if (msie && name == 'src') value = decodeURI(value); var bindings = parseBindings(value), bindAttr; if (hasBindings(bindings) || SPECIAL_ATTRS[name]) { element.removeAttr(name); bindAttr = fromJson(element.attr(NG_BIND_ATTR) || "{}"); bindAttr[SPECIAL_ATTRS[name] || name] = value; element.attr(NG_BIND_ATTR, toJson(bindAttr)); } }); /** * @workInProgress * @ngdoc overview * @name angular.widget * @description * * An angular widget can be either a custom attribute that modifies an existing DOM element or an * entirely new DOM element. * * During html compilation, widgets are processed after {@link angular.markup markup}, but before * {@link angular.directive directives}. * * Following is the list of built-in angular widgets: * * * {@link angular.widget.@ng:format ng:format} - Formats data for display to user and for storage. * * {@link angular.widget.@ng:non-bindable ng:non-bindable} - Blocks angular from processing an * HTML element. * * {@link angular.widget.@ng:repeat ng:repeat} - Creates and manages a collection of cloned HTML * elements. * * {@link angular.widget.@ng:required ng:required} - Verifies presence of user input. * * {@link angular.widget.@ng:validate ng:validate} - Validates content of user input. * * {@link angular.widget.HTML HTML input elements} - Standard HTML input elements data-bound by * angular. * * {@link angular.widget.ng:view ng:view} - Works with $route to "include" partial templates * * {@link angular.widget.ng:switch ng:switch} - Conditionally changes DOM structure * * {@link angular.widget.ng:include ng:include} - Includes an external HTML fragment * * For more information about angular widgets, see {@link guide/dev_guide.compiler.widgets * Understanding Angular Widgets} in the angular Developer Guide. */ /** * @workInProgress * @ngdoc widget * @name angular.widget.HTML * * @description * The most common widgets you will use will be in the form of the * standard HTML set. These widgets are bound using the `name` attribute * to an expression. In addition, they can have `ng:validate`, `ng:required`, * `ng:format`, `ng:change` attribute to further control their behavior. * * @usageContent * see example below for usage * * <input type="text|checkbox|..." ... /> * <textarea ... /> * <select ...> * <option>...</option> * </select> * * @example <doc:example> <doc:source> <table style="font-size:.9em;"> <tr> <th>Name</th> <th>Format</th> <th>HTML</th> <th>UI</th> <th ng:non-bindable>{{input#}}</th> </tr> <tr> <th>text</th> <td>String</td> <td><tt>&lt;input type="text" name="input1"&gt;</tt></td> <td><input type="text" name="input1" size="4"></td> <td><tt>{{input1|json}}</tt></td> </tr> <tr> <th>textarea</th> <td>String</td> <td><tt>&lt;textarea name="input2"&gt;&lt;/textarea&gt;</tt></td> <td><textarea name="input2" cols='6'></textarea></td> <td><tt>{{input2|json}}</tt></td> </tr> <tr> <th>radio</th> <td>String</td> <td><tt> &lt;input type="radio" name="input3" value="A"&gt;<br> &lt;input type="radio" name="input3" value="B"&gt; </tt></td> <td> <input type="radio" name="input3" value="A"> <input type="radio" name="input3" value="B"> </td> <td><tt>{{input3|json}}</tt></td> </tr> <tr> <th>checkbox</th> <td>Boolean</td> <td><tt>&lt;input type="checkbox" name="input4" value="checked"&gt;</tt></td> <td><input type="checkbox" name="input4" value="checked"></td> <td><tt>{{input4|json}}</tt></td> </tr> <tr> <th>pulldown</th> <td>String</td> <td><tt> &lt;select name="input5"&gt;<br> &nbsp;&nbsp;&lt;option value="c"&gt;C&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="d"&gt;D&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input5"> <option value="c">C</option> <option value="d">D</option> </select> </td> <td><tt>{{input5|json}}</tt></td> </tr> <tr> <th>multiselect</th> <td>Array</td> <td><tt> &lt;select name="input6" multiple size="4"&gt;<br> &nbsp;&nbsp;&lt;option value="e"&gt;E&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="f"&gt;F&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input6" multiple size="4"> <option value="e">E</option> <option value="f">F</option> </select> </td> <td><tt>{{input6|json}}</tt></td> </tr> </table> </doc:source> <doc:scenario> it('should exercise text', function(){ input('input1').enter('Carlos'); expect(binding('input1')).toEqual('"Carlos"'); }); it('should exercise textarea', function(){ input('input2').enter('Carlos'); expect(binding('input2')).toEqual('"Carlos"'); }); it('should exercise radio', function(){ expect(binding('input3')).toEqual('null'); input('input3').select('A'); expect(binding('input3')).toEqual('"A"'); input('input3').select('B'); expect(binding('input3')).toEqual('"B"'); }); it('should exercise checkbox', function(){ expect(binding('input4')).toEqual('false'); input('input4').check(); expect(binding('input4')).toEqual('true'); }); it('should exercise pulldown', function(){ expect(binding('input5')).toEqual('"c"'); select('input5').option('d'); expect(binding('input5')).toEqual('"d"'); }); it('should exercise multiselect', function(){ expect(binding('input6')).toEqual('[]'); select('input6').options('e'); expect(binding('input6')).toEqual('["e"]'); select('input6').options('e', 'f'); expect(binding('input6')).toEqual('["e","f"]'); }); </doc:scenario> </doc:example> */ function modelAccessor(scope, element) { var expr = element.attr('name'); var exprFn, assignFn; if (expr) { exprFn = parser(expr).assignable(); assignFn = exprFn.assign; if (!assignFn) throw new Error("Expression '" + expr + "' is not assignable."); return { get: function() { return exprFn(scope); }, set: function(value) { if (value !== undefined) { assignFn(scope, value); } } }; } } function modelFormattedAccessor(scope, element) { var accessor = modelAccessor(scope, element), formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName); if (accessor) { return { get: function() { return formatter.format(scope, accessor.get()); }, set: function(value) { return accessor.set(formatter.parse(scope, value)); } }; } } function compileValidator(expr) { return parser(expr).validator()(); } function compileFormatter(expr) { return parser(expr).formatter()(); } /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:validate * * @description * The `ng:validate` attribute widget validates the user input. If the input does not pass * validation, the `ng-validation-error` CSS class and the `ng:error` attribute are set on the input * element. Check out {@link angular.validator validators} to find out more. * * @param {string} validator The name of a built-in or custom {@link angular.validator validator} to * to be used. * * @element INPUT * @css ng-validation-error * * @example * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * <doc:example> <doc:source> I don't validate: <input type="text" name="value" value="NotANumber"><br/> I need an integer or nothing: <input type="text" name="value" ng:validate="integer"><br/> </doc:source> <doc:scenario> it('should check ng:validate', function(){ expect(element('.doc-example-live :input:last').prop('className')). toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input:last').prop('className')). not().toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:required * * @description * The `ng:required` attribute widget validates that the user input is present. It is a special case * of the {@link angular.widget.@ng:validate ng:validate} attribute widget. * * @element INPUT * @css ng-validation-error * * @example * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * <doc:example> <doc:source> I cannot be blank: <input type="text" name="value" ng:required><br/> </doc:source> <doc:scenario> it('should check ng:required', function(){ expect(element('.doc-example-live :input').prop('className')). toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input').prop('className')). not().toMatch(/ng-validation-error/); }); </doc:scenario> </doc:example> */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:format * * @description * The `ng:format` attribute widget formats stored data to user-readable text and parses the text * back to the stored form. You might find this useful, for example, if you collect user input in a * text field but need to store the data in the model as a list. Check out * {@link angular.formatter formatters} to learn more. * * @param {string} formatter The name of the built-in or custom {@link angular.formatter formatter} * to be used. * * @element INPUT * * @example * This example shows how the user input is converted from a string and internally represented as an * array. * <doc:example> <doc:source> Enter a comma separated list of items: <input type="text" name="list" ng:format="list" value="table, chairs, plate"> <pre>list={{list}}</pre> </doc:source> <doc:scenario> it('should check ng:format', function(){ expect(binding('list')).toBe('list=["table","chairs","plate"]'); input('list').enter(',,, a ,,,'); expect(binding('list')).toBe('list=["a"]'); }); </doc:scenario> </doc:example> */ function valueAccessor(scope, element) { var validatorName = element.attr('ng:validate') || NOOP, validator = compileValidator(validatorName), requiredExpr = element.attr('ng:required'), formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName), format, parse, lastError, required, invalidWidgets = scope.$service('$invalidWidgets') || {markValid:noop, markInvalid:noop}; if (!validator) throw "Validator named '" + validatorName + "' not found."; format = formatter.format; parse = formatter.parse; if (requiredExpr) { scope.$watch(requiredExpr, function(scope, newValue) { required = newValue; validate(); }); } else { required = requiredExpr === ''; } element.data($$validate, validate); return { get: function(){ if (lastError) elementError(element, NG_VALIDATION_ERROR, null); try { var value = parse(scope, element.val()); validate(); return value; } catch (e) { lastError = e; elementError(element, NG_VALIDATION_ERROR, e); } }, set: function(value) { var oldValue = element.val(), newValue = format(scope, value); if (oldValue != newValue) { element.val(newValue || ''); // needed for ie } validate(); } }; function validate() { var value = trim(element.val()); if (element[0].disabled || element[0].readOnly) { elementError(element, NG_VALIDATION_ERROR, null); invalidWidgets.markValid(element); } else { var error, validateScope = inherit(scope, {$element:element}); error = required && !value ? 'Required' : (value ? validator(validateScope, value) : null); elementError(element, NG_VALIDATION_ERROR, error); lastError = error; if (error) { invalidWidgets.markInvalid(element); } else { invalidWidgets.markValid(element); } } } } function checkedAccessor(scope, element) { var domElement = element[0], elementValue = domElement.value; return { get: function(){ return !!domElement.checked; }, set: function(value){ domElement.checked = toBoolean(value); } }; } function radioAccessor(scope, element) { var domElement = element[0]; return { get: function(){ return domElement.checked ? domElement.value : null; }, set: function(value){ domElement.checked = value == domElement.value; } }; } function optionsAccessor(scope, element) { var formatterName = element.attr('ng:format') || NOOP, formatter = compileFormatter(formatterName); return { get: function(){ var values = []; forEach(element[0].options, function(option){ if (option.selected) values.push(formatter.parse(scope, option.value)); }); return values; }, set: function(values){ var keys = {}; forEach(values, function(value){ keys[formatter.format(scope, value)] = true; }); forEach(element[0].options, function(option){ option.selected = keys[option.value]; }); } }; } function noopAccessor() { return { get: noop, set: noop }; } /* * TODO: refactor * * The table below is not quite right. In some cases the formatter is on the model side * and in some cases it is on the view side. This is a historical artifact * * The concept of model/view accessor is useful for anyone who is trying to develop UI, and * so it should be exposed to others. There should be a form object which keeps track of the * accessors and also acts as their factory. It should expose it as an object and allow * the validator to publish errors to it, so that the the error messages can be bound to it. * */ var textWidget = inputWidget('keydown change', modelAccessor, valueAccessor, initWidgetValue(), true), INPUT_TYPE = { 'text': textWidget, 'textarea': textWidget, 'hidden': textWidget, 'password': textWidget, 'checkbox': inputWidget('click', modelFormattedAccessor, checkedAccessor, initWidgetValue(false)), 'radio': inputWidget('click', modelFormattedAccessor, radioAccessor, radioInit), 'select-one': inputWidget('change', modelAccessor, valueAccessor, initWidgetValue(null)), 'select-multiple': inputWidget('change', modelAccessor, optionsAccessor, initWidgetValue([])) // 'file': fileWidget??? }; function initWidgetValue(initValue) { return function (model, view) { var value = view.get(); if (!value && isDefined(initValue)) { value = copy(initValue); } if (isUndefined(model.get()) && isDefined(value)) { model.set(value); } }; } function radioInit(model, view, element) { var modelValue = model.get(), viewValue = view.get(), input = element[0]; input.checked = false; input.name = this.$id + '@' + input.name; if (isUndefined(modelValue)) { model.set(modelValue = null); } if (modelValue == null && viewValue !== null) { model.set(viewValue); } view.set(modelValue); } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:change * * @description * The directive executes an expression whenever the input widget changes. * * @element INPUT * @param {expression} expression to execute. * * @example * @example <doc:example> <doc:source> <div ng:init="checkboxCount=0; textCount=0"></div> <input type="text" name="text" ng:change="textCount = 1 + textCount"> changeCount {{textCount}}<br/> <input type="checkbox" name="checkbox" ng:change="checkboxCount = 1 + checkboxCount"> changeCount {{checkboxCount}}<br/> </doc:source> <doc:scenario> it('should check ng:change', function(){ expect(binding('textCount')).toBe('0'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('text').enter('abc'); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('checkbox').check(); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('1'); }); </doc:scenario> </doc:example> */ function inputWidget(events, modelAccessor, viewAccessor, initFn, textBox) { return annotate('$defer', function($defer, element) { var scope = this, model = modelAccessor(scope, element), view = viewAccessor(scope, element), ngChange = element.attr('ng:change') || noop, lastValue; if (model) { initFn.call(scope, model, view, element); scope.$eval(element.attr('ng:init') || noop); element.bind(events, function(event){ function handler(){ var value = view.get(); if (!textBox || value != lastValue) { model.set(value); lastValue = model.get(); scope.$eval(ngChange); } } event.type == 'keydown' ? $defer(handler) : scope.$apply(handler); }); scope.$watch(model.get, function(scope, value) { if (!equals(lastValue, value)) { view.set(lastValue = value); } }); } }); } function inputWidgetSelector(element){ this.directives(true); this.descend(true); return INPUT_TYPE[lowercase(element[0].type)] || noop; } angularWidget('input', inputWidgetSelector); angularWidget('textarea', inputWidgetSelector); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:options * * @description * Dynamically generate a list of `<option>` elements for a `<select>` element using an array or * an object obtained by evaluating the `ng:options` expression. * * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `name` attribute * of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ng:options` provides iterator facility for `<option>` element which must be used instead * of {@link angular.widget.@ng:repeat ng:repeat}. `ng:repeat` is not suitable for use with * `<option>` element because of the following reasons: * * * value attribute of the option element that we need to bind to requires a string, but the * source of data for the iteration might be in a form of array containing objects instead of * strings * * {@link angular.widget.@ng:repeat ng:repeat} unrolls after the select binds causing * incorect rendering on most browsers. * * binding to a value not in list confuses most browsers. * * @element select * @param {comprehension_expression} comprehension in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl(){ this.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; this.color = this.colors[2]; // red } </script> <div ng:controller="MyCntrl"> <ul> <li ng:repeat="color in colors"> Name: <input name="color.name"> [<a href ng:click="colors.$remove(color)">X</a>] </li> <li> [<a href ng:click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select name="color" ng:options="c.name for c in colors"></select><br> Color (null allowed): <div class="nullable"> <select name="color" ng:options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </div><br/> Color grouped by shade: <select name="color" ng:options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng:click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng:style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng:options', function(){ expect(binding('color')).toMatch('red'); select('color').option('0'); expect(binding('color')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('color')).toMatch('null'); }); </doc:scenario> </doc:example> */ // 00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/; angularWidget('select', function(element){ this.descend(true); this.directives(true); var isMultiselect = element.attr('multiple'), expression = element.attr('ng:options'), onChange = expressionCompile(element.attr('ng:change') || ""), match; if (!expression) { return inputWidgetSelector.call(this, element); } if (! (match = expression.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ng:options in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + expression + "'."); } var displayFn = expressionCompile(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = expressionCompile(match[3] || ''), valueFn = expressionCompile(match[2] ? match[1] : valueName), valuesFn = expressionCompile(match[7]), // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate = jqLite(document.createElement('optgroup')), nullOption = false; // if false then user will not be able to select it return function(selectElement){ // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element var optionGroupsCache = [[{element: selectElement, label:''}]], scope = this, model = modelAccessor(scope, element), inChangeEvent; // find existing special options forEach(selectElement.children(), function(option){ if (option.value == '') // User is allowed to select the null. nullOption = {label:jqLite(option).text(), id:''}; }); selectElement.html(''); // clear contents selectElement.bind('change', function(){ var optionGroup, collection = valuesFn(scope) || [], key = selectElement.val(), tempScope = scope.$new(), value, optionElement, index, groupIndex, length, groupLength; // let's set a flag that the current model change is due to a change event. // the default action of option selection will cause the appropriate option element to be // deselected and another one to be selected - there is no need for us to be updating the DOM // in this case. inChangeEvent = true; try { if (isMultiselect) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { if (keyName) tempScope[keyName] = key; tempScope[valueName] = collection[optionElement.val()]; value.push(valueFn(tempScope)); } } } } else { if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { tempScope[valueName] = collection[key]; if (keyName) tempScope[keyName] = key; value = valueFn(tempScope); } } if (isDefined(value) && model.get() !== value) { model.set(value); onChange(scope); } scope.$root.$apply(); } finally { tempScope = null; // TODO(misko): needs to be $destroy inChangeEvent = false; } }); scope.$watch(function(scope) { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, values = valuesFn(scope) || [], keys = values, key, groupLength, length, fragment, groupIndex, index, optionElement, optionScope = scope.$new(), modelValue = model.get(), selected, selectedSet = false, // nothing is selected yet isMulti = isMultiselect, lastElement, element; try { if (isMulti) { selectedSet = new HashMap(); if (modelValue && isNumber(length = modelValue.length)) { for (index = 0; index < length; index++) { selectedSet.put(modelValue[index], true); } } } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push(extend({selected:modelValue === null, id:'', label:''}, nullOption)); selectedSet = true; } // If we have a keyName then we are iterating over on object. Grab the keys and sort them. if(keyName) { keys = []; for (key in values) { if (values.hasOwnProperty(key)) keys.push(key); } keys.sort(); } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { optionScope[valueName] = values[keyName ? optionScope[keyName]=keys[index]:index]; optionGroupName = groupByFn(optionScope) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (isMulti) { selected = !!selectedSet.remove(valueFn(optionScope)); } else { selected = modelValue === valueFn(optionScope); selectedSet = selectedSet || selected; // see if at least one item is selected } optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: displayFn(optionScope) || '', // what will be seen by the user selected: selected // determine if we should be selected }); } optionGroupNames.sort(); if (!isMulti && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups optionGroupsCache.push( existingOptions = [ existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label } ] ); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the begining for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (!inChangeEvent && existingOption.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } finally { optionScope.$destroy(); } }); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:include * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ng:include won't work for file:// access). * * @param {string} src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {Scope=} [scope=new_child_scope] optional expression which evaluates to an * instance of angular.scope to set the HTML fragment to. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @example <doc:example> <doc:source jsfiddle="false"> <select name="url"> <option value="examples/ng-include/template1.html">template1.html</option> <option value="examples/ng-include/template2.html">template2.html</option> <option value="">(blank)</option> </select> url of the template: <tt><a href="{{url}}">{{url}}</a></tt> <hr/> <ng:include src="url"></ng:include> </doc:source> <doc:scenario> it('should load template1.html', function(){ expect(element('.doc-example-live ng\\:include').text()). toBe('Content of template1.html\n'); }); it('should load template2.html', function(){ select('url').option('examples/ng-include/template2.html'); expect(element('.doc-example-live ng\\:include').text()). toBe('Content of template2.html\n'); }); it('should change to blank', function(){ select('url').option(''); expect(element('.doc-example-live ng\\:include').text()).toEqual(''); }); </doc:scenario> </doc:example> */ angularWidget('ng:include', function(element){ var compiler = this, srcExp = element.attr("src"), scopeExp = element.attr("scope") || '', onloadExp = element[0].getAttribute('onload') || ''; //workaround for jquery bug #7537 if (element[0]['ng:compiled']) { this.descend(true); this.directives(true); } else { element[0]['ng:compiled'] = true; return extend(function(xhr, element){ var scope = this, changeCounter = 0, releaseScopes = [], childScope, oldScope; function incrementChange(){ changeCounter++;} this.$watch(srcExp, incrementChange); this.$watch(function(scope){ var newScope = scope.$eval(scopeExp); if (newScope !== oldScope) { oldScope = newScope; incrementChange(); } }); this.$watch(function(){return changeCounter;}, function(scope) { var src = scope.$eval(srcExp), useScope = scope.$eval(scopeExp); while(releaseScopes.length) { releaseScopes.pop().$destroy(); } if (src) { xhr('GET', src, null, function(code, response){ element.html(response); if (useScope) { childScope = useScope; } else { releaseScopes.push(childScope = scope.$new()); } compiler.compile(element)(childScope); scope.$eval(onloadExp); }, false, true); } else { childScope = null; element.html(''); } }); }, {$inject:['$xhr.cache']}); } }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:switch * * @description * Conditionally change the DOM structure. * * @usageContent * <any ng:switch-when="matchValue1">...</any> * <any ng:switch-when="matchValue2">...</any> * ... * <any ng:switch-default>...</any> * * @param {*} on expression to match against <tt>ng:switch-when</tt>. * @paramDescription * On child elments add: * * * `ng:switch-when`: the case statement to match against. If match then this * case will be displayed. * * `ng:switch-default`: the default case when no other casses match. * * @example <doc:example> <doc:source> <select name="switch"> <option>settings</option> <option>home</option> <option>other</option> </select> <tt>switch={{switch}}</tt> </hr> <ng:switch on="switch" > <div ng:switch-when="settings">Settings Div</div> <span ng:switch-when="home">Home Span</span> <span ng:switch-default>default</span> </ng:switch> </code> </doc:source> <doc:scenario> it('should start in settings', function(){ expect(element('.doc-example-live ng\\:switch').text()).toEqual('Settings Div'); }); it('should change to home', function(){ select('switch').option('home'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('Home Span'); }); it('should select deafault', function(){ select('switch').option('other'); expect(element('.doc-example-live ng\\:switch').text()).toEqual('default'); }); </doc:scenario> </doc:example> */ angularWidget('ng:switch', function (element) { var compiler = this, watchExpr = element.attr("on"), changeExpr = element.attr('change'), casesTemplate = {}, defaultCaseTemplate, children = element.children(), length = children.length, child, when; if (!watchExpr) throw new Error("Missing 'on' attribute."); while(length--) { child = jqLite(children[length]); // this needs to be here for IE child.remove(); when = child.attr('ng:switch-when'); if (isString(when)) { casesTemplate[when] = compiler.compile(child); } else if (isString(child.attr('ng:switch-default'))) { defaultCaseTemplate = compiler.compile(child); } } children = null; // release memory; element.html(''); return function(element){ var changeCounter = 0; var childScope; var selectedTemplate; this.$watch(watchExpr, function(scope, value) { element.html(''); if ((selectedTemplate = casesTemplate[value] || defaultCaseTemplate)) { changeCounter++; if (childScope) childScope.$destroy(); childScope = scope.$new(); childScope.$eval(changeExpr); } }); this.$watch(function(){return changeCounter;}, function() { element.html(''); if (selectedTemplate) { selectedTemplate(childScope, function(caseElement) { element.append(caseElement); }); } }); }; }); /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with ng:click without * changing the location or causing page reloads, e.g.: * <a href="" ng:click="model.$save()">Save</a> */ angularWidget('a', function() { this.descend(true); this.directives(true); return function(element) { var hasNgHref = ((element.attr('ng:bind-attr') || '').indexOf('"href":') !== -1); // turn <a href ng:click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!hasNgHref && !element.attr('name') && !element.attr('href')) { element.attr('href', ''); } if (element.attr('href') === '' && !hasNgHref) { element.bind('click', function(event){ event.preventDefault(); }); } }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:repeat * * @description * The `ng:repeat` widget instantiates a template once per item from a collection. The collection is * enumerated with the `ng:repeat-index` attribute, starting from 0. Each template instance gets * its own scope, where the given loop variable is set to the current collection item, and `$index` * is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$position` – `{string}` – position of the repeated element in the iterator. One of: * * `'first'`, * * `'middle'` * * `'last'` * * Note: Although `ng:repeat` looks like a directive, it is actually an attribute widget. * * @element ANY * @param {string} repeat_expression The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ng:repeat` to display every person: <doc:example> <doc:source> <div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng:repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng:repeat', function(){ var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ angularWidget('@ng:repeat', function(expression, element){ element.removeAttr('ng:repeat'); element.replaceWith(jqLite('<!-- ng:repeat: ' + expression + ' -->')); var linker = this.compile(element); return function(iterStartElement){ var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ng:repeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + keyValue + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; var childScopes = []; var childElements = [iterStartElement]; var parentScope = this; this.$watch(function(scope){ var index = 0, childCount = childScopes.length, collection = scope.$eval(rhs), collectionLength = size(collection, true), fragment = document.createDocumentFragment(), addFragmentTo = (childCount < collectionLength) ? childElements[childCount] : null, childScope, key; for (key in collection) { if (collection.hasOwnProperty(key)) { if (index < childCount) { // reuse existing child childScope = childScopes[index]; childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); childScope.$eval(); } else { // grow children childScope = parentScope.$new(); childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); childScopes.push(childScope); linker(childScope, function(clone){ clone.attr('ng:repeat-index', index); fragment.appendChild(clone[0]); // TODO(misko): Temporary hack - maybe think about it - removed after we add fragment after $digest() // This causes double $digest for children // The first flush will couse a lot of DOM access (initial) // Second flush shuld be noop since nothing has change hence no DOM access. childScope.$digest(); childElements[index + 1] = clone; }); } index ++; } } //attach new nodes buffered in doc fragment if (addFragmentTo) { // TODO(misko): For performance reasons, we should do the addition after all other widgets // have run. For this should happend after $digest() is done! addFragmentTo.after(jqLite(fragment)); } // shrink children while(childScopes.length > index) { // can not use $destroy(true) since there may be multiple iterators on same parent. childScopes.pop().$destroy(); childElements.pop().remove(); } }); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:non-bindable * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML. * * Note: `ng:non-bindable` looks like a directive, but is actually an attribute widget. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ng:non-bindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng:non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng:non-bindable', function(){ expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ angularWidget("@ng:non-bindable", noop); /** * @ngdoc widget * @name angular.widget.ng:view * * @description * # Overview * `ng:view` is a widget that complements the {@link angular.service.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * This widget provides functionality similar to {@link angular.widget.ng:include ng:include} when * used like this: * * <ng:include src="$route.current.template" scope="$route.current.scope"></ng:include> * * * # Advantages * Compared to `ng:include`, `ng:view` offers these advantages: * * - shorter syntax * - more efficient execution * - doesn't require `$route` service to be available on the root scope * * * @example <doc:example> <doc:source jsfiddle="false"> <script> function MyCtrl($route) { $route.when('/overview', { controller: OverviewCtrl, template: 'partials/guide/dev_guide.overview.html'}); $route.when('/bootstrap', { controller: BootstrapCtrl, template: 'partials/guide/dev_guide.bootstrap.auto_bootstrap.html'}); }; MyCtrl.$inject = ['$route']; function BootstrapCtrl(){} function OverviewCtrl(){} </script> <div ng:controller="MyCtrl"> <a href="overview">overview</a> | <a href="bootstrap">bootstrap</a> | <a href="undefined">undefined</a> <br/> The view is included below: <hr/> <ng:view></ng:view> </div> </doc:source> <doc:scenario> it('should load templates', function(){ element('.doc-example-live a:contains(overview)').click(); expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Overview/); element('.doc-example-live a:contains(bootstrap)').click(); expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Initializing Angular: Automatic Initiialization/); }); </doc:scenario> </doc:example> */ angularWidget('ng:view', function(element) { var compiler = this; if (!element[0]['ng:compiled']) { element[0]['ng:compiled'] = true; return annotate('$xhr.cache', '$route', function($xhr, $route, element){ var template; var changeCounter = 0; this.$on('$afterRouteChange', function(){ changeCounter++; }); this.$watch(function(){return changeCounter;}, function() { var template = $route.current && $route.current.template; if (template) { //xhr's callback must be async, see commit history for more info $xhr('GET', template, function(code, response) { element.html(response); compiler.compile(element)($route.current.scope); }); } else { element.html(''); } }); }); } else { compiler.descend(true); compiler.directives(true); } }); /** * @ngdoc widget * @name angular.widget.ng:pluralize * * @description * # Overview * ng:pluralize is a widget that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/dev_guide.i18n Angular i18n} dev guide). You configure ng:pluralize by * specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a pural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ng:pluralize * You configure ng:pluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/dev_guide.expressions * Angular expression}; these are evaluated on the current scope for its binded value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ng:pluralize: * * <pre> * <ng:pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng:pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng:non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng:non-bindable>{{numberExpression}}</span>. * * # Configuring ng:pluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng:pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng:pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its correspoding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> Person 1:<input type="text" name="person1" value="Igor" /><br/> Person 2:<input type="text" name="person2" value="Misko" /><br/> Number of People:<input type="text" name="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng:pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng:pluralize><br> <!--- Example with offset ---> With Offset(2): <ng:pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng:pluralize> </doc:source> <doc:scenario> it('should show correct pluralized string', function(){ expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live .ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function(){ using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live .ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ angularWidget('ng:pluralize', function(element) { var numberExp = element.attr('count'), whenExp = element.attr('when'), offset = element.attr('offset') || 0; return annotate('$locale', function($locale, element) { var scope = this, whens = scope.$eval(whenExp), whensExpFns = {}; forEach(whens, function(expression, key) { whensExpFns[key] = compileBindTemplate(expression.replace(/{}/g, '{{' + numberExp + '-' + offset + '}}')); }); scope.$watch(function() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!whens[value]) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function(scope, newVal) { element.text(newVal); }); }); }); var browserSingleton; angularService('$browser', function($log, $sniffer) { if (!browserSingleton) { browserSingleton = new Browser(window, jqLite(window.document), jqLite(window.document.body), XHR, $log, $sniffer); browserSingleton.bind(); } return browserSingleton; }, {$inject: ['$log', '$sniffer']}); extend(angular, { // disabled for now until we agree on public name //'annotate': annotate, 'compile': compile, 'scope': createScope, 'copy': copy, 'extend': extend, 'equals': equals, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase }); //try to bind to jquery now so that one can write angular.element().read() //but we will rebind on bootstrap again. bindJQuery(); jqLiteWrap(document).ready(function(){ angularInit(angularJsConfig(document), document); }); })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],.ng-cloak{display:none;}.ng-format-negative{color:red;}.ng-exception{border:2px solid #FF0000;font-family:"Courier New",Courier,monospace;font-size:smaller;white-space:pre;}.ng-validation-error{border:2px solid #FF0000;}#ng-callout{margin:0;padding:0;border:0;outline:0;font-size:13px;font-weight:normal;font-family:Verdana,Arial,Helvetica,sans-serif;vertical-align:baseline;background:transparent;text-decoration:none;}#ng-callout .ng-arrow-left{background-image:url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");background-repeat:no-repeat;background-position:left top;position:absolute;z-index:101;left:-12px;height:23px;width:10px;top:-3px;}#ng-callout .ng-arrow-right{background-image:url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");background-repeat:no-repeat;background-position:left top;position:absolute;z-index:101;height:23px;width:11px;top:-2px;}#ng-callout{position:absolute;z-index:100;border:2px solid #CCCCCC;background-color:#fff;}#ng-callout .ng-content{padding:10px 10px 10px 10px;color:#333333;}#ng-callout .ng-title{background-color:#CCCCCC;text-align:left;padding-left:8px;padding-bottom:5px;padding-top:2px;font-weight:bold;}.ng-input-indicator-wait{background-image:url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");background-position:right;background-repeat:no-repeat;}</style>');
var React = require('react/addons'); var Foo = 'Foo'; var MyComponent = React.createClass({ shouldComponentUpdate: function(nextProps, nextState) { return React.addons.shallowCompare(this, nextProps, nextState); }, render: function() { return <div />; } }); module.exports = MyComponent;
import React from 'react'; import PropTypes from 'prop-types'; import uuid from 'uuid'; import { File } from 'react-feather'; import { sanitize } from 'utils'; import { styles } from './styles.module.scss'; const VALID_FILE_TYPES = [ 'png', 'jpg', 'jpeg', 'gif', 'zip', 'rar', 'gzip', 'pdf', 'txt', 'json', 'doc', 'docx', 'csv', 'js', 'html', 'css', ]; const MAX_FILE_SIZE = process.env.REACT_APP_MAX_FILE_SIZE || 4; /** * Encode the given file to binary string * @param {File} file */ const encodeFile = file => { return new Promise((resolve, reject) => { const reader = new window.FileReader(); if (!file) { reject(); return; } reader.onload = readerEvent => { resolve(window.btoa(readerEvent.target.result)); }; reader.readAsBinaryString(file); }); }; export const FileTransfer = ({ sendEncryptedMessage }) => { const fileInput = React.useRef(null); const supported = React.useMemo( () => Boolean(window.File) && Boolean(window.FileReader) && Boolean(window.FileList) && Boolean(window.Blob) && Boolean(window.btoa) && Boolean(window.atob) && Boolean(window.URL), [], ); React.useEffect(() => { const currentFileInput = fileInput.current; let isMounted = true; const handleFileTransfer = async event => { const file = event.target.files && event.target.files[0]; if (file) { const fileType = file.type || 'file'; const fileName = sanitize(file.name); const fileExtension = file.name.split('.').pop().toLowerCase(); if (VALID_FILE_TYPES.indexOf(fileExtension) <= -1) { // eslint-disable-next-line no-alert alert('File type not supported'); return false; } if (file.size > MAX_FILE_SIZE * 1000000) { // eslint-disable-next-line no-alert alert(`Max filesize is ${MAX_FILE_SIZE}MB`); return false; } const fileId = uuid.v4(); const fileData = { id: fileId, file, fileName, fileType, encodedFile: await encodeFile(file), }; // Mounted component guard if (!isMounted) { return; } fileInput.current.value = ''; sendEncryptedMessage({ type: 'SEND_FILE', payload: { fileName: fileData.fileName, encodedFile: fileData.encodedFile, fileType: fileData.fileType, timestamp: Date.now(), }, }); } return false; }; currentFileInput.addEventListener('change', handleFileTransfer); return () => { isMounted = false; currentFileInput.removeEventListener('change', handleFileTransfer); }; }, [sendEncryptedMessage]); if (!supported) { return null; } return ( <div className={`${styles} icon file-transfer btn btn-link`}> <input placeholder="Choose a file..." type="file" name="fileUploader" id="fileInput" ref={fileInput} /> <label htmlFor="fileInput"> <File color="#fff" /> </label> </div> ); }; FileTransfer.propTypes = { sendEncryptedMessage: PropTypes.func.isRequired, }; export default FileTransfer;
/** * React v15.1.0-alpha.1 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.React = f()}})(function(){var define,module,exports;return (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){ /** * Copyright 2013-present, 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 AutoFocusUtils */ 'use strict'; var ReactDOMComponentTree = _dereq_(41); var focusNode = _dereq_(151); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; },{"151":151,"41":41}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-present 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 BeforeInputEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(143); var FallbackCompositionState = _dereq_(21); var SyntheticCompositionEvent = _dereq_(100); var SyntheticInputEvent = _dereq_(104); var keyOf = _dereq_(161); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({ onBeforeInput: null }), captured: keyOf({ onBeforeInputCapture: null }) }, dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionEnd: null }), captured: keyOf({ onCompositionEndCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionStart: null }), captured: keyOf({ onCompositionStartCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionUpdate: null }), captured: keyOf({ onCompositionUpdateCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; },{"100":100,"104":104,"143":143,"16":16,"161":161,"20":20,"21":21}],3:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],4:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 CSSPropertyOperations */ 'use strict'; var CSSProperty = _dereq_(3); var ExecutionEnvironment = _dereq_(143); var ReactInstrumentation = _dereq_(71); var camelizeStyleName = _dereq_(145); var dangerousStyleValue = _dereq_(117); var hyphenateStyleName = _dereq_(156); var memoizeStringOnly = _dereq_(163); var warning = _dereq_(167); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("development" !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; "development" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; "development" !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if ("development" !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(component._debugID, 'update styles', styles); } var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("development" !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; },{"117":117,"143":143,"145":145,"156":156,"163":163,"167":167,"3":3,"71":71}],5:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 CallbackQueue */ 'use strict'; var _assign = _dereq_(168); var PooledClass = _dereq_(25); var invariant = _dereq_(157); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } _assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function (callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function () { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { !(callbacks.length === contexts.length) ? "development" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, checkpoint: function () { return this._callbacks ? this._callbacks.length : 0; }, rollback: function (len) { if (this._callbacks) { this._callbacks.length = len; this._contexts.length = len; } }, /** * Resets the internal queue. * * @internal */ reset: function () { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function () { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; },{"157":157,"168":168,"25":25}],6:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ChangeEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(143); var ReactDOMComponentTree = _dereq_(41); var ReactUpdates = _dereq_(93); var SyntheticEvent = _dereq_(102); var getEventTarget = _dereq_(125); var isEventSupported = _dereq_(132); var isTextInputElement = _dereq_(133); var keyOf = _dereq_(161); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({ onChange: null }), captured: keyOf({ onChangeCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] } }; /** * For IE shims */ var activeElement = null; var activeElementInst = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topChange) { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 11); } /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); if (activeElement.attachEvent) { activeElement.attachEvent('onpropertychange', handlePropertyChange); } else { activeElement.addEventListener('propertychange', handlePropertyChange, false); } } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; if (activeElement.detachEvent) { activeElement.detachEvent('onpropertychange', handlePropertyChange); } else { activeElement.removeEventListener('propertychange', handlePropertyChange, false); } activeElement = null; activeElementInst = null; activeElementValue = null; activeElementValueProp = null; } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return targetInst; } } function handleEventsForInputEventIE(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementInst; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topClick) { return targetInst; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputEvent; } else { getTargetInstFunc = getTargetInstForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } } }; module.exports = ChangeEventPlugin; },{"102":102,"125":125,"132":132,"133":133,"143":143,"16":16,"161":161,"17":17,"20":20,"41":41,"93":93}],7:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 DOMChildrenOperations */ 'use strict'; var DOMLazyTree = _dereq_(8); var Danger = _dereq_(12); var ReactMultiChildUpdateTypes = _dereq_(76); var ReactDOMComponentTree = _dereq_(41); var ReactInstrumentation = _dereq_(71); var createMicrosoftUnsafeLocalFunction = _dereq_(116); var setInnerHTML = _dereq_(137); var setTextContent = _dereq_(138); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getNativeNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, 'replace text', stringText); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if ("development" !== 'production') { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); ReactInstrumentation.debugTool.onNativeOperation(prevInstance._debugID, 'replace with', markup.toString()); }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { if ("development" !== 'production') { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, 'insert child', { toIndex: update.toIndex, content: update.content.toString() }); } break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, 'move child', { fromIndex: update.fromIndex, toIndex: update.toIndex }); } break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, 'replace children', update.content.toString()); } break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, 'replace text', update.content.toString()); } break; case ReactMultiChildUpdateTypes.REMOVE_NODE: removeChild(parentNode, update.fromNode); if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, 'remove child', { fromIndex: update.fromIndex }); } break; } } } }; module.exports = DOMChildrenOperations; },{"116":116,"12":12,"137":137,"138":138,"41":41,"71":71,"76":76,"8":8}],8:[function(_dereq_,module,exports){ /** * Copyright 2015-present, 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 DOMLazyTree */ 'use strict'; var DOMNamespaces = _dereq_(9); var createMicrosoftUnsafeLocalFunction = _dereq_(116); var setTextContent = _dereq_(138); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { node.innerHTML = tree.html; } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { tree.node.innerHTML = html; } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; },{"116":116,"138":138,"9":9}],9:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 DOMNamespaces */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; },{}],10:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 DOMProperty */ 'use strict'; var invariant = _dereq_(157); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_SIDE_EFFECTS: 0x2, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? "development" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : void 0; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : void 0; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasSideEffects: * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. If true, we read from * the DOM before updating to ensure that the value is only set if it has * changed. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * @type {Object} */ getPossibleStandardName: "development" !== 'production' ? {} : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; },{"157":157}],11:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 DOMPropertyOperations */ 'use strict'; var DOMProperty = _dereq_(10); var ReactDOMComponentTree = _dereq_(41); var ReactDOMInstrumentation = _dereq_(49); var ReactInstrumentation = _dereq_(71); var quoteAttributeValueForBrowser = _dereq_(135); var warning = _dereq_(167); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; "development" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { if ("development" !== 'production') { ReactDOMInstrumentation.debugTool.onCreateMarkupForProperty(name, value); } var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); return; } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } if ("development" !== 'production') { ReactDOMInstrumentation.debugTool.onSetValueForProperty(node, name, value); var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } if ("development" !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { // No HAS_SIDE_EFFECTS logic here, only `value` has it and is string. node[propName] = false; } else { if (!propertyInfo.hasSideEffects || '' + node[propName] !== '') { node[propName] = ''; } } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } if ("development" !== 'production') { ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name); ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name); } } }; module.exports = DOMPropertyOperations; },{"10":10,"135":135,"167":167,"41":41,"49":49,"71":71}],12:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 Danger */ 'use strict'; var DOMLazyTree = _dereq_(8); var ExecutionEnvironment = _dereq_(143); var createNodesFromMarkup = _dereq_(148); var emptyFunction = _dereq_(149); var getMarkupWrap = _dereq_(153); var invariant = _dereq_(157); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function (markupList) { !ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : void 0; var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { !markupList[i] ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : void 0; nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); !!resultList.hasOwnProperty(resultIndex) ? "development" !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : void 0; resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("development" !== 'production') { console.error('Danger: Discarding unexpected node:', renderNode); } } } // Although resultList was populated out of order, it should now be a dense // array. !(resultListAssignmentCount === resultList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : void 0; !(resultList.length === markupList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : void 0; return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : void 0; !markup ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : void 0; !(oldChild.nodeName !== 'HTML') ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; },{"143":143,"148":148,"149":149,"153":153,"157":157,"8":8}],13:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 DefaultEventPluginOrder */ 'use strict'; var keyOf = _dereq_(161); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; module.exports = DefaultEventPluginOrder; },{"161":161}],14:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 DisabledInputUtils */ 'use strict'; var disableableMouseListenerNames = { onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }; /** * Implements a native component that does not receive mouse events * when `disabled` is set. */ var DisabledInputUtils = { getNativeProps: function (inst, props) { if (!props.disabled) { return props; } // Copy the props, except the mouse listeners var nativeProps = {}; for (var key in props) { if (!disableableMouseListenerNames[key] && props.hasOwnProperty(key)) { nativeProps[key] = props[key]; } } return nativeProps; } }; module.exports = DisabledInputUtils; },{}],15:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 EnterLeaveEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ReactDOMComponentTree = _dereq_(41); var SyntheticMouseEvent = _dereq_(106); var keyOf = _dereq_(161); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { mouseEnter: { registrationName: keyOf({ onMouseEnter: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] }, mouseLeave: { registrationName: keyOf({ onMouseLeave: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === topLevelTypes.topMouseOut) { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; },{"106":106,"16":16,"161":161,"20":20,"41":41}],16:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 EventConstants */ 'use strict'; var keyMirror = _dereq_(160); var PropagationPhases = keyMirror({ bubbled: null, captured: null }); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topAbort: null, topAnimationEnd: null, topAnimationIteration: null, topAnimationStart: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topInvalid: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topTransitionEnd: null, topVolumeChange: null, topWaiting: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"160":160}],17:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 EventPluginHub */ 'use strict'; var EventPluginRegistry = _dereq_(18); var EventPluginUtils = _dereq_(19); var ReactErrorUtils = _dereq_(64); var accumulateInto = _dereq_(113); var forEachAccumulated = _dereq_(121); var invariant = _dereq_(157); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? "development" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : void 0; var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[inst._rootNodeID] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[inst._rootNodeID]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { delete bankForRegistrationName[inst._rootNodeID]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { for (var registrationName in listenerBank) { if (!listenerBank[registrationName][inst._rootNodeID]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][inst._rootNodeID]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? "development" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; },{"113":113,"121":121,"157":157,"18":18,"19":19,"64":64}],18:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 EventPluginRegistry */ 'use strict'; var invariant = _dereq_(157); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !PluginModule.extractEvents ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : void 0; EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, PluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; if ("development" !== 'production') { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: "development" !== 'production' ? {} : null, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (InjectedEventPluginOrder) { !!EventPluginOrder ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : void 0; // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { !!namesToPlugins[pluginName] ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : void 0; namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if ("development" !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; },{"157":157}],19:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 EventPluginUtils */ 'use strict'; var EventConstants = _dereq_(16); var ReactErrorUtils = _dereq_(64); var invariant = _dereq_(157); var warning = _dereq_(167); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if ("development" !== 'production') { "development" !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if ("development" !== 'production') { "development" !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("development" !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; "development" !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("development" !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? "development" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; },{"157":157,"16":16,"167":167,"64":64}],20:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 EventPropagators */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPluginUtils = _dereq_(19); var accumulateInto = _dereq_(113); var forEachAccumulated = _dereq_(121); var warning = _dereq_(167); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, upwards, event) { if ("development" !== 'production') { "development" !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; },{"113":113,"121":121,"16":16,"167":167,"17":17,"19":19}],21:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 FallbackCompositionState */ 'use strict'; var _assign = _dereq_(168); var PooledClass = _dereq_(25); var getTextContentAccessor = _dereq_(129); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; },{"129":129,"168":168,"25":25}],22:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 HTMLDOMPropertyConfig */ 'use strict'; var DOMProperty = _dereq_(10); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {} }; module.exports = HTMLDOMPropertyConfig; },{"10":10}],23:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 KeyEscapeUtils */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {*} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; },{}],24:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 LinkedValueUtils */ 'use strict'; var ReactPropTypes = _dereq_(84); var ReactPropTypeLocations = _dereq_(83); var invariant = _dereq_(157); var warning = _dereq_(167); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : void 0; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: ReactPropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); "development" !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; },{"157":157,"167":167,"83":83,"84":84}],25:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 PooledClass */ 'use strict'; var invariant = _dereq_(157); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; },{"157":157}],26:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 React */ 'use strict'; var _assign = _dereq_(168); var ReactChildren = _dereq_(29); var ReactComponent = _dereq_(31); var ReactClass = _dereq_(30); var ReactDOMFactories = _dereq_(45); var ReactElement = _dereq_(61); var ReactElementValidator = _dereq_(62); var ReactPropTypes = _dereq_(84); var ReactVersion = _dereq_(94); var onlyChild = _dereq_(134); var warning = _dereq_(167); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if ("development" !== 'production') { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if ("development" !== 'production') { var warned = false; __spread = function () { "development" !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; module.exports = React; },{"134":134,"167":167,"168":168,"29":29,"30":30,"31":31,"45":45,"61":61,"62":62,"84":84,"94":94}],27:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactBrowserEventEmitter */ 'use strict'; var _assign = _dereq_(168); var EventConstants = _dereq_(16); var EventPluginRegistry = _dereq_(18); var ReactEventEmitterMixin = _dereq_(65); var ViewportMetrics = _dereq_(112); var getVendorPrefixedEventName = _dereq_(130); var isEventSupported = _dereq_(132); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * EventPluginHub.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = document.createEvent && 'pageX' in document.createEvent('MouseEvent'); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; },{"112":112,"130":130,"132":132,"16":16,"168":168,"18":18,"65":65}],28:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactChildReconciler */ 'use strict'; var ReactReconciler = _dereq_(86); var instantiateReactComponent = _dereq_(131); var KeyEscapeUtils = _dereq_(23); var shouldUpdateReactComponent = _dereq_(139); var traverseAllChildren = _dereq_(140); var warning = _dereq_(167); function instantiateChild(childInstances, child, name) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if ("development" !== 'production') { "development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', KeyEscapeUtils.unescape(name)) : void 0; } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context) { if (nestedChildNodes == null) { return null; } var childInstances = {}; traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, removedNodes, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { removedNodes[name] = ReactReconciler.getNativeNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getNativeNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } } }; module.exports = ReactChildReconciler; },{"131":131,"139":139,"140":140,"167":167,"23":23,"86":86}],29:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactChildren */ 'use strict'; var PooledClass = _dereq_(25); var ReactElement = _dereq_(61); var emptyFunction = _dereq_(149); var traverseAllChildren = _dereq_(140); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func; var context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result; var keyPrefix = bookKeeping.keyPrefix; var func = bookKeeping.func; var context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; },{"140":140,"149":149,"25":25,"61":61}],30:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactClass */ 'use strict'; var _assign = _dereq_(168); var ReactComponent = _dereq_(31); var ReactElement = _dereq_(61); var ReactPropTypeLocations = _dereq_(83); var ReactPropTypeLocationNames = _dereq_(82); var ReactNoopUpdateQueue = _dereq_(80); var emptyObject = _dereq_(150); var invariant = _dereq_(157); var keyMirror = _dereq_(160); var keyOf = _dereq_(161); var warning = _dereq_(167); var MIXINS_KEY = keyOf({ mixins: null }); /** * Policies that describe methods in `ReactClassInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ "development" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } !(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.') : invariant(false) : void 0; !!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("development" !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : void 0; var isInherited = name in Constructor; !!isInherited ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("development" !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { "development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { "development" !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { var Constructor = function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("development" !== 'production') { "development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ("development" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : void 0; this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("development" !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0; "development" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; },{"150":150,"157":157,"160":160,"161":161,"167":167,"168":168,"31":31,"61":61,"80":80,"82":82,"83":83}],31:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactComponent */ 'use strict'; var ReactNoopUpdateQueue = _dereq_(80); var ReactInstrumentation = _dereq_(71); var canDefineProperty = _dereq_(115); var emptyObject = _dereq_(150); var invariant = _dereq_(157); var warning = _dereq_(167); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : void 0; if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetState(); "development" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if ("development" !== 'production') { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { "development" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; },{"115":115,"150":150,"157":157,"167":167,"71":71,"80":80}],32:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactComponentBrowserEnvironment */ 'use strict'; var DOMChildrenOperations = _dereq_(7); var ReactDOMIDOperations = _dereq_(47); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function (rootNodeID) {} }; module.exports = ReactComponentBrowserEnvironment; },{"47":47,"7":7}],33:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactComponentEnvironment */ 'use strict'; var invariant = _dereq_(157); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. */ unmountIDFromEnvironment: null, /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? "development" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : void 0; ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; },{"157":157}],34:[function(_dereq_,module,exports){ /** * Copyright 2016-present, 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 ReactComponentTreeDevtool */ 'use strict'; var invariant = _dereq_(157); var tree = {}; var rootIDs = []; function updateTree(id, update) { if (!tree[id]) { tree[id] = { parentID: null, ownerID: null, text: null, childIDs: [], displayName: 'Unknown', isMounted: false, updateCount: 0 }; } update(tree[id]); } function purgeDeep(id) { var item = tree[id]; if (item) { var childIDs = item.childIDs; delete tree[id]; childIDs.forEach(purgeDeep); } } var ReactComponentTreeDevtool = { onSetDisplayName: function (id, displayName) { updateTree(id, function (item) { return item.displayName = displayName; }); }, onSetChildren: function (id, nextChildIDs) { updateTree(id, function (item) { var prevChildIDs = item.childIDs; item.childIDs = nextChildIDs; nextChildIDs.forEach(function (nextChildID) { var nextChild = tree[nextChildID]; !nextChild ? "development" !== 'production' ? invariant(false, 'Expected devtool events to fire for the child ' + 'before its parent includes it in onSetChildren().') : invariant(false) : void 0; !(nextChild.displayName != null) ? "development" !== 'production' ? invariant(false, 'Expected onSetDisplayName() to fire for the child ' + 'before its parent includes it in onSetChildren().') : invariant(false) : void 0; !(nextChild.childIDs != null || nextChild.text != null) ? "development" !== 'production' ? invariant(false, 'Expected onSetChildren() or onSetText() to fire for the child ' + 'before its parent includes it in onSetChildren().') : invariant(false) : void 0; !nextChild.isMounted ? "development" !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child ' + 'before its parent includes it in onSetChildren().') : invariant(false) : void 0; if (prevChildIDs.indexOf(nextChildID) === -1) { nextChild.parentID = id; } }); }); }, onSetOwner: function (id, ownerID) { updateTree(id, function (item) { return item.ownerID = ownerID; }); }, onSetText: function (id, text) { updateTree(id, function (item) { return item.text = text; }); }, onMountComponent: function (id) { updateTree(id, function (item) { return item.isMounted = true; }); }, onMountRootComponent: function (id) { rootIDs.push(id); }, onUpdateComponent: function (id) { updateTree(id, function (item) { return item.updateCount++; }); }, onUnmountComponent: function (id) { updateTree(id, function (item) { return item.isMounted = false; }); rootIDs = rootIDs.filter(function (rootID) { return rootID !== id; }); }, purgeUnmountedComponents: function () { Object.keys(tree).filter(function (id) { return !tree[id].isMounted; }).forEach(purgeDeep); }, isMounted: function (id) { var item = tree[id]; return item ? item.isMounted : false; }, getChildIDs: function (id) { var item = tree[id]; return item ? item.childIDs : []; }, getDisplayName: function (id) { var item = tree[id]; return item ? item.displayName : 'Unknown'; }, getOwnerID: function (id) { var item = tree[id]; return item ? item.ownerID : null; }, getParentID: function (id) { var item = tree[id]; return item ? item.parentID : null; }, getText: function (id) { var item = tree[id]; return item ? item.text : null; }, getUpdateCount: function (id) { var item = tree[id]; return item ? item.updateCount : 0; }, getRootIDs: function () { return rootIDs; }, getRegisteredIDs: function () { return Object.keys(tree); } }; module.exports = ReactComponentTreeDevtool; },{"157":157}],35:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactCompositeComponent */ 'use strict'; var _assign = _dereq_(168); var ReactComponentEnvironment = _dereq_(33); var ReactCurrentOwner = _dereq_(36); var ReactElement = _dereq_(61); var ReactErrorUtils = _dereq_(64); var ReactInstanceMap = _dereq_(70); var ReactInstrumentation = _dereq_(71); var ReactNodeTypes = _dereq_(79); var ReactPropTypeLocations = _dereq_(83); var ReactPropTypeLocationNames = _dereq_(82); var ReactReconciler = _dereq_(86); var ReactUpdateQueue = _dereq_(92); var emptyObject = _dereq_(150); var invariant = _dereq_(157); var shouldUpdateReactComponent = _dereq_(139); var warning = _dereq_(167); function getDeclarationErrorAddendum(component) { var owner = component._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if ("development" !== 'production') { "development" !== 'production' ? warning(element === null || element === false || ReactElement.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; } } function invokeComponentDidMountWithTimer() { var publicInstance = this._instance; if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidMount'); } publicInstance.componentDidMount(); if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidMount'); } } function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) { var publicInstance = this._instance; if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidUpdate'); } publicInstance.componentDidUpdate(prevProps, prevState, prevContext); if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidUpdate'); } } function shouldConstruct(Component) { return Component.prototype && Component.prototype.isReactComponent; } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = null; this._instance = null; this._nativeParent = null; this._nativeContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} nativeParent * @param {?object} nativeContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { this._context = context; this._mountOrder = nextMountID++; this._nativeParent = nativeParent; this._nativeContainerInfo = nativeContainerInfo; var publicProps = this._processProps(this._currentElement.props); var publicContext = this._processContext(context); var Component = this._currentElement.type; // Initialize the public class var inst = this._constructComponent(publicProps, publicContext); var renderedElement; // Support functional components if (!shouldConstruct(Component) && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || ReactElement.isValidElement(inst)) ? "development" !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : invariant(false) : void 0; inst = new StatelessComponent(Component); } if ("development" !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { "development" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; "development" !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = ReactUpdateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if ("development" !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. "development" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } if (inst.componentDidMount) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this); } else { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } } return markup; }, _constructComponent: function (publicProps, publicContext) { if ("development" !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(publicProps, publicContext); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(publicProps, publicContext); } }, _constructComponentWithoutOwner: function (publicProps, publicContext) { var Component = this._currentElement.type; var instanceOrElement; if (shouldConstruct(Component)) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'ctor'); } } instanceOrElement = new Component(publicProps, publicContext, ReactUpdateQueue); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'ctor'); } } } else { // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render'); } } instanceOrElement = Component(publicProps, publicContext, ReactUpdateQueue); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render'); } } } return instanceOrElement; }, performInitialMountWithErrorHandling: function (renderedElement, nativeParent, nativeContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, nativeParent, nativeContainerInfo, transaction, context) { var inst = this._instance; if (inst.componentWillMount) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillMount'); } } inst.componentWillMount(); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillMount'); } } // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } this._renderedNodeType = ReactNodeTypes.getType(renderedElement); this._renderedComponent = this._instantiateReactComponent(renderedElement); var markup = ReactReconciler.mountComponent(this._renderedComponent, transaction, nativeParent, nativeContainerInfo, this._processChildContext(context)); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, this._renderedComponent._debugID !== 0 ? [this._renderedComponent._debugID] : []); } } return markup; }, getNativeNode: function () { return ReactReconciler.getNativeNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUnmount'); } } if (safely) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else { inst.componentWillUnmount(); } if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUnmount'); } } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = null; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if ("development" !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); } var childContext = inst.getChildContext && inst.getChildContext(); if ("development" !== 'production') { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } if (childContext) { !(typeof Component.childContextTypes === 'object') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : void 0; if ("development" !== 'production') { this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : void 0; } return _assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function (newProps) { if ("development" !== 'production') { var Component = this._currentElement.type; if (Component.propTypes) { this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function (propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : void 0; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // top-level render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module "development" !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : void 0; } else { "development" !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : void 0; } } } } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; var willReceive = false; var nextContext; var nextProps; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } // Distinguish between a props update versus a simple state update if (prevParentElement === nextParentElement) { // Skip checking prop types again -- we don't read inst.props to avoid // warning for DOM component props in this upgrade nextProps = nextParentElement.props; } else { nextProps = this._processProps(nextParentElement.props); willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillReceiveProps'); } } inst.componentWillReceiveProps(nextProps, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillReceiveProps'); } } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate && inst.shouldComponentUpdate) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'shouldComponentUpdate'); } } shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'shouldComponentUpdate'); } } } if ("development" !== 'production') { "development" !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } this._updateBatchNumber = null; if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = _assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUpdate'); } } inst.componentWillUpdate(nextProps, nextState, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUpdate'); } } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext), this); } else { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldNativeNode = ReactReconciler.getNativeNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, false); this._renderedNodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, transaction, this._nativeParent, this._nativeContainerInfo, this._processChildContext(context)); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, this._renderedComponent._debugID !== 0 ? [this._renderedComponent._debugID] : []); } } this._replaceNodeWithMarkup(oldNativeNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldNativeNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldNativeNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render'); } } var renderedComponent = inst.render(); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render'); } } if ("development" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedComponent === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function () { var renderedComponent; ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } !( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? "development" !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : void 0; return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : void 0; var publicComponentInstance = component.getPublicInstance(); if ("development" !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; "development" !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (inst instanceof StatelessComponent) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; },{"139":139,"150":150,"157":157,"167":167,"168":168,"33":33,"36":36,"61":61,"64":64,"70":70,"71":71,"79":79,"82":82,"83":83,"86":86,"92":92}],36:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOM */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = _dereq_(41); var ReactDefaultInjection = _dereq_(60); var ReactMount = _dereq_(74); var ReactReconciler = _dereq_(86); var ReactUpdates = _dereq_(93); var ReactVersion = _dereq_(94); var findDOMNode = _dereq_(119); var getNativeComponentFromComposite = _dereq_(127); var renderSubtreeIntoContainer = _dereq_(136); var warning = _dereq_(167); ReactDefaultInjection.inject(); var React = { findDOMNode: findDOMNode, render: ReactMount.render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* eslint-enable camelcase */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getNativeComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if ("development" !== 'production') { var ExecutionEnvironment = _dereq_(143); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; "development" !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; "development" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { "development" !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } module.exports = React; },{"119":119,"127":127,"136":136,"143":143,"167":167,"41":41,"60":60,"74":74,"86":86,"93":93,"94":94}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMButton */ 'use strict'; var DisabledInputUtils = _dereq_(14); /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = { getNativeProps: DisabledInputUtils.getNativeProps }; module.exports = ReactDOMButton; },{"14":14}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMComponent */ /* global hasOwnProperty:true */ 'use strict'; var _assign = _dereq_(168); var AutoFocusUtils = _dereq_(1); var CSSPropertyOperations = _dereq_(4); var DOMLazyTree = _dereq_(8); var DOMNamespaces = _dereq_(9); var DOMProperty = _dereq_(10); var DOMPropertyOperations = _dereq_(11); var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPluginRegistry = _dereq_(18); var ReactBrowserEventEmitter = _dereq_(27); var ReactComponentBrowserEnvironment = _dereq_(32); var ReactDOMButton = _dereq_(38); var ReactDOMComponentFlags = _dereq_(40); var ReactDOMComponentTree = _dereq_(41); var ReactDOMInput = _dereq_(48); var ReactDOMOption = _dereq_(50); var ReactDOMSelect = _dereq_(51); var ReactDOMTextarea = _dereq_(55); var ReactInstrumentation = _dereq_(71); var ReactMultiChild = _dereq_(75); var ReactServerRenderingTransaction = _dereq_(90); var emptyFunction = _dereq_(149); var escapeTextContentForBrowser = _dereq_(118); var invariant = _dereq_(157); var isEventSupported = _dereq_(132); var keyOf = _dereq_(161); var shallowEqual = _dereq_(166); var validateDOMNesting = _dereq_(141); var warning = _dereq_(167); var Flags = ReactDOMComponentFlags; var deleteListener = EventPluginHub.deleteListener; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = keyOf({ style: null }); var HTML = keyOf({ __html: null }); var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined because undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; "development" !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : invariant(false) : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? "development" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "development" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; "development" !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0; "development" !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0; } !(props.style == null || typeof props.style === 'object') ? "development" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : void 0; } function enqueuePutListener(inst, registrationName, listener, transaction) { if (transaction instanceof ReactServerRenderingTransaction) { return; } if ("development" !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. "development" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._nativeContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } var setContentChildForInstrumentation = emptyFunction; if ("development" !== 'production') { setContentChildForInstrumentation = function (contentToUse) { var debugID = this._debugID; var contentDebugID = debugID + '#text'; this._contentDebugID = contentDebugID; ReactInstrumentation.debugTool.onSetDisplayName(contentDebugID, '#text'); ReactInstrumentation.debugTool.onSetText(contentDebugID, '' + contentToUse); ReactInstrumentation.debugTool.onMountComponent(contentDebugID); ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); }; } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? "development" !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : void 0; var node = getNode(inst); !node ? "development" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); } } break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; // NOTE: menuitem's close tag should be omitted, but that causes problems. var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? "development" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; validateDangerousTag(tag); this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._nativeNode = null; this._nativeParent = null; this._rootNodeID = null; this._domID = null; this._nativeContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if ("development" !== 'production') { this._ancestorInfo = null; this._contentDebugID = null; } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the containing DOM component instance * @param {?object} info about the native container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = nativeContainerInfo._idCounter++; this._nativeParent = nativeParent; this._nativeContainerInfo = nativeContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'iframe': case 'object': case 'img': case 'form': case 'video': case 'audio': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'button': props = ReactDOMButton.getNativeProps(this, props, nativeParent); break; case 'input': ReactDOMInput.mountWrapper(this, props, nativeParent); props = ReactDOMInput.getNativeProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'option': ReactDOMOption.mountWrapper(this, props, nativeParent); props = ReactDOMOption.getNativeProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, nativeParent); props = ReactDOMSelect.getNativeProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, nativeParent); props = ReactDOMTextarea.getNativeProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (nativeParent != null) { namespaceURI = nativeParent._namespaceURI; parentTag = nativeParent._tag; } else if (nativeContainerInfo._tag) { namespaceURI = nativeContainerInfo._namespaceURI; parentTag = nativeContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if ("development" !== 'production') { var parentInfo; if (nativeParent != null) { parentInfo = nativeParent._ancestorInfo; } else if (nativeContainerInfo._tag) { parentInfo = nativeContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); var type = this._currentElement.type; div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else { el = ownerDocument.createElement(this._currentElement.type, props.is || null); } } else { el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._nativeParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'button': case 'input': case 'select': case 'textarea': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if ("development" !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = _assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._nativeParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); if ("development" !== 'production') { setContentChildForInstrumentation.call(this, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node if ("development" !== 'production') { setContentChildForInstrumentation.call(this, contentToUse); } DOMLazyTree.queueText(lazyTree, contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'button': lastProps = ReactDOMButton.getNativeProps(this, lastProps); nextProps = ReactDOMButton.getNativeProps(this, nextProps); break; case 'input': ReactDOMInput.updateWrapper(this); lastProps = ReactDOMInput.getNativeProps(this, lastProps); nextProps = ReactDOMInput.getNativeProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getNativeProps(this, lastProps); nextProps = ReactDOMOption.getNativeProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getNativeProps(this, lastProps); nextProps = ReactDOMSelect.getNativeProps(this, nextProps); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); break; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction); this._updateDOMChildren(lastProps, nextProps, transaction, context); if (this._tag === 'select') { // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if ("development" !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = _assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); if ("development" !== 'production') { this._contentDebugID = this._debugID + '#text'; setContentChildForInstrumentation.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { if ("development" !== 'production') { if (this._contentDebugID) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); this._contentDebugID = null; } } this.updateChildren(nextChildren, transaction, context); } }, getNativeNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely) { switch (this._tag) { case 'iframe': case 'object': case 'img': case 'form': case 'video': case 'audio': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ !false ? "development" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : void 0; break; } this.unmountChildren(safely); ReactDOMComponentTree.uncacheNode(this); EventPluginHub.deleteAllListeners(this); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._domID = null; this._wrapperState = null; if ("development" !== 'production') { if (this._contentDebugID) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); this._contentDebugID = null; } } }, getPublicInstance: function () { return getNode(this); } }; _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; },{"1":1,"10":10,"11":11,"118":118,"132":132,"141":141,"149":149,"157":157,"16":16,"161":161,"166":166,"167":167,"168":168,"17":17,"18":18,"27":27,"32":32,"38":38,"4":4,"40":40,"41":41,"48":48,"50":50,"51":51,"55":55,"71":71,"75":75,"8":8,"9":9,"90":90}],40:[function(_dereq_,module,exports){ /** * Copyright 2015-present, 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 ReactDOMComponentFlags */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; },{}],41:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMComponentTree */ 'use strict'; var DOMProperty = _dereq_(10); var ReactDOMComponentFlags = _dereq_(40); var invariant = _dereq_(157); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Drill down (through composites and empty components) until we get a native or * native text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedNativeOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_nativeNode` on the rendered native/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var nativeInst = getRenderedNativeOrTextFromComponent(inst); nativeInst._nativeNode = node; node[internalInstanceKey] = nativeInst; } function uncacheNode(inst) { var node = inst._nativeNode; if (node) { delete node[internalInstanceKey]; inst._nativeNode = null; } } /** * Populate `_nativeNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedNativeOrTextFromComponent(childInst)._domID; if (childID == null) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (childNode.nodeType === 1 && childNode.getAttribute(ATTR_NAME) === String(childID) || childNode.nodeType === 8 && childNode.nodeValue === ' react-text: ' + childID + ' ' || childNode.nodeType === 8 && childNode.nodeValue === ' react-empty: ' + childID + ' ') { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. !false ? "development" !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : invariant(false) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._nativeNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._nativeNode !== undefined) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : void 0; if (inst._nativeNode) { return inst._nativeNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._nativeNode) { parents.push(inst); !inst._nativeParent ? "development" !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : invariant(false) : void 0; inst = inst._nativeParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._nativeNode); } return inst._nativeNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; },{"10":10,"157":157,"40":40}],42:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMContainerInfo */ 'use strict'; var validateDOMNesting = _dereq_(141); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if ("development" !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; },{"141":141}],43:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMDebugTool */ 'use strict'; var ReactDOMUnknownPropertyDevtool = _dereq_(57); var warning = _dereq_(167); var eventHandlers = []; var handlerDoesThrowForEvent = {}; function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) { if ("development" !== 'production') { eventHandlers.forEach(function (handler) { try { if (handler[handlerFunctionName]) { handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5); } } catch (e) { "development" !== 'production' ? warning(!handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e.message) : void 0; handlerDoesThrowForEvent[handlerFunctionName] = true; } }); } } var ReactDOMDebugTool = { addDevtool: function (devtool) { eventHandlers.push(devtool); }, removeDevtool: function (devtool) { for (var i = 0; i < eventHandlers.length; i++) { if (eventHandlers[i] === devtool) { eventHandlers.splice(i, 1); i--; } } }, onCreateMarkupForProperty: function (name, value) { emitEvent('onCreateMarkupForProperty', name, value); }, onSetValueForProperty: function (node, name, value) { emitEvent('onSetValueForProperty', node, name, value); }, onDeleteValueForProperty: function (node, name) { emitEvent('onDeleteValueForProperty', node, name); } }; ReactDOMDebugTool.addDevtool(ReactDOMUnknownPropertyDevtool); module.exports = ReactDOMDebugTool; },{"167":167,"57":57}],44:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactDOMEmptyComponent */ 'use strict'; var _assign = _dereq_(168); var DOMLazyTree = _dereq_(8); var ReactDOMComponentTree = _dereq_(41); var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._nativeNode = null; this._nativeParent = null; this._nativeContainerInfo = null; this._domID = null; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { var domID = nativeContainerInfo._idCounter++; this._domID = domID; this._nativeParent = nativeParent; this._nativeContainerInfo = nativeContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getNativeNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; },{"168":168,"41":41,"8":8}],45:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMFactories */ 'use strict'; var ReactElement = _dereq_(61); var ReactElementValidator = _dereq_(62); var mapObject = _dereq_(162); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if ("development" !== 'production') { return ReactElementValidator.createFactory(tag); } return ReactElement.createFactory(tag); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = mapObject({ a: 'a', abbr: 'abbr', address: 'address', area: 'area', article: 'article', aside: 'aside', audio: 'audio', b: 'b', base: 'base', bdi: 'bdi', bdo: 'bdo', big: 'big', blockquote: 'blockquote', body: 'body', br: 'br', button: 'button', canvas: 'canvas', caption: 'caption', cite: 'cite', code: 'code', col: 'col', colgroup: 'colgroup', data: 'data', datalist: 'datalist', dd: 'dd', del: 'del', details: 'details', dfn: 'dfn', dialog: 'dialog', div: 'div', dl: 'dl', dt: 'dt', em: 'em', embed: 'embed', fieldset: 'fieldset', figcaption: 'figcaption', figure: 'figure', footer: 'footer', form: 'form', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', head: 'head', header: 'header', hgroup: 'hgroup', hr: 'hr', html: 'html', i: 'i', iframe: 'iframe', img: 'img', input: 'input', ins: 'ins', kbd: 'kbd', keygen: 'keygen', label: 'label', legend: 'legend', li: 'li', link: 'link', main: 'main', map: 'map', mark: 'mark', menu: 'menu', menuitem: 'menuitem', meta: 'meta', meter: 'meter', nav: 'nav', noscript: 'noscript', object: 'object', ol: 'ol', optgroup: 'optgroup', option: 'option', output: 'output', p: 'p', param: 'param', picture: 'picture', pre: 'pre', progress: 'progress', q: 'q', rp: 'rp', rt: 'rt', ruby: 'ruby', s: 's', samp: 'samp', script: 'script', section: 'section', select: 'select', small: 'small', source: 'source', span: 'span', strong: 'strong', style: 'style', sub: 'sub', summary: 'summary', sup: 'sup', table: 'table', tbody: 'tbody', td: 'td', textarea: 'textarea', tfoot: 'tfoot', th: 'th', thead: 'thead', time: 'time', title: 'title', tr: 'tr', track: 'track', u: 'u', ul: 'ul', 'var': 'var', video: 'video', wbr: 'wbr', // SVG circle: 'circle', clipPath: 'clipPath', defs: 'defs', ellipse: 'ellipse', g: 'g', image: 'image', line: 'line', linearGradient: 'linearGradient', mask: 'mask', path: 'path', pattern: 'pattern', polygon: 'polygon', polyline: 'polyline', radialGradient: 'radialGradient', rect: 'rect', stop: 'stop', svg: 'svg', text: 'text', tspan: 'tspan' }, createDOMFactory); module.exports = ReactDOMFactories; },{"162":162,"61":61,"62":62}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMFeatureFlags */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: true }; module.exports = ReactDOMFeatureFlags; },{}],47:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMIDOperations */ 'use strict'; var DOMChildrenOperations = _dereq_(7); var ReactDOMComponentTree = _dereq_(41); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; },{"41":41,"7":7}],48:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMInput */ 'use strict'; var _assign = _dereq_(168); var DisabledInputUtils = _dereq_(14); var DOMPropertyOperations = _dereq_(11); var LinkedValueUtils = _dereq_(24); var ReactDOMComponentTree = _dereq_(41); var ReactUpdates = _dereq_(93); var invariant = _dereq_(157); var warning = _dereq_(167); var didWarnValueLink = false; var didWarnCheckedLink = false; var didWarnValueNull = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } function warnIfValueIsNull(props) { if (props != null && props.value === null && !didWarnValueNull) { "development" !== 'production' ? warning(false, '`value` prop on `input` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : void 0; didWarnValueNull = true; } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getNativeProps: function (inst, props) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var nativeProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined }, DisabledInputUtils.getNativeProps(inst, props), { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); var owner = inst._currentElement._owner; if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.checkedLink !== undefined && !didWarnCheckedLink) { "development" !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnCheckedLink = true; } if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { "development" !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnValueDefaultValue = true; } warnIfValueIsNull(props); } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null, listeners: null, onChange: _handleChange.bind(inst) }; if ("development" !== 'production') { inst._wrapperState.controlled = props.checked !== undefined || props.value !== undefined; } }, updateWrapper: function (inst) { var props = inst._currentElement.props; if ("development" !== 'production') { warnIfValueIsNull(props); var initialValue = inst._wrapperState.initialChecked || inst._wrapperState.initialValue; var defaultValue = props.defaultChecked || props.defaultValue; var controlled = props.checked !== undefined || props.value !== undefined; var owner = inst._currentElement._owner; if ((initialValue || !inst._wrapperState.controlled) && controlled && !didWarnUncontrolledToControlled) { "development" !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && (defaultValue || !controlled) && !didWarnControlledToUncontrolled) { "development" !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(this); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; },{"11":11,"14":14,"157":157,"167":167,"168":168,"24":24,"41":41,"93":93}],49:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMInstrumentation */ 'use strict'; var ReactDOMDebugTool = _dereq_(43); module.exports = { debugTool: ReactDOMDebugTool }; },{"43":43}],50:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMOption */ 'use strict'; var _assign = _dereq_(168); var ReactChildren = _dereq_(29); var ReactDOMComponentTree = _dereq_(41); var ReactDOMSelect = _dereq_(51); var warning = _dereq_(167); /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, nativeParent) { // TODO (yungsters): Remove support for `selected` in <option>. if ("development" !== 'production') { "development" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (nativeParent != null) { var selectParent = nativeParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._nativeParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === '' + props.value) { selected = true; break; } } } else { selected = '' + selectValue === '' + props.value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getNativeProps: function (inst, props) { var nativeProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { nativeProps.selected = inst._wrapperState.selected; } var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { "development" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); if (content) { nativeProps.children = content; } return nativeProps; } }; module.exports = ReactDOMOption; },{"167":167,"168":168,"29":29,"41":41,"51":51}],51:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMSelect */ 'use strict'; var _assign = _dereq_(168); var DisabledInputUtils = _dereq_(14); var LinkedValueUtils = _dereq_(24); var ReactDOMComponentTree = _dereq_(41); var ReactUpdates = _dereq_(93); var warning = _dereq_(167); var didWarnValueLink = false; var didWarnValueNull = false; var didWarnValueDefaultValue = false; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function warnIfValueIsNull(props) { if (props != null && props.value === null && !didWarnValueNull) { "development" !== 'production' ? warning(false, '`value` prop on `select` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : void 0; didWarnValueNull = true; } } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } if (props.multiple) { "development" !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else { "development" !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getNativeProps: function (inst, props) { return _assign({}, DisabledInputUtils.getNativeProps(inst, props), { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if ("development" !== 'production') { checkSelectPropTypes(inst, props); warnIfValueIsNull(props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; if ("development" !== 'production') { warnIfValueIsNull(props); } // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); if (this._rootNodeID) { this._wrapperState.pendingUpdate = true; } ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; },{"14":14,"167":167,"168":168,"24":24,"41":41,"93":93}],52:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = _dereq_(143); var getNodeForCharacterOffset = _dereq_(128); var getTextContentAccessor = _dereq_(129); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"128":128,"129":129,"143":143}],53:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMServer */ 'use strict'; var ReactDefaultInjection = _dereq_(60); var ReactServerRendering = _dereq_(89); var ReactVersion = _dereq_(94); ReactDefaultInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; },{"60":60,"89":89,"94":94}],54:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMTextComponent */ 'use strict'; var _assign = _dereq_(168); var DOMChildrenOperations = _dereq_(7); var DOMLazyTree = _dereq_(8); var ReactDOMComponentTree = _dereq_(41); var ReactInstrumentation = _dereq_(71); var escapeTextContentForBrowser = _dereq_(118); var invariant = _dereq_(157); var validateDOMNesting = _dereq_(141); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._nativeNode = null; this._nativeParent = null; // Properties this._domID = null; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetText(this._debugID, this._stringText); var parentInfo; if (nativeParent != null) { parentInfo = nativeParent._ancestorInfo; } else if (nativeContainerInfo != null) { parentInfo = nativeContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting('#text', this, parentInfo); } } var domID = nativeContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._nativeParent = nativeParent; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getNativeNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetText(this._debugID, nextStringText); } } } }, getNativeNode: function () { var nativeNode = this._commentNodes; if (nativeNode) { return nativeNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? "development" !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : invariant(false) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } nativeNode = [this._nativeNode, this._closingComment]; this._commentNodes = nativeNode; return nativeNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMTextComponent; },{"118":118,"141":141,"157":157,"168":168,"41":41,"7":7,"71":71,"8":8}],55:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMTextarea */ 'use strict'; var _assign = _dereq_(168); var DisabledInputUtils = _dereq_(14); var DOMPropertyOperations = _dereq_(11); var LinkedValueUtils = _dereq_(24); var ReactDOMComponentTree = _dereq_(41); var ReactUpdates = _dereq_(93); var invariant = _dereq_(157); var warning = _dereq_(167); var didWarnValueLink = false; var didWarnValueNull = false; var didWarnValDefaultVal = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } function warnIfValueIsNull(props) { if (props != null && props.value === null && !didWarnValueNull) { "development" !== 'production' ? warning(false, '`value` prop on `textarea` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : void 0; didWarnValueNull = true; } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getNativeProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. var nativeProps = _assign({}, DisabledInputUtils.getNativeProps(inst, props), { defaultValue: undefined, value: undefined, children: inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { "development" !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } warnIfValueIsNull(props); } var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if ("development" !== 'production') { "development" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? "development" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? "development" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue), listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; if ("development" !== 'production') { warnIfValueIsNull(props); } var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; },{"11":11,"14":14,"157":157,"167":167,"168":168,"24":24,"41":41,"93":93}],56:[function(_dereq_,module,exports){ /** * Copyright 2015-present, 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 ReactDOMTreeTraversal */ 'use strict'; var invariant = _dereq_(157); /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { !('_nativeNode' in instA) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : void 0; !('_nativeNode' in instB) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : void 0; var depthA = 0; for (var tempA = instA; tempA; tempA = tempA._nativeParent) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = tempB._nativeParent) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = instA._nativeParent; depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = instB._nativeParent; depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = instA._nativeParent; instB = instB._nativeParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { !('_nativeNode' in instA) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : invariant(false) : void 0; !('_nativeNode' in instB) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : invariant(false) : void 0; while (instB) { if (instB === instA) { return true; } instB = instB._nativeParent; } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { !('_nativeNode' in inst) ? "development" !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : invariant(false) : void 0; return inst._nativeParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = inst._nativeParent; } var i; for (i = path.length; i-- > 0;) { fn(path[i], false, arg); } for (i = 0; i < path.length; i++) { fn(path[i], true, arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = from._nativeParent; } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = to._nativeParent; } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], true, argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], false, argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; },{"157":157}],57:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDOMUnknownPropertyDevtool */ 'use strict'; var DOMProperty = _dereq_(10); var EventPluginRegistry = _dereq_(18); var warning = _dereq_(167); if ("development" !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function (name) { if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) { return; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. "development" !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : void 0; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; "development" !== 'production' ? warning(registrationName == null, 'Unknown event handler property %s. Did you mean `%s`?', name, registrationName) : void 0; }; } var ReactDOMUnknownPropertyDevtool = { onCreateMarkupForProperty: function (name, value) { warnUnknownProperty(name); }, onSetValueForProperty: function (node, name, value) { warnUnknownProperty(name); }, onDeleteValueForProperty: function (node, name) { warnUnknownProperty(name); } }; module.exports = ReactDOMUnknownPropertyDevtool; },{"10":10,"167":167,"18":18}],58:[function(_dereq_,module,exports){ /** * Copyright 2016-present, 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 ReactDebugTool */ 'use strict'; var ExecutionEnvironment = _dereq_(143); var performanceNow = _dereq_(165); var warning = _dereq_(167); var eventHandlers = []; var handlerDoesThrowForEvent = {}; function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) { if ("development" !== 'production') { eventHandlers.forEach(function (handler) { try { if (handler[handlerFunctionName]) { handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5); } } catch (e) { "development" !== 'production' ? warning(!handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e.message) : void 0; handlerDoesThrowForEvent[handlerFunctionName] = true; } }); } } var isProfiling = false; var flushHistory = []; var currentFlushNesting = 0; var currentFlushMeasurements = null; var currentFlushStartTime = null; var currentTimerDebugID = null; var currentTimerStartTime = null; var currentTimerType = null; function resetMeasurements() { if ("development" !== 'production') { if (!isProfiling || currentFlushNesting === 0) { currentFlushStartTime = null; currentFlushMeasurements = null; return; } var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements || []; var previousOperations = ReactNativeOperationHistoryDevtool.getHistory(); if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeDevtool.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeDevtool.getOwnerID(id); var parentID = ReactComponentTreeDevtool.getParentID(id); tree[id] = { displayName: ReactComponentTreeDevtool.getDisplayName(id), text: ReactComponentTreeDevtool.getText(id), updateCount: ReactComponentTreeDevtool.getUpdateCount(id), childIDs: ReactComponentTreeDevtool.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID), parentID: parentID }; return tree; }, {}) }); } currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; ReactComponentTreeDevtool.purgeUnmountedComponents(); ReactNativeOperationHistoryDevtool.clearHistory(); } } var ReactDebugTool = { addDevtool: function (devtool) { eventHandlers.push(devtool); }, removeDevtool: function (devtool) { for (var i = 0; i < eventHandlers.length; i++) { if (eventHandlers[i] === devtool) { eventHandlers.splice(i, 1); i--; } } }, beginProfiling: function () { if ("development" !== 'production') { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); } }, endProfiling: function () { if ("development" !== 'production') { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); } }, getFlushHistory: function () { if ("development" !== 'production') { return flushHistory; } }, onBeginFlush: function () { if ("development" !== 'production') { currentFlushNesting++; resetMeasurements(); } emitEvent('onBeginFlush'); }, onEndFlush: function () { if ("development" !== 'production') { resetMeasurements(); currentFlushNesting--; } emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { emitEvent('onBeginLifeCycleTimer', debugID, timerType); if ("development" !== 'production') { if (isProfiling && currentFlushNesting > 0) { "development" !== 'production' ? warning(!currentTimerType, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; currentTimerStartTime = performanceNow(); currentTimerDebugID = debugID; currentTimerType = timerType; } } }, onEndLifeCycleTimer: function (debugID, timerType) { if ("development" !== 'production') { if (isProfiling && currentFlushNesting > 0) { "development" !== 'production' ? warning(currentTimerType === timerType, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime }); currentTimerStartTime = null; currentTimerDebugID = null; currentTimerType = null; } } emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onBeginReconcilerTimer: function (debugID, timerType) { emitEvent('onBeginReconcilerTimer', debugID, timerType); }, onEndReconcilerTimer: function (debugID, timerType) { emitEvent('onEndReconcilerTimer', debugID, timerType); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onNativeOperation: function (debugID, type, payload) { emitEvent('onNativeOperation', debugID, type, payload); }, onSetState: function () { emitEvent('onSetState'); }, onSetDisplayName: function (debugID, displayName) { emitEvent('onSetDisplayName', debugID, displayName); }, onSetChildren: function (debugID, childDebugIDs) { emitEvent('onSetChildren', debugID, childDebugIDs); }, onSetOwner: function (debugID, ownerDebugID) { emitEvent('onSetOwner', debugID, ownerDebugID); }, onSetText: function (debugID, text) { emitEvent('onSetText', debugID, text); }, onMountRootComponent: function (debugID) { emitEvent('onMountRootComponent', debugID); }, onMountComponent: function (debugID) { emitEvent('onMountComponent', debugID); }, onUpdateComponent: function (debugID) { emitEvent('onUpdateComponent', debugID); }, onUnmountComponent: function (debugID) { emitEvent('onUnmountComponent', debugID); } }; if ("development" !== 'production') { var ReactInvalidSetStateWarningDevTool = _dereq_(72); var ReactNativeOperationHistoryDevtool = _dereq_(78); var ReactComponentTreeDevtool = _dereq_(34); ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool); ReactDebugTool.addDevtool(ReactComponentTreeDevtool); ReactDebugTool.addDevtool(ReactNativeOperationHistoryDevtool); var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } } module.exports = ReactDebugTool; },{"143":143,"165":165,"167":167,"34":34,"72":72,"78":78}],59:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDefaultBatchingStrategy */ 'use strict'; var _assign = _dereq_(168); var ReactUpdates = _dereq_(93); var Transaction = _dereq_(111); var emptyFunction = _dereq_(149); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; },{"111":111,"149":149,"168":168,"93":93}],60:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = _dereq_(2); var ChangeEventPlugin = _dereq_(6); var DefaultEventPluginOrder = _dereq_(13); var EnterLeaveEventPlugin = _dereq_(15); var HTMLDOMPropertyConfig = _dereq_(22); var ReactComponentBrowserEnvironment = _dereq_(32); var ReactDOMComponent = _dereq_(39); var ReactDOMComponentTree = _dereq_(41); var ReactDOMEmptyComponent = _dereq_(44); var ReactDOMTreeTraversal = _dereq_(56); var ReactDOMTextComponent = _dereq_(54); var ReactDefaultBatchingStrategy = _dereq_(59); var ReactEventListener = _dereq_(66); var ReactInjection = _dereq_(68); var ReactReconcileTransaction = _dereq_(85); var SVGDOMPropertyConfig = _dereq_(95); var SelectEventPlugin = _dereq_(96); var SimpleEventPlugin = _dereq_(97); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); } module.exports = { inject: inject }; },{"13":13,"15":15,"2":2,"22":22,"32":32,"39":39,"41":41,"44":44,"54":54,"56":56,"59":59,"6":6,"66":66,"68":68,"85":85,"95":95,"96":96,"97":97}],61:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactElement */ 'use strict'; var _assign = _dereq_(168); var ReactCurrentOwner = _dereq_(36); var warning = _dereq_(167); var canDefineProperty = _dereq_(115); // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if ("development" !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if ("development" !== 'production') { "development" !== 'production' ? warning( /* eslint-disable no-proto */ config.__proto__ == null || config.__proto__ === Object.prototype, /* eslint-enable no-proto */ 'React.createElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0; ref = !config.hasOwnProperty('ref') || Object.getOwnPropertyDescriptor(config, 'ref').get ? null : config.ref; key = !config.hasOwnProperty('key') || Object.getOwnPropertyDescriptor(config, 'key').get ? null : '' + config.key; } else { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if ("development" !== 'production') { // Create dummy `key` and `ref` property to `props` to warn users // against its use if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { if (!props.hasOwnProperty('key')) { Object.defineProperty(props, 'key', { get: function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; "development" !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element') : void 0; } return undefined; }, configurable: true }); } if (!props.hasOwnProperty('ref')) { Object.defineProperty(props, 'ref', { get: function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; "development" !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element') : void 0; } return undefined; }, configurable: true }); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if ("development" !== 'production') { "development" !== 'production' ? warning( /* eslint-disable no-proto */ config.__proto__ == null || config.__proto__ === Object.prototype, /* eslint-enable no-proto */ 'React.cloneElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0; } if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; },{"115":115,"167":167,"168":168,"36":36}],62:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactElement = _dereq_(61); var ReactPropTypeLocations = _dereq_(83); var ReactPropTypeLocationNames = _dereq_(82); var ReactCurrentOwner = _dereq_(36); var canDefineProperty = _dereq_(115); var getIteratorFn = _dereq_(126); var invariant = _dereq_(157); var warning = _dereq_(167); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; var loggedTypeFailures = {}; /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var addenda = getAddendaForKeyUse('uniqueKey', element, parentType); if (addenda === null) { // we already showed the warning return; } "development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : void 0; } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} messageType A key used for de-duping warnings. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. * @returns {?object} A set of addenda to use in the warning message, or null * if the warning has already been shown before (and shouldn't be shown again). */ function getAddendaForKeyUse(messageType, element, parentType) { var addendum = getDeclarationErrorAddendum(); if (!addendum) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { addendum = ' Check the top-level render call using <' + parentName + '>.'; } } var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {}); if (memoizer[addendum]) { return null; } memoizer[addendum] = true; var addenda = { parentOrOwner: addendum, url: ' See https://fb.me/react-warning-keys for more information.', childOwner: null }; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } return addenda; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : void 0; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } "development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(); "development" !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : void 0; } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop); } if (typeof componentClass.getDefaultProps === 'function') { "development" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. "development" !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : void 0; var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if ("development" !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { "development" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; },{"115":115,"126":126,"157":157,"167":167,"36":36,"61":61,"82":82,"83":83}],63:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactEmptyComponent */ 'use strict'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; },{}],64:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactErrorUtils */ 'use strict'; var SyntheticDragEvent = _dereq_(101); var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { if (caughtError === null) { caughtError = x; } return undefined; } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if ("development" !== 'production') { var fakeNode; var cacheCanWrapEvent; (function () { /** * IE and Edge don't allow access to the DataTransfer.dropEffect property when * it's wrapped in another event. This function detects whether we're in an * environment that behaves this way. * * @param {*} ev Event that is being tested */ var canWrapEvent = function (ev) { if (!(ev instanceof SyntheticDragEvent)) { return true; } else if (cacheCanWrapEvent !== null) { return cacheCanWrapEvent; } var canAccessDropEffect = false; function handleWrappedEvent() { try { ev.dataTransfer.dropEffect; // eslint-disable-line no-unused-expressions canAccessDropEffect = true; } catch (e) {} } var wrappedEventName = 'react-wrappeddragevent'; var wrappedEvent = document.createEvent('Event'); wrappedEvent.initEvent(wrappedEventName, false, false); fakeNode.addEventListener(wrappedEventName, handleWrappedEvent, false); fakeNode.dispatchEvent(wrappedEvent); fakeNode.removeEventListener(wrappedEventName, handleWrappedEvent, false); cacheCanWrapEvent = canAccessDropEffect; return canAccessDropEffect; }; /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { if (!canWrapEvent(a)) { invokeGuardedCallback(name, func, a, b); return; } var boundFunc = func.bind(null, a, b); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } cacheCanWrapEvent = null; })(); } module.exports = ReactErrorUtils; },{"101":101}],65:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = _dereq_(17); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"17":17}],66:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactEventListener */ 'use strict'; var _assign = _dereq_(168); var EventListener = _dereq_(142); var ExecutionEnvironment = _dereq_(143); var PooledClass = _dereq_(25); var ReactDOMComponentTree = _dereq_(41); var ReactUpdates = _dereq_(93); var getEventTarget = _dereq_(125); var getUnboundedScrollPosition = _dereq_(154); /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while (inst._nativeParent) { inst = inst._nativeParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); var container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { bookKeeping.ancestors.push(ancestor); ancestor = ancestor && findParent(ancestor); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"125":125,"142":142,"143":143,"154":154,"168":168,"25":25,"41":41,"93":93}],67:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactFeatureFlags */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; },{}],68:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactInjection */ 'use strict'; var DOMProperty = _dereq_(10); var EventPluginHub = _dereq_(17); var EventPluginUtils = _dereq_(19); var ReactComponentEnvironment = _dereq_(33); var ReactClass = _dereq_(30); var ReactEmptyComponent = _dereq_(63); var ReactBrowserEventEmitter = _dereq_(27); var ReactNativeComponent = _dereq_(77); var ReactUpdates = _dereq_(93); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"10":10,"17":17,"19":19,"27":27,"30":30,"33":33,"63":63,"77":77,"93":93}],69:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactInputSelection */ 'use strict'; var ReactDOMSelection = _dereq_(52); var containsNode = _dereq_(146); var focusNode = _dereq_(151); var getActiveElement = _dereq_(152); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"146":146,"151":151,"152":152,"52":52}],70:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; },{}],71:[function(_dereq_,module,exports){ /** * Copyright 2016-present, 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 ReactInstrumentation */ 'use strict'; var ReactDebugTool = _dereq_(58); module.exports = { debugTool: ReactDebugTool }; },{"58":58}],72:[function(_dereq_,module,exports){ /** * Copyright 2016-present, 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 ReactInvalidSetStateWarningDevTool */ 'use strict'; var warning = _dereq_(167); if ("development" !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { "development" !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; } var ReactInvalidSetStateWarningDevTool = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningDevTool; },{"167":167}],73:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactMarkupChecksum */ 'use strict'; var adler32 = _dereq_(114); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"114":114}],74:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactMount */ 'use strict'; var DOMLazyTree = _dereq_(8); var DOMProperty = _dereq_(10); var ReactBrowserEventEmitter = _dereq_(27); var ReactCurrentOwner = _dereq_(36); var ReactDOMComponentTree = _dereq_(41); var ReactDOMContainerInfo = _dereq_(42); var ReactDOMFeatureFlags = _dereq_(46); var ReactElement = _dereq_(61); var ReactFeatureFlags = _dereq_(67); var ReactInstrumentation = _dereq_(71); var ReactMarkupChecksum = _dereq_(73); var ReactReconciler = _dereq_(86); var ReactUpdateQueue = _dereq_(92); var ReactUpdates = _dereq_(93); var emptyObject = _dereq_(150); var instantiateReactComponent = _dereq_(131); var invariant = _dereq_(157); var setInnerHTML = _dereq_(137); var shouldUpdateReactComponent = _dereq_(139); var warning = _dereq_(167); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var instancesByReactRootID = {}; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var wrappedElement = wrapperInstance._currentElement.props; var type = wrappedElement.type; markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name); console.time(markerName); } var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context); if (markerName) { console.timeEnd(markerName); } wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance; ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container, safely) { ReactReconciler.unmountComponent(instance, safely); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._nativeParent); } } function getNativeRootInstanceInContainer(container) { var rootEl = getReactRootElementInContainer(container); var prevNativeInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl); return prevNativeInstance && !prevNativeInstance._nativeParent ? prevNativeInstance : null; } function getTopLevelWrapperInContainer(container) { var root = getNativeRootInstanceInContainer(container); return root ? root._nativeContainerInfo._topLevelWrapper : null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var topLevelRootCounter = 1; var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; if ("development" !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { // this.props is actually a ReactElement return this.props; }; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** * Used by devtools. The keys are not important. */ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); return prevComponent; }, /** * Render a new component into the DOM. Hooked by devtools! * * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginFlush(); } // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement); if ("development" !== 'production') { // Mute future events from the top level wrapper. // It is an implementation detail that devtools should not know about. componentInstance._debugID = 0; } // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; if ("development" !== 'production') { // The instance here is TopLevelWrapper so we report mount for its child. ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._renderedComponent._debugID); ReactInstrumentation.debugTool.onEndFlush(); } return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && parentComponent._reactInternalInstance != null) ? "development" !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : void 0; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render'); !ReactElement.isValidElement(nextElement) ? "development" !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : void 0; "development" !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0; var nextWrappedElement = ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); var prevComponent = getTopLevelWrapperInContainer(container); if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if ("development" !== 'production') { "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { "development" !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : void 0; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Unmounts and destroys the React component rendered in the `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) "development" !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : void 0; var prevComponent = getTopLevelWrapperInContainer(container); if (!prevComponent) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME); if ("development" !== 'production') { "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0; } return false; } delete instancesByReactRootID[prevComponent._instance.rootID]; ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false); return true; }, _mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : void 0; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { ReactDOMComponentTree.precacheNode(instance, rootElement); return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if ("development" !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0; } } } !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : void 0; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } DOMLazyTree.insertTreeBefore(container, markup, null); } else { setInnerHTML(container, markup); ReactDOMComponentTree.precacheNode(instance, container.firstChild); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(container.firstChild)._debugID, 'mount', markup.toString()); } } }; module.exports = ReactMount; },{"10":10,"131":131,"137":137,"139":139,"150":150,"157":157,"167":167,"27":27,"36":36,"41":41,"42":42,"46":46,"61":61,"67":67,"71":71,"73":73,"8":8,"86":86,"92":92,"93":93}],75:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactMultiChild */ 'use strict'; var ReactComponentEnvironment = _dereq_(33); var ReactInstrumentation = _dereq_(71); var ReactMultiChildUpdateTypes = _dereq_(76); var ReactCurrentOwner = _dereq_(36); var ReactReconciler = _dereq_(86); var ReactChildReconciler = _dereq_(28); var emptyFunction = _dereq_(149); var flattenChildren = _dereq_(120); var invariant = _dereq_(157); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.INSERT_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getNativeNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.REMOVE_NODE, content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.SET_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.TEXT_CONTENT, content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction; if ("development" !== 'production') { setChildrenForInstrumentation = function (children) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, children ? Object.keys(children).map(function (key) { return children[key]._debugID; }) : []); }; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if ("development" !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, removedNodes, transaction, context) { var nextChildren; if ("development" !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements); ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context); child._mountIndex = index++; mountImages.push(mountImage); } } if ("development" !== 'production') { setChildrenForInstrumentation.call(this, children); } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : invariant(false) : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : invariant(false) : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, lastPlacedNode, nextIndex, transaction, context)); } nextIndex++; lastPlacedNode = ReactReconciler.getNativeNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; if ("development" !== 'production') { setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, afterNode, index, transaction, context) { var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context); child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } } }; module.exports = ReactMultiChild; },{"120":120,"149":149,"157":157,"28":28,"33":33,"36":36,"71":71,"76":76,"86":86}],76:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = _dereq_(160); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"160":160}],77:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactNativeComponent */ 'use strict'; var _assign = _dereq_(168); var invariant = _dereq_(157); var autoGenerateWrapperClass = null; var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags. var tagToComponentClass = {}; var textComponentClass = null; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function (componentClasses) { _assign(tagToComponentClass, componentClasses); } }; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if (typeof element.type === 'function') { return element.type; } var tag = element.type; var componentClass = tagToComponentClass[tag]; if (componentClass == null) { tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); } return componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; },{"157":157,"168":168}],78:[function(_dereq_,module,exports){ /** * Copyright 2016-present, 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 ReactNativeOperationHistoryDevtool */ 'use strict'; var history = []; var ReactNativeOperationHistoryDevtool = { onNativeOperation: function (debugID, type, payload) { history.push({ instanceID: debugID, type: type, payload: payload }); }, clearHistory: function () { history = []; }, getHistory: function () { return history; } }; module.exports = ReactNativeOperationHistoryDevtool; },{}],79:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactNodeTypes */ 'use strict'; var ReactElement = _dereq_(61); var invariant = _dereq_(157); var ReactNodeTypes = { NATIVE: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (ReactElement.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.NATIVE; } } !false ? "development" !== 'production' ? invariant(false, 'Unexpected node: %s', node) : invariant(false) : void 0; } }; module.exports = ReactNodeTypes; },{"157":157,"61":61}],80:[function(_dereq_,module,exports){ /** * Copyright 2015-present, 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 ReactNoopUpdateQueue */ 'use strict'; var warning = _dereq_(167); function warnTDZ(publicInstance, callerName) { if ("development" !== 'production') { "development" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnTDZ(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnTDZ(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnTDZ(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; },{"167":167}],81:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactOwner */ 'use strict'; var invariant = _dereq_(157); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function (object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : void 0; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; },{"157":157}],82:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if ("development" !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],83:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactPropTypeLocations */ 'use strict'; var keyMirror = _dereq_(160); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"160":160}],84:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactPropTypes */ 'use strict'; var ReactElement = _dereq_(61); var ReactPropTypeLocationNames = _dereq_(82); var emptyFunction = _dereq_(149); var getIteratorFn = _dereq_(126); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']'); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOf, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOfType, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } module.exports = ReactPropTypes; },{"126":126,"149":149,"61":61,"82":82}],85:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactReconcileTransaction */ 'use strict'; var _assign = _dereq_(168); var CallbackQueue = _dereq_(5); var PooledClass = _dereq_(25); var ReactBrowserEventEmitter = _dereq_(27); var ReactInputSelection = _dereq_(69); var Transaction = _dereq_(111); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"111":111,"168":168,"25":25,"27":27,"5":5,"69":69}],86:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactReconciler */ 'use strict'; var ReactRef = _dereq_(87); var ReactInstrumentation = _dereq_(71); var invariant = _dereq_(157); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing native component instance * @param {?object} info about the native container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, nativeParent, nativeContainerInfo, context) { if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'mountComponent'); } } var markup = internalInstance.mountComponent(transaction, nativeParent, nativeContainerInfo, context); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'mountComponent'); ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getNativeNode: function (internalInstance) { return internalInstance.getNativeNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'unmountComponent'); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'unmountComponent'); ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'receiveComponent'); } } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'receiveComponent'); ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. !(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1) ? "development" !== 'production' ? invariant(false, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : invariant(false) : void 0; return; } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'performUpdateIfNecessary'); } } internalInstance.performUpdateIfNecessary(transaction); if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'performUpdateIfNecessary'); ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; },{"157":157,"71":71,"87":87}],87:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactRef */ 'use strict'; var ReactOwner = _dereq_(81); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; return( // This has a few false positives w/r/t empty components. prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref ); }; ReactRef.detachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; },{"81":81}],88:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactServerBatchingStrategy */ 'use strict'; var ReactServerBatchingStrategy = { isBatchingUpdates: false, batchedUpdates: function (callback) { // Don't do anything here. During the server rendering we don't want to // schedule any updates. We will simply ignore them. } }; module.exports = ReactServerBatchingStrategy; },{}],89:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactServerRendering */ 'use strict'; var ReactDOMContainerInfo = _dereq_(42); var ReactDefaultBatchingStrategy = _dereq_(59); var ReactElement = _dereq_(61); var ReactInstrumentation = _dereq_(71); var ReactMarkupChecksum = _dereq_(73); var ReactReconciler = _dereq_(86); var ReactServerBatchingStrategy = _dereq_(88); var ReactServerRenderingTransaction = _dereq_(90); var ReactUpdates = _dereq_(93); var emptyObject = _dereq_(150); var instantiateReactComponent = _dereq_(131); var invariant = _dereq_(157); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToStringImpl(element, makeStaticMarkup) { var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element); var markup = ReactReconciler.mountComponent(componentInstance, transaction, null, ReactDOMContainerInfo(), emptyObject); if ("development" !== 'production') { ReactInstrumentation.debugTool.onUnmountComponent(componentInstance._debugID); } if (!makeStaticMarkup) { markup = ReactMarkupChecksum.addChecksumToMarkup(markup); } return markup; }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring */ function renderToString(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : void 0; return renderToStringImpl(element, false); } /** * Similar to renderToString, except this doesn't create extra DOM attributes * such as data-react-id that React uses internally. * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup */ function renderToStaticMarkup(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : void 0; return renderToStringImpl(element, true); } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; },{"131":131,"150":150,"157":157,"42":42,"59":59,"61":61,"71":71,"73":73,"86":86,"88":88,"90":90,"93":93}],90:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 ReactServerRenderingTransaction */ 'use strict'; var _assign = _dereq_(168); var PooledClass = _dereq_(25); var Transaction = _dereq_(111); /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = []; var noopCallbackQueue = { enqueue: function () {} }; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.useCreateElement = false; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return noopCallbackQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () {}, checkpoint: function () {}, rollback: function () {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"111":111,"168":168,"25":25}],91:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactUMDEntry */ 'use strict'; var _assign = _dereq_(168); var ReactDOM = _dereq_(37); var ReactDOMServer = _dereq_(53); var React = _dereq_(26); // `version` will be added here by ReactIsomorphic. var ReactUMDEntry = _assign({ __SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOM, __SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOMServer }, React); module.exports = ReactUMDEntry; },{"168":168,"26":26,"37":37,"53":53}],92:[function(_dereq_,module,exports){ /** * Copyright 2015-present, 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 ReactUpdateQueue */ 'use strict'; var ReactCurrentOwner = _dereq_(36); var ReactInstanceMap = _dereq_(70); var ReactUpdates = _dereq_(93); var invariant = _dereq_(157); var warning = _dereq_(167); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if ("development" !== 'production') { // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. "development" !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : void 0; } return null; } if ("development" !== 'production') { "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function (publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, newElement) { internalInstance._pendingElement = newElement; enqueueUpdate(internalInstance); }, validateCallback: function (callback, callerName) { !(!callback || typeof callback === 'function') ? "development" !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : invariant(false) : void 0; } }; module.exports = ReactUpdateQueue; },{"157":157,"167":167,"36":36,"70":70,"93":93}],93:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactUpdates */ 'use strict'; var _assign = _dereq_(168); var CallbackQueue = _dereq_(5); var PooledClass = _dereq_(25); var ReactFeatureFlags = _dereq_(67); var ReactInstrumentation = _dereq_(71); var ReactReconciler = _dereq_(86); var Transaction = _dereq_(111); var invariant = _dereq_(157); var dirtyComponents = []; var updateBatchNumber = 0; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.props === component._renderedComponent._currentElement) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginFlush(); } // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } if ("development" !== 'production') { ReactInstrumentation.debugTool.onEndFlush(); } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? "development" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : void 0; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; },{"111":111,"157":157,"168":168,"25":25,"5":5,"67":67,"71":71,"86":86}],94:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ReactVersion */ 'use strict'; module.exports = '15.1.0-alpha.1'; },{}],95:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SVGDOMPropertyConfig */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); module.exports = SVGDOMPropertyConfig; },{}],96:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SelectEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(143); var ReactDOMComponentTree = _dereq_(41); var ReactInputSelection = _dereq_(69); var SyntheticEvent = _dereq_(102); var getActiveElement = _dereq_(152); var isTextInputElement = _dereq_(133); var keyOf = _dereq_(161); var shallowEqual = _dereq_(166); var topLevelTypes = EventConstants.topLevelTypes; var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. See #3639. var hasListener = false; var ON_SELECT_KEY = keyOf({ onSelect: null }); /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) { break; } // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (inst, registrationName, listener) { if (registrationName === ON_SELECT_KEY) { hasListener = true; } } }; module.exports = SelectEventPlugin; },{"102":102,"133":133,"143":143,"152":152,"16":16,"161":161,"166":166,"20":20,"41":41,"69":69}],97:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SimpleEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventListener = _dereq_(142); var EventPropagators = _dereq_(20); var ReactDOMComponentTree = _dereq_(41); var SyntheticAnimationEvent = _dereq_(98); var SyntheticClipboardEvent = _dereq_(99); var SyntheticEvent = _dereq_(102); var SyntheticFocusEvent = _dereq_(103); var SyntheticKeyboardEvent = _dereq_(105); var SyntheticMouseEvent = _dereq_(106); var SyntheticDragEvent = _dereq_(101); var SyntheticTouchEvent = _dereq_(107); var SyntheticTransitionEvent = _dereq_(108); var SyntheticUIEvent = _dereq_(109); var SyntheticWheelEvent = _dereq_(110); var emptyFunction = _dereq_(149); var getEventCharCode = _dereq_(122); var invariant = _dereq_(157); var keyOf = _dereq_(161); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: true }), captured: keyOf({ onAbortCapture: true }) } }, animationEnd: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationEnd: true }), captured: keyOf({ onAnimationEndCapture: true }) } }, animationIteration: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationIteration: true }), captured: keyOf({ onAnimationIterationCapture: true }) } }, animationStart: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationStart: true }), captured: keyOf({ onAnimationStartCapture: true }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: true }), captured: keyOf({ onBlurCapture: true }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: true }), captured: keyOf({ onCanPlayCapture: true }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: true }), captured: keyOf({ onCanPlayThroughCapture: true }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: true }), captured: keyOf({ onClickCapture: true }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: true }), captured: keyOf({ onContextMenuCapture: true }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: true }), captured: keyOf({ onCopyCapture: true }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: true }), captured: keyOf({ onCutCapture: true }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: true }), captured: keyOf({ onDoubleClickCapture: true }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: true }), captured: keyOf({ onDragCapture: true }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: true }), captured: keyOf({ onDragEndCapture: true }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: true }), captured: keyOf({ onDragEnterCapture: true }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: true }), captured: keyOf({ onDragExitCapture: true }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: true }), captured: keyOf({ onDragLeaveCapture: true }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: true }), captured: keyOf({ onDragOverCapture: true }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: true }), captured: keyOf({ onDragStartCapture: true }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: true }), captured: keyOf({ onDropCapture: true }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: true }), captured: keyOf({ onDurationChangeCapture: true }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: true }), captured: keyOf({ onEmptiedCapture: true }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: true }), captured: keyOf({ onEncryptedCapture: true }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: true }), captured: keyOf({ onEndedCapture: true }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: true }), captured: keyOf({ onErrorCapture: true }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: true }), captured: keyOf({ onFocusCapture: true }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: true }), captured: keyOf({ onInputCapture: true }) } }, invalid: { phasedRegistrationNames: { bubbled: keyOf({ onInvalid: true }), captured: keyOf({ onInvalidCapture: true }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: true }), captured: keyOf({ onKeyDownCapture: true }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: true }), captured: keyOf({ onKeyPressCapture: true }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: true }), captured: keyOf({ onKeyUpCapture: true }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: true }), captured: keyOf({ onLoadCapture: true }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: true }), captured: keyOf({ onLoadedDataCapture: true }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: true }), captured: keyOf({ onLoadedMetadataCapture: true }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: true }), captured: keyOf({ onLoadStartCapture: true }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: true }), captured: keyOf({ onMouseDownCapture: true }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: true }), captured: keyOf({ onMouseMoveCapture: true }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: true }), captured: keyOf({ onMouseOutCapture: true }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: true }), captured: keyOf({ onMouseOverCapture: true }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: true }), captured: keyOf({ onMouseUpCapture: true }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: true }), captured: keyOf({ onPasteCapture: true }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: true }), captured: keyOf({ onPauseCapture: true }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: true }), captured: keyOf({ onPlayCapture: true }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: true }), captured: keyOf({ onPlayingCapture: true }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: true }), captured: keyOf({ onProgressCapture: true }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: true }), captured: keyOf({ onRateChangeCapture: true }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: true }), captured: keyOf({ onResetCapture: true }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: true }), captured: keyOf({ onScrollCapture: true }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: true }), captured: keyOf({ onSeekedCapture: true }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: true }), captured: keyOf({ onSeekingCapture: true }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: true }), captured: keyOf({ onStalledCapture: true }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: true }), captured: keyOf({ onSubmitCapture: true }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: true }), captured: keyOf({ onSuspendCapture: true }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: true }), captured: keyOf({ onTimeUpdateCapture: true }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: true }), captured: keyOf({ onTouchCancelCapture: true }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: true }), captured: keyOf({ onTouchEndCapture: true }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: true }), captured: keyOf({ onTouchMoveCapture: true }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: true }), captured: keyOf({ onTouchStartCapture: true }) } }, transitionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTransitionEnd: true }), captured: keyOf({ onTransitionEndCapture: true }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: true }), captured: keyOf({ onVolumeChangeCapture: true }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: true }), captured: keyOf({ onWaitingCapture: true }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: true }), captured: keyOf({ onWheelCapture: true }) } } }; var topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topAnimationEnd: eventTypes.animationEnd, topAnimationIteration: eventTypes.animationIteration, topAnimationStart: eventTypes.animationStart, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topInvalid: eventTypes.invalid, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topTransitionEnd: eventTypes.transitionEnd, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var ON_CLICK_KEY = keyOf({ onClick: null }); var onClickListeners = {}; var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topInvalid: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topAnimationEnd: case topLevelTypes.topAnimationIteration: case topLevelTypes.topAnimationStart: EventConstructor = SyntheticAnimationEvent; break; case topLevelTypes.topTransitionEnd: EventConstructor = SyntheticTransitionEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? "development" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var id = inst._rootNodeID; var node = ReactDOMComponentTree.getNodeFromInstance(inst); if (!onClickListeners[id]) { onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (inst, registrationName) { if (registrationName === ON_CLICK_KEY) { var id = inst._rootNodeID; onClickListeners[id].remove(); delete onClickListeners[id]; } } }; module.exports = SimpleEventPlugin; },{"101":101,"102":102,"103":103,"105":105,"106":106,"107":107,"108":108,"109":109,"110":110,"122":122,"142":142,"149":149,"157":157,"16":16,"161":161,"20":20,"41":41,"98":98,"99":99}],98:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticAnimationEvent */ 'use strict'; var SyntheticEvent = _dereq_(102); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; },{"102":102}],99:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticClipboardEvent */ 'use strict'; var SyntheticEvent = _dereq_(102); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"102":102}],100:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticCompositionEvent */ 'use strict'; var SyntheticEvent = _dereq_(102); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; },{"102":102}],101:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticDragEvent */ 'use strict'; var SyntheticMouseEvent = _dereq_(106); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"106":106}],102:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticEvent */ 'use strict'; var _assign = _dereq_(168); var PooledClass = _dereq_(25); var emptyFunction = _dereq_(149); var warning = _dereq_(167); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if ("development" !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if ("development" !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if ("development" !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if ("development" !== 'production') { var noop = _dereq_(149); Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', noop)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', noop)); } } }); SyntheticEvent.Interface = EventInterface; if ("development" !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { "development" !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; "development" !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } },{"149":149,"167":167,"168":168,"25":25}],103:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticFocusEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(109); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"109":109}],104:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticInputEvent */ 'use strict'; var SyntheticEvent = _dereq_(102); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; },{"102":102}],105:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticKeyboardEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(109); var getEventCharCode = _dereq_(122); var getEventKey = _dereq_(123); var getEventModifierState = _dereq_(124); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"109":109,"122":122,"123":123,"124":124}],106:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticMouseEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(109); var ViewportMetrics = _dereq_(112); var getEventModifierState = _dereq_(124); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"109":109,"112":112,"124":124}],107:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticTouchEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(109); var getEventModifierState = _dereq_(124); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"109":109,"124":124}],108:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticTransitionEvent */ 'use strict'; var SyntheticEvent = _dereq_(102); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; },{"102":102}],109:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticUIEvent */ 'use strict'; var SyntheticEvent = _dereq_(102); var getEventTarget = _dereq_(125); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"102":102,"125":125}],110:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 SyntheticWheelEvent */ 'use strict'; var SyntheticMouseEvent = _dereq_(106); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"106":106}],111:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 Transaction */ 'use strict'; var invariant = _dereq_(157); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; },{"157":157}],112:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{}],113:[function(_dereq_,module,exports){ /** * Copyright 2014-present, 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 accumulateInto */ 'use strict'; var invariant = _dereq_(157); /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; },{"157":157}],114:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 adler32 */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; },{}],115:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 canDefineProperty */ 'use strict'; var canDefineProperty = false; if ("development" !== 'production') { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; },{}],116:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 createMicrosoftUnsafeLocalFunction */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; },{}],117:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 dangerousStyleValue */ 'use strict'; var CSSProperty = _dereq_(3); var warning = _dereq_(167); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { if ("development" !== 'production') { if (component) { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { "development" !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0; } } } value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; },{"167":167,"3":3}],118:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 escapeTextContentForBrowser */ 'use strict'; var ESCAPE_LOOKUP = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '\'': '&#x27;' }; var ESCAPE_REGEX = /[&><"']/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextContentForBrowser; },{}],119:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 findDOMNode */ 'use strict'; var ReactCurrentOwner = _dereq_(36); var ReactDOMComponentTree = _dereq_(41); var ReactInstanceMap = _dereq_(70); var getNativeComponentFromComposite = _dereq_(127); var invariant = _dereq_(157); var warning = _dereq_(167); /** * Returns the DOM node rendered by this element. * * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getNativeComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { !false ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : void 0; } else { !false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : void 0; } } module.exports = findDOMNode; },{"127":127,"157":157,"167":167,"36":36,"41":41,"70":70}],120:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 flattenChildren */ 'use strict'; var KeyEscapeUtils = _dereq_(23); var traverseAllChildren = _dereq_(140); var warning = _dereq_(167); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = result[name] === undefined; if ("development" !== 'production') { "development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', KeyEscapeUtils.unescape(name)) : void 0; } if (keyUnique && child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; },{"140":140,"167":167,"23":23}],121:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 forEachAccumulated */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function (arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],122:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getEventCharCode */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],123:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getEventKey */ 'use strict'; var getEventCharCode = _dereq_(122); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; },{"122":122}],124:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getEventModifierState */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; },{}],125:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getEventTarget */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],126:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getIteratorFn */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; },{}],127:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getNativeComponentFromComposite */ 'use strict'; var ReactNodeTypes = _dereq_(79); function getNativeComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.NATIVE) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getNativeComponentFromComposite; },{"79":79}],128:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],129:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = _dereq_(143); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"143":143}],130:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 getVendorPrefixedEventName */ 'use strict'; var ExecutionEnvironment = _dereq_(143); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; },{"143":143}],131:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 instantiateReactComponent */ 'use strict'; var _assign = _dereq_(168); var ReactCompositeComponent = _dereq_(35); var ReactEmptyComponent = _dereq_(63); var ReactNativeComponent = _dereq_(77); var ReactInstrumentation = _dereq_(71); var invariant = _dereq_(157); var warning = _dereq_(167); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function getDisplayName(instance) { var element = instance._currentElement; if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else if (instance.getName) { return instance.getName() || 'Unknown'; } else { return element.type.displayName || element.type.name || 'Unknown'; } } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } var nextDebugID = 1; /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node) { var instance; var isEmpty = node === null || node === false; if (isEmpty) { instance = ReactEmptyComponent.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : void 0; // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { !false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getNativeNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if ("development" !== 'production') { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } if ("development" !== 'production') { var debugID = isEmpty ? 0 : nextDebugID++; instance._debugID = debugID; var displayName = getDisplayName(instance); ReactInstrumentation.debugTool.onSetDisplayName(debugID, displayName); var owner = node && node._owner; if (owner) { ReactInstrumentation.debugTool.onSetOwner(debugID, owner._debugID); } } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if ("development" !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; },{"157":157,"167":167,"168":168,"35":35,"63":63,"71":71,"77":77}],132:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 isEventSupported */ 'use strict'; var ExecutionEnvironment = _dereq_(143); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"143":143}],133:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 isTextInputElement */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); } module.exports = isTextInputElement; },{}],134:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 onlyChild */ 'use strict'; var ReactElement = _dereq_(61); var invariant = _dereq_(157); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : void 0; return children; } module.exports = onlyChild; },{"157":157,"61":61}],135:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = _dereq_(118); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; },{"118":118}],136:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 renderSubtreeIntoContainer */ 'use strict'; var ReactMount = _dereq_(74); module.exports = ReactMount.renderSubtreeIntoContainer; },{"74":74}],137:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 setInnerHTML */ 'use strict'; var ExecutionEnvironment = _dereq_(143); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = _dereq_(116); /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { node.innerHTML = html; }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; },{"116":116,"143":143}],138:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 setTextContent */ 'use strict'; var ExecutionEnvironment = _dereq_(143); var escapeTextContentForBrowser = _dereq_(118); var setInnerHTML = _dereq_(137); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; },{"118":118,"137":137,"143":143}],139:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 shouldUpdateReactComponent */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; },{}],140:[function(_dereq_,module,exports){ /** * Copyright 2013-present, 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 traverseAllChildren */ 'use strict'; var ReactCurrentOwner = _dereq_(36); var ReactElement = _dereq_(61); var getIteratorFn = _dereq_(126); var invariant = _dereq_(157); var KeyEscapeUtils = _dereq_(23); var warning = _dereq_(167); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if ("development" !== 'production') { "development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if ("development" !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); !false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; },{"126":126,"157":157,"167":167,"23":23,"36":36,"61":61}],141:[function(_dereq_,module,exports){ /** * Copyright 2015-present, 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 validateDOMNesting */ 'use strict'; var _assign = _dereq_(168); var emptyFunction = _dereq_(149); var warning = _dereq_(167); var validateDOMNesting = emptyFunction; if ("development" !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; if (childTag !== '#text') { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' + 'See %s.%s', tagDisplayName, ancestorTag, ownerInfo, info) : void 0; } else { "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0; } } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; },{"149":149,"167":167,"168":168}],142:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * * 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. * * @typechecks */ var emptyFunction = _dereq_(149); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function () { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function () { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function () { target.removeEventListener(eventType, callback, true); } }; } else { if ("development" !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function () {} }; module.exports = EventListener; },{"149":149}],143:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],144:[function(_dereq_,module,exports){ "use strict"; /** * Copyright (c) 2013-present, 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. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],145:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * * @typechecks */ 'use strict'; var camelize = _dereq_(144); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; },{"144":144}],146:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ var isTextNode = _dereq_(159); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"159":159}],147:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ var invariant = _dereq_(157); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? "development" !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; },{"157":157}],148:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = _dereq_(143); var createArrayFromMixed = _dereq_(147); var getMarkupWrap = _dereq_(153); var invariant = _dereq_(157); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; },{"143":143,"147":147,"153":153,"157":157}],149:[function(_dereq_,module,exports){ "use strict"; /** * Copyright (c) 2013-present, 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. * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; },{}],150:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * */ 'use strict'; var emptyObject = {}; if ("development" !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],151:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; },{}],152:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],153:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = _dereq_(143); var invariant = _dereq_(157); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; },{"143":143,"157":157}],154:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],155:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],156:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * * @typechecks */ 'use strict'; var hyphenate = _dereq_(155); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; },{"155":155}],157:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * */ '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 ("development" !== 'production') { 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; },{}],158:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; },{}],159:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ var isNode = _dereq_(158); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; },{"158":158}],160:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * * @typechecks static-only */ 'use strict'; var invariant = _dereq_(157); /** * 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)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : void 0; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{"157":157}],161:[function(_dereq_,module,exports){ "use strict"; /** * Copyright (c) 2013-present, 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. * */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],162:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; },{}],163:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; },{}],164:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * * @typechecks */ 'use strict'; var ExecutionEnvironment = _dereq_(143); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"143":143}],165:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ var performance = _dereq_(164); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function () { return performance.now(); }; } else { performanceNow = function () { return Date.now(); }; } module.exports = performanceNow; },{"164":164}],166:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, 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. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * 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 (is(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. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; },{}],167:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * */ 'use strict'; var emptyFunction = _dereq_(149); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("development" !== 'production') { warning = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} } }; } module.exports = warning; },{"149":149}],168:[function(_dereq_,module,exports){ 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}]},{},[91])(91) });
/** * React (with addons) v0.14.0 * * 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. * */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.React=e()}}(function(){return function e(t,n,r){function o(i,u){if(!n[i]){if(!t[i]){var s="function"==typeof require&&require;if(!u&&s)return s(i,!0);if(a)return a(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[i]={exports:{}};t[i][0].call(c.exports,function(e){var n=t[i][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[i].exports}for(var a="function"==typeof require&&require,i=0;i<r.length;i++)o(r[i]);return o}({1:[function(e,t,n){"use strict";var r=e(22),o=e(26),a=e(37),i=e(29),u=e(62),s=e(91),l=e(93),c=e(114),p=e(136),d=e(139);e(167);o.addons={CSSTransitionGroup:i,LinkedStateMixin:r,PureRenderMixin:a,TransitionGroup:s,batchedUpdates:function(){return l.batchedUpdates.apply(this,arguments)},cloneWithProps:c,createFragment:u.create,shallowCompare:p,update:d},t.exports=o},{114:114,136:136,139:139,167:167,22:22,26:26,29:29,37:37,62:62,91:91,93:93}],2:[function(e,t,n){"use strict";var r=e(70),o=e(118),a=e(151),i={componentDidMount:function(){this.props.autoFocus&&a(o(this))}},u={Mixin:i,focusDOMComponent:function(){a(r.getNode(this._rootNodeID))}};t.exports=u},{118:118,151:151,70:70}],3:[function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function a(e){switch(e){case N.topCompositionStart:return w.compositionStart;case N.topCompositionEnd:return w.compositionEnd;case N.topCompositionUpdate:return w.compositionUpdate}}function i(e,t){return e===N.topKeyDown&&t.keyCode===E}function u(e,t){switch(e){case N.topKeyUp:return-1!==b.indexOf(t.keyCode);case N.topKeyDown:return t.keyCode!==E;case N.topKeyPress:case N.topMouseDown:case N.topBlur:return!0;default:return!1}}function s(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function l(e,t,n,r,o){var l,c;if(_?l=a(e):R?u(e,r)&&(l=w.compositionEnd):i(e,r)&&(l=w.compositionStart),!l)return null;P&&(R||l!==w.compositionStart?l===w.compositionEnd&&R&&(c=R.getData()):R=m.getPooled(t));var p=g.getPooled(l,n,r,o);if(c)p.data=c;else{var d=s(r);null!==d&&(p.data=d)}return h.accumulateTwoPhaseDispatches(p),p}function c(e,t){switch(e){case N.topCompositionEnd:return s(t);case N.topKeyPress:var n=t.which;return n!==T?null:(S=!0,M);case N.topTextInput:var r=t.data;return r===M&&S?null:r;default:return null}}function p(e,t){if(R){if(e===N.topCompositionEnd||u(e,t)){var n=R.getData();return m.release(R),R=null,n}return null}switch(e){case N.topPaste:return null;case N.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case N.topCompositionEnd:return P?null:t.data;default:return null}}function d(e,t,n,r,o){var a;if(a=D?c(e,r):p(e,r),!a)return null;var i=y.getPooled(w.beforeInput,n,r,o);return i.data=a,h.accumulateTwoPhaseDispatches(i),i}var f=e(15),h=e(19),v=e(143),m=e(20),g=e(100),y=e(104),C=e(162),b=[9,13,27,32],E=229,_=v.canUseDOM&&"CompositionEvent"in window,x=null;v.canUseDOM&&"documentMode"in document&&(x=document.documentMode);var D=v.canUseDOM&&"TextEvent"in window&&!x&&!r(),P=v.canUseDOM&&(!_||x&&x>8&&11>=x),T=32,M=String.fromCharCode(T),N=f.topLevelTypes,w={beforeInput:{phasedRegistrationNames:{bubbled:C({onBeforeInput:null}),captured:C({onBeforeInputCapture:null})},dependencies:[N.topCompositionEnd,N.topKeyPress,N.topTextInput,N.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:C({onCompositionEnd:null}),captured:C({onCompositionEndCapture:null})},dependencies:[N.topBlur,N.topCompositionEnd,N.topKeyDown,N.topKeyPress,N.topKeyUp,N.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:C({onCompositionStart:null}),captured:C({onCompositionStartCapture:null})},dependencies:[N.topBlur,N.topCompositionStart,N.topKeyDown,N.topKeyPress,N.topKeyUp,N.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:C({onCompositionUpdate:null}),captured:C({onCompositionUpdateCapture:null})},dependencies:[N.topBlur,N.topCompositionUpdate,N.topKeyDown,N.topKeyPress,N.topKeyUp,N.topMouseDown]}},S=!1,R=null,I={eventTypes:w,extractEvents:function(e,t,n,r,o){return[l(e,t,n,r,o),d(e,t,n,r,o)]}};t.exports=I},{100:100,104:104,143:143,15:15,162:162,19:19,20:20}],4:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={animationIterationCount:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,stopOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},a=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){a.forEach(function(t){o[r(t,e)]=o[e]})});var i={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},u={isUnitlessNumber:o,shorthandPropertyExpansions:i};t.exports=u},{}],5:[function(e,t,n){"use strict";var r=e(4),o=e(143),a=e(76),i=(e(145),e(115)),u=e(156),s=e(164),l=(e(167),s(function(e){return u(e)})),c=!1,p="cssFloat";if(o.canUseDOM){var d=document.createElement("div").style;try{d.font=""}catch(f){c=!0}void 0===document.documentElement.style.cssFloat&&(p="styleFloat")}var h={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=l(n)+":",t+=i(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var o in t)if(t.hasOwnProperty(o)){var a=i(o,t[o]);if("float"===o&&(o=p),a)n[o]=a;else{var u=c&&r.shorthandPropertyExpansions[o];if(u)for(var s in u)n[s]="";else n[o]=""}}}};a.measureMethods(h,"CSSPropertyOperations",{setValueForStyles:"setValueForStyles"}),t.exports=h},{115:115,143:143,145:145,156:156,164:164,167:167,4:4,76:76}],6:[function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=e(25),a=e(24),i=e(157);a(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){e.length!==t.length?i(!1):void 0,this._callbacks=null,this._contexts=null;for(var n=0;n<e.length;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),t.exports=r},{157:157,24:24,25:25}],7:[function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=x.getPooled(w.change,R,e,D(e));b.accumulateTwoPhaseDispatches(t),_.batchedUpdates(a,t)}function a(e){C.enqueueEvents(e),C.processEventQueue(!1)}function i(e,t){S=e,R=t,S.attachEvent("onchange",o)}function u(){S&&(S.detachEvent("onchange",o),S=null,R=null)}function s(e,t,n){return e===N.topChange?n:void 0}function l(e,t,n){e===N.topFocus?(u(),i(t,n)):e===N.topBlur&&u()}function c(e,t){S=e,R=t,I=e.value,k=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(S,"value",L),S.attachEvent("onpropertychange",d)}function p(){S&&(delete S.value,S.detachEvent("onpropertychange",d),S=null,R=null,I=null,k=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==I&&(I=t,o(e))}}function f(e,t,n){return e===N.topInput?n:void 0}function h(e,t,n){e===N.topFocus?(p(),c(t,n)):e===N.topBlur&&p()}function v(e,t,n){return e!==N.topSelectionChange&&e!==N.topKeyUp&&e!==N.topKeyDown||!S||S.value===I?void 0:(I=S.value,R)}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===N.topClick?n:void 0}var y=e(15),C=e(16),b=e(19),E=e(143),_=e(93),x=e(102),D=e(124),P=e(129),T=e(130),M=e(162),N=y.topLevelTypes,w={change:{phasedRegistrationNames:{bubbled:M({onChange:null}),captured:M({onChangeCapture:null})},dependencies:[N.topBlur,N.topChange,N.topClick,N.topFocus,N.topInput,N.topKeyDown,N.topKeyUp,N.topSelectionChange]}},S=null,R=null,I=null,k=null,O=!1;E.canUseDOM&&(O=P("change")&&(!("documentMode"in document)||document.documentMode>8));var A=!1;E.canUseDOM&&(A=P("input")&&(!("documentMode"in document)||document.documentMode>9));var L={get:function(){return k.get.call(this)},set:function(e){I=""+e,k.set.call(this,e)}},U={eventTypes:w,extractEvents:function(e,t,n,o,a){var i,u;if(r(t)?O?i=s:u=l:T(t)?A?i=f:(i=v,u=h):m(t)&&(i=g),i){var c=i(e,t,n);if(c){var p=x.getPooled(w.change,c,o,a);return p.type="change",b.accumulateTwoPhaseDispatches(p),p}}u&&u(e,t,n)}};t.exports=U},{102:102,124:124,129:129,130:130,143:143,15:15,16:16,162:162,19:19,93:93}],8:[function(e,t,n){"use strict";var r=0,o={createReactRootIndex:function(){return r++}};t.exports=o},{}],9:[function(e,t,n){"use strict";function r(e,t,n){var r=n>=e.childNodes.length?null:e.childNodes.item(n);e.insertBefore(t,r)}var o=e(12),a=e(72),i=e(76),u=e(134),s=e(135),l=e(157),c={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:s,processUpdates:function(e,t){for(var n,i=null,c=null,p=0;p<e.length;p++)if(n=e[p],n.type===a.MOVE_EXISTING||n.type===a.REMOVE_NODE){var d=n.fromIndex,f=n.parentNode.childNodes[d],h=n.parentID;f?void 0:l(!1),i=i||{},i[h]=i[h]||[],i[h][d]=f,c=c||[],c.push(f)}var v;if(v=t.length&&"string"==typeof t[0]?o.dangerouslyRenderMarkup(t):t,c)for(var m=0;m<c.length;m++)c[m].parentNode.removeChild(c[m]);for(var g=0;g<e.length;g++)switch(n=e[g],n.type){case a.INSERT_MARKUP:r(n.parentNode,v[n.markupIndex],n.toIndex);break;case a.MOVE_EXISTING:r(n.parentNode,i[n.parentID][n.fromIndex],n.toIndex);break;case a.SET_MARKUP:u(n.parentNode,n.content);break;case a.TEXT_CONTENT:s(n.parentNode,n.content);break;case a.REMOVE_NODE:}}};i.measureMethods(c,"DOMChildrenOperations",{updateTextContent:"updateTextContent"}),t.exports=c},{12:12,134:134,135:135,157:157,72:72,76:76}],10:[function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=e(157),a={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=a,n=e.Properties||{},i=e.DOMAttributeNamespaces||{},s=e.DOMAttributeNames||{},l=e.DOMPropertyNames||{},c=e.DOMMutationMethods||{};e.isCustomAttribute&&u._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var p in n){u.properties.hasOwnProperty(p)?o(!1):void 0;var d=p.toLowerCase(),f=n[p],h={attributeName:d,attributeNamespace:null,propertyName:p,mutationMethod:null,mustUseAttribute:r(f,t.MUST_USE_ATTRIBUTE),mustUseProperty:r(f,t.MUST_USE_PROPERTY),hasSideEffects:r(f,t.HAS_SIDE_EFFECTS),hasBooleanValue:r(f,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(f,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(f,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(f,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(h.mustUseAttribute&&h.mustUseProperty?o(!1):void 0,!h.mustUseProperty&&h.hasSideEffects?o(!1):void 0,h.hasBooleanValue+h.hasNumericValue+h.hasOverloadedBooleanValue<=1?void 0:o(!1),s.hasOwnProperty(p)){var v=s[p];h.attributeName=v}i.hasOwnProperty(p)&&(h.attributeNamespace=i[p]),l.hasOwnProperty(p)&&(h.propertyName=l[p]),c.hasOwnProperty(p)&&(h.mutationMethod=c[p]),u.properties[p]=h}}},i={},u={ID_ATTRIBUTE_NAME:"data-reactid",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<u._isCustomAttributeFunctions.length;t++){var n=u._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=i[e];return r||(i[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:a};t.exports=u},{157:157}],11:[function(e,t,n){"use strict";function r(e){return c.hasOwnProperty(e)?!0:l.hasOwnProperty(e)?!1:s.test(e)?(c[e]=!0,!0):(l[e]=!0,!1)}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&1>t||e.hasOverloadedBooleanValue&&t===!1}var a=e(10),i=e(76),u=e(132),s=(e(167),/^[a-zA-Z_][\w\.\-]*$/),l={},c={},p={createMarkupForID:function(e){return a.ID_ATTRIBUTE_NAME+"="+u(e)},setAttributeForID:function(e,t){e.setAttribute(a.ID_ATTRIBUTE_NAME,t)},createMarkupForProperty:function(e,t){var n=a.properties.hasOwnProperty(e)?a.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&t===!0?r+'=""':r+"="+u(t)}return a.isCustomAttribute(e)?null==t?"":e+"="+u(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+u(t):""},setValueForProperty:function(e,t,n){var r=a.properties.hasOwnProperty(t)?a.properties[t]:null;if(r){var i=r.mutationMethod;if(i)i(e,n);else if(o(r,n))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute){var u=r.attributeName,s=r.attributeNamespace;s?e.setAttributeNS(s,u,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?e.setAttribute(u,""):e.setAttribute(u,""+n)}else{var l=r.propertyName;r.hasSideEffects&&""+e[l]==""+n||(e[l]=n)}}else a.isCustomAttribute(t)&&p.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){r(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){var n=a.properties.hasOwnProperty(t)?a.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseAttribute)e.removeAttribute(n.attributeName);else{var o=n.propertyName,i=a.getDefaultValueForProperty(e.nodeName,o);n.hasSideEffects&&""+e[o]===i||(e[o]=i)}}else a.isCustomAttribute(t)&&e.removeAttribute(t)}};i.measureMethods(p,"DOMPropertyOperations",{setValueForProperty:"setValueForProperty",setValueForAttribute:"setValueForAttribute",deleteValueForProperty:"deleteValueForProperty"}),t.exports=p},{10:10,132:132,167:167,76:76}],12:[function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=e(143),a=e(148),i=e(149),u=e(153),s=e(157),l=/^(<[^ \/>]+)/,c="data-danger-index",p={dangerouslyRenderMarkup:function(e){o.canUseDOM?void 0:s(!1);for(var t,n={},p=0;p<e.length;p++)e[p]?void 0:s(!1),t=r(e[p]),t=u(t)?t:"*",n[t]=n[t]||[],n[t][p]=e[p];var d=[],f=0;for(t in n)if(n.hasOwnProperty(t)){var h,v=n[t];for(h in v)if(v.hasOwnProperty(h)){var m=v[h];v[h]=m.replace(l,"$1 "+c+'="'+h+'" ')}for(var g=a(v.join(""),i),y=0;y<g.length;++y){var C=g[y];C.hasAttribute&&C.hasAttribute(c)&&(h=+C.getAttribute(c),C.removeAttribute(c),d.hasOwnProperty(h)?s(!1):void 0,d[h]=C,f+=1)}}return f!==d.length?s(!1):void 0,d.length!==e.length?s(!1):void 0,d},dangerouslyReplaceNodeWithMarkup:function(e,t){o.canUseDOM?void 0:s(!1),t?void 0:s(!1),"html"===e.tagName.toLowerCase()?s(!1):void 0;var n;n="string"==typeof t?a(t,i)[0]:t,e.parentNode.replaceChild(n,e)}};t.exports=p},{143:143,148:148,149:149,153:153,157:157}],13:[function(e,t,n){"use strict";var r=e(162),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null})];t.exports=o},{162:162}],14:[function(e,t,n){"use strict";var r=e(15),o=e(19),a=e(106),i=e(70),u=e(162),s=r.topLevelTypes,l=i.getFirstReactDOM,c={mouseEnter:{registrationName:u({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:u({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},p=[null,null],d={eventTypes:c,extractEvents:function(e,t,n,r,u){if(e===s.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var d;if(t.window===t)d=t;else{var f=t.ownerDocument;d=f?f.defaultView||f.parentWindow:window}var h,v,m="",g="";if(e===s.topMouseOut?(h=t,m=n,v=l(r.relatedTarget||r.toElement),v?g=i.getID(v):v=d,v=v||d):(h=d,v=t,g=n),h===v)return null;var y=a.getPooled(c.mouseLeave,m,r,u);y.type="mouseleave",y.target=h,y.relatedTarget=v;var C=a.getPooled(c.mouseEnter,g,r,u);return C.type="mouseenter",C.target=v,C.relatedTarget=h,o.accumulateEnterLeaveDispatches(y,C,m,g),p[0]=y,p[1]=C,p}};t.exports=d},{106:106,15:15,162:162,19:19,70:70}],15:[function(e,t,n){"use strict";var r=e(161),o=r({bubbled:null,captured:null}),a=r({topAbort:null,topBlur:null,topCanPlay:null,topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topVolumeChange:null,topWaiting:null,topWheel:null}),i={topLevelTypes:a,PropagationPhases:o};t.exports=i},{161:161}],16:[function(e,t,n){"use strict";var r=e(17),o=e(18),a=e(59),i=e(112),u=e(120),s=e(157),l=(e(167),{}),c=null,p=function(e,t){e&&(o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},d=function(e){return p(e,!0)},f=function(e){return p(e,!1)},h=null,v={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){h=e},getInstanceHandle:function(){return h},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){"function"!=typeof n?s(!1):void 0;var o=l[t]||(l[t]={});o[e]=n;var a=r.registrationNameModules[t];a&&a.didPutListener&&a.didPutListener(e,t,n)},getListener:function(e,t){var n=l[t];return n&&n[e]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=l[t];o&&delete o[e]},deleteAllListeners:function(e){for(var t in l)if(l[t][e]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete l[t][e]}},extractEvents:function(e,t,n,o,a){for(var u,s=r.plugins,l=0;l<s.length;l++){var c=s[l];if(c){var p=c.extractEvents(e,t,n,o,a);p&&(u=i(u,p))}}return u},enqueueEvents:function(e){e&&(c=i(c,e))},processEventQueue:function(e){var t=c;c=null,e?u(t,d):u(t,f),c?s(!1):void 0,a.rethrowCaughtError()},__purge:function(){l={}},__getListenerBank:function(){return l}};t.exports=v},{112:112,120:120,157:157,167:167,17:17,18:18,59:59}],17:[function(e,t,n){"use strict";function r(){if(u)for(var e in s){var t=s[e],n=u.indexOf(e);if(n>-1?void 0:i(!1),!l.plugins[n]){t.extractEvents?void 0:i(!1),l.plugins[n]=t;var r=t.eventTypes;for(var a in r)o(r[a],t,a)?void 0:i(!1)}}}function o(e,t,n){l.eventNameDispatchConfigs.hasOwnProperty(n)?i(!1):void 0,l.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var u=r[o];a(u,t,n)}return!0}return e.registrationName?(a(e.registrationName,t,n),!0):!1}function a(e,t,n){l.registrationNameModules[e]?i(!1):void 0,l.registrationNameModules[e]=t,l.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var i=e(157),u=null,s={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){u?i(!1):void 0,u=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];s.hasOwnProperty(n)&&s[n]===o||(s[n]?i(!1):void 0,s[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return l.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=l.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){u=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];l.plugins.length=0;var t=l.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=l.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=l},{157:157}],18:[function(e,t,n){"use strict";function r(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function o(e){return e===m.topMouseMove||e===m.topTouchMove}function a(e){return e===m.topMouseDown||e===m.topTouchStart}function i(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=v.Mount.getNode(r),t?f.invokeGuardedCallbackWithCatch(o,n,e,r):f.invokeGuardedCallback(o,n,e,r),e.currentTarget=null}function u(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)i(e,t,n[o],r[o]);else n&&i(e,t,n,r);e._dispatchListeners=null,e._dispatchIDs=null}function s(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function l(e){var t=s(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function c(e){var t=e._dispatchListeners,n=e._dispatchIDs;Array.isArray(t)?h(!1):void 0;var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var d=e(15),f=e(59),h=e(157),v=(e(167),{Mount:null,injectMount:function(e){v.Mount=e}}),m=d.topLevelTypes,g={isEndish:r,isMoveish:o,isStartish:a,executeDirectDispatch:c,executeDispatchesInOrder:u,executeDispatchesInOrderStopAtTrue:l,hasDispatches:p,getNode:function(e){return v.Mount.getNode(e)},getID:function(e){return v.Mount.getID(e)},injection:v};t.exports=g},{15:15,157:157,167:167,59:59}],19:[function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return y(e,r)}function o(e,t,n){var o=t?g.bubbled:g.captured,a=r(e,n,o);a&&(n._dispatchListeners=v(n._dispatchListeners,a),n._dispatchIDs=v(n._dispatchIDs,e))}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(e.dispatchMarker,o,e)}function u(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=y(e,r);o&&(n._dispatchListeners=v(n._dispatchListeners,o),n._dispatchIDs=v(n._dispatchIDs,e))}}function s(e){e&&e.dispatchConfig.registrationName&&u(e.dispatchMarker,null,e)}function l(e){m(e,a)}function c(e){m(e,i)}function p(e,t,n,r){h.injection.getInstanceHandle().traverseEnterLeave(n,r,u,e,t)}function d(e){m(e,s)}var f=e(15),h=e(16),v=(e(167),e(112)),m=e(120),g=f.PropagationPhases,y=h.getListener,C={accumulateTwoPhaseDispatches:l,accumulateTwoPhaseDispatchesSkipTarget:c,accumulateDirectDispatches:d,accumulateEnterLeaveDispatches:p};t.exports=C},{112:112,120:120,15:15,16:16,167:167}],20:[function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=e(25),a=e(24),i=e(127);a(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[i()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),a=o.length;for(e=0;r>e&&n[e]===o[e];e++);var i=r-e;for(t=1;i>=t&&n[r-t]===o[a-t];t++);var u=t>1?1-t:void 0;return this._fallbackText=o.slice(e,u),this._fallbackText}}),o.addPoolingTo(r),t.exports=r},{127:127,24:24,25:25}],21:[function(e,t,n){"use strict";var r,o=e(10),a=e(143),i=o.injection.MUST_USE_ATTRIBUTE,u=o.injection.MUST_USE_PROPERTY,s=o.injection.HAS_BOOLEAN_VALUE,l=o.injection.HAS_SIDE_EFFECTS,c=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,d=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(a.canUseDOM){var f=document.implementation;r=f&&f.hasFeature&&f.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var h={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:i|s,allowTransparency:i,alt:null,async:s,autoComplete:null,autoPlay:s,capture:i|s,cellPadding:null,cellSpacing:null,charSet:i,challenge:i,checked:u|s,classID:i,className:r?i:u,cols:i|p,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:u|s,coords:null,crossOrigin:null,data:null,dateTime:i,defer:s,dir:null,disabled:i|s,download:d,draggable:null,encType:null,form:i,formAction:i,formEncType:i,formMethod:i,formNoValidate:s,formTarget:i,frameBorder:i,headers:null,height:i,hidden:i|s,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:u,inputMode:i,is:i,keyParams:i,keyType:i,label:null,lang:null,list:i,loop:u|s,low:null,manifest:i,marginHeight:null,marginWidth:null,max:null,maxLength:i,media:i,mediaGroup:null,method:null,min:null,minLength:i,multiple:u|s,muted:u|s,name:null,noValidate:s,open:s,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:u|s,rel:null,required:s,role:i,rows:i|p,rowSpan:null,sandbox:null,scope:null,scoped:s,scrolling:null,seamless:i|s,selected:u|s,shape:null,size:i|p,sizes:i,span:p,spellCheck:null,src:null,srcDoc:u,srcSet:i,start:c,step:null,style:null,summary:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:u|l,width:i,wmode:i,wrap:null,about:i,datatype:i,inlist:i,prefix:i,property:i,resource:i,"typeof":i,vocab:i,autoCapitalize:null,autoCorrect:null,autoSave:null,itemProp:i,itemScope:i|s,itemType:i,itemID:i,itemRef:i,results:null,security:i,unselectable:i},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",autoSave:"autosave",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=h},{10:10,143:143}],22:[function(e,t,n){"use strict";var r=e(68),o=e(88),a={linkState:function(e){return new r(this.state[e],o.createStateKeySetter(this,e))}};t.exports=a},{68:68,88:88}],23:[function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?l(!1):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?l(!1):void 0}function a(e){r(e),null!=e.checked||null!=e.onChange?l(!1):void 0}function i(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var u=e(80),s=e(79),l=e(157),c=(e(167),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),p={value:function(e,t,n){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:u.func},d={},f={checkPropTypes:function(e,t,n){for(var r in p){if(p.hasOwnProperty(r))var o=p[r](t,r,e,s.prop);o instanceof Error&&!(o.message in d)&&(d[o.message]=!0,i(n))}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(a(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(a(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};t.exports=f},{157:157,167:167,79:79,80:80}],24:[function(e,t,n){"use strict";function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),r=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var a=arguments[o];if(null!=a){var i=Object(a);for(var u in i)r.call(i,u)&&(n[u]=i[u])}}return n}t.exports=r},{}],25:[function(e,t,n){"use strict";var r=e(157),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},a=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},i=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},u=function(e,t,n,r){var o=this;if(o.instancePool.length){var a=o.instancePool.pop();return o.call(a,e,t,n,r),a}return new o(e,t,n,r)},s=function(e,t,n,r,o){var a=this;if(a.instancePool.length){var i=a.instancePool.pop();return a.call(i,e,t,n,r,o),i}return new a(e,t,n,r,o)},l=function(e){var t=this;e instanceof t?void 0:r(!1),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=10,p=o,d=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=c),n.release=l,n},f={addPoolingTo:d,oneArgumentPooler:o,twoArgumentPooler:a,threeArgumentPooler:i,fourArgumentPooler:u,fiveArgumentPooler:s};t.exports=f},{157:157}],26:[function(e,t,n){"use strict";var r=e(40),o=e(50),a=e(67),i=e(24),u=e(116),s={};i(s,a),i(s,{findDOMNode:u("findDOMNode","ReactDOM","react-dom",r,r.findDOMNode),render:u("render","ReactDOM","react-dom",r,r.render),unmountComponentAtNode:u("unmountComponentAtNode","ReactDOM","react-dom",r,r.unmountComponentAtNode),renderToString:u("renderToString","ReactDOMServer","react-dom/server",o,o.renderToString),renderToStaticMarkup:u("renderToStaticMarkup","ReactDOMServer","react-dom/server",o,o.renderToStaticMarkup)}),s.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=r,t.exports=s},{116:116,24:24,40:40,50:50,67:67}],27:[function(e,t,n){"use strict";var r=(e(66),e(118)),o=(e(167),"_getDOMNodeDidWarn"),a={getDOMNode:function(){return this.constructor[o]=!0,r(this)}};t.exports=a},{118:118,167:167,66:66}],28:[function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=h++,d[e[m]]={}),d[e[m]]}var o=e(15),a=e(16),i=e(17),u=e(60),s=e(76),l=e(111),c=e(24),p=e(129),d={},f=!1,h=0,v={topAbort:"abort",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover", topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),g=c({},u,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(g.handleTopLevel),g.ReactEventListener=e}},setEnabled:function(e){g.ReactEventListener&&g.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!g.ReactEventListener||!g.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,a=r(n),u=i.registrationNameDependencies[e],s=o.topLevelTypes,l=0;l<u.length;l++){var c=u[l];a.hasOwnProperty(c)&&a[c]||(c===s.topWheel?p("wheel")?g.ReactEventListener.trapBubbledEvent(s.topWheel,"wheel",n):p("mousewheel")?g.ReactEventListener.trapBubbledEvent(s.topWheel,"mousewheel",n):g.ReactEventListener.trapBubbledEvent(s.topWheel,"DOMMouseScroll",n):c===s.topScroll?p("scroll",!0)?g.ReactEventListener.trapCapturedEvent(s.topScroll,"scroll",n):g.ReactEventListener.trapBubbledEvent(s.topScroll,"scroll",g.ReactEventListener.WINDOW_HANDLE):c===s.topFocus||c===s.topBlur?(p("focus",!0)?(g.ReactEventListener.trapCapturedEvent(s.topFocus,"focus",n),g.ReactEventListener.trapCapturedEvent(s.topBlur,"blur",n)):p("focusin")&&(g.ReactEventListener.trapBubbledEvent(s.topFocus,"focusin",n),g.ReactEventListener.trapBubbledEvent(s.topBlur,"focusout",n)),a[s.topBlur]=!0,a[s.topFocus]=!0):v.hasOwnProperty(c)&&g.ReactEventListener.trapBubbledEvent(c,v[c],n),a[c]=!0)}},trapBubbledEvent:function(e,t,n){return g.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return g.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!f){var e=l.refreshScrollValues;g.ReactEventListener.monitorScrollValue(e),f=!0}},eventNameDispatchConfigs:a.eventNameDispatchConfigs,registrationNameModules:a.registrationNameModules,putListener:a.putListener,getListener:a.getListener,deleteListener:a.deleteListener,deleteAllListeners:a.deleteAllListeners});s.measureMethods(g,"ReactBrowserEventEmitter",{putListener:"putListener",deleteListener:"deleteListener"}),t.exports=g},{111:111,129:129,15:15,16:16,17:17,24:24,60:60,76:76}],29:[function(e,t,n){"use strict";function r(e){var t="transition"+e+"Timeout",n="transition"+e;return function(e){if(e[n]){if(!e[t])return new Error(t+" wasn't supplied to ReactCSSTransitionGroup: this can cause unreliable animations and won't be supported in a future version of React. See https://fb.me/react-animation-transition-group-timeout for more information.");if("number"!=typeof e[t])return new Error(t+" must be a number (in milliseconds)")}}}var o=e(26),a=e(24),i=e(91),u=e(30),s=o.createClass({displayName:"ReactCSSTransitionGroup",propTypes:{transitionName:u.propTypes.name,transitionAppear:o.PropTypes.bool,transitionEnter:o.PropTypes.bool,transitionLeave:o.PropTypes.bool,transitionAppearTimeout:r("Appear"),transitionEnterTimeout:r("Enter"),transitionLeaveTimeout:r("Leave")},getDefaultProps:function(){return{transitionAppear:!1,transitionEnter:!0,transitionLeave:!0}},_wrapChild:function(e){return o.createElement(u,{name:this.props.transitionName,appear:this.props.transitionAppear,enter:this.props.transitionEnter,leave:this.props.transitionLeave,appearTimeout:this.props.transitionAppearTimeout,enterTimeout:this.props.transitionEnterTimeout,leaveTimeout:this.props.transitionLeaveTimeout},e)},render:function(){return o.createElement(i,a({},this.props,{childFactory:this._wrapChild}))}});t.exports=s},{24:24,26:26,30:30,91:91}],30:[function(e,t,n){"use strict";var r=e(26),o=e(40),a=e(141),i=e(90),u=e(131),s=17,l=r.createClass({displayName:"ReactCSSTransitionGroupChild",propTypes:{name:r.PropTypes.oneOfType([r.PropTypes.string,r.PropTypes.shape({enter:r.PropTypes.string,leave:r.PropTypes.string,active:r.PropTypes.string}),r.PropTypes.shape({enter:r.PropTypes.string,enterActive:r.PropTypes.string,leave:r.PropTypes.string,leaveActive:r.PropTypes.string,appear:r.PropTypes.string,appearActive:r.PropTypes.string})]).isRequired,appear:r.PropTypes.bool,enter:r.PropTypes.bool,leave:r.PropTypes.bool,appearTimeout:r.PropTypes.number,enterTimeout:r.PropTypes.number,leaveTimeout:r.PropTypes.number},transition:function(e,t,n){var r=o.findDOMNode(this);if(!r)return void(t&&t());var u=this.props.name[e]||this.props.name+"-"+e,s=this.props.name[e+"Active"]||u+"-active",l=null,c=function(e){e&&e.target!==r||(clearTimeout(l),a.removeClass(r,u),a.removeClass(r,s),i.removeEndEventListener(r,c),t&&t())};a.addClass(r,u),this.queueClass(s),n?l=setTimeout(c,n):i.addEndEventListener(r,c)},queueClass:function(e){this.classNameQueue.push(e),this.timeout||(this.timeout=setTimeout(this.flushClassNameQueue,s))},flushClassNameQueue:function(){this.isMounted()&&this.classNameQueue.forEach(a.addClass.bind(a,o.findDOMNode(this))),this.classNameQueue.length=0,this.timeout=null},componentWillMount:function(){this.classNameQueue=[]},componentWillUnmount:function(){this.timeout&&clearTimeout(this.timeout)},componentWillAppear:function(e){this.props.appear?this.transition("appear",e,this.props.appearTimeout):e()},componentWillEnter:function(e){this.props.enter?this.transition("enter",e,this.props.enterTimeout):e()},componentWillLeave:function(e){this.props.leave?this.transition("leave",e,this.props.leaveTimeout):e()},render:function(){return u(this.props.children)}});t.exports=l},{131:131,141:141,26:26,40:40,90:90}],31:[function(e,t,n){"use strict";function r(e,t,n){var r=void 0===e[n];null!=t&&r&&(e[n]=a(t,null))}var o=e(82),a=e(128),i=e(137),u=e(138),s=(e(167),{instantiateChildren:function(e,t,n){if(null==e)return null;var o={};return u(e,r,o),o},updateChildren:function(e,t,n,r){if(!t&&!e)return null;var u;for(u in t)if(t.hasOwnProperty(u)){var s=e&&e[u],l=s&&s._currentElement,c=t[u];if(null!=s&&i(l,c))o.receiveComponent(s,c,n,r),t[u]=s;else{s&&o.unmountComponent(s,u);var p=a(c,null);t[u]=p}}for(u in e)!e.hasOwnProperty(u)||t&&t.hasOwnProperty(u)||o.unmountComponent(e[u]);return t},unmountChildren:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];o.unmountComponent(n)}}});t.exports=s},{128:128,137:137,138:138,167:167,82:82}],32:[function(e,t,n){"use strict";function r(e){return(""+e).replace(b,"//")}function o(e,t){this.func=e,this.context=t,this.count=0}function a(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function i(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);g(e,a,r),o.release(r)}function u(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function s(e,t,n){var o=e.result,a=e.keyPrefix,i=e.func,u=e.context,s=i.call(u,t,e.count++);Array.isArray(s)?l(s,o,n,m.thatReturnsArgument):null!=s&&(v.isValidElement(s)&&(s=v.cloneAndReplaceKey(s,a+(s!==t?r(s.key||"")+"/":"")+n)),o.push(s))}function l(e,t,n,o,a){var i="";null!=n&&(i=r(n)+"/");var l=u.getPooled(t,i,o,a);g(e,s,l),u.release(l)}function c(e,t,n){if(null==e)return e;var r=[];return l(e,r,null,t,n),r}function p(e,t,n){return null}function d(e,t){return g(e,p,null)}function f(e){var t=[];return l(e,t,null,m.thatReturnsArgument),t}var h=e(25),v=e(55),m=e(149),g=e(138),y=h.twoArgumentPooler,C=h.fourArgumentPooler,b=/\/(?!\/)/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(o,y),u.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(u,C);var E={forEach:i,map:c,mapIntoWithKeyPrefixInternal:l,count:d,toArray:f};t.exports=E},{138:138,149:149,25:25,55:55}],33:[function(e,t,n){"use strict";function r(e,t){var n=_.hasOwnProperty(t)?_[t]:null;D.hasOwnProperty(t)&&(n!==b.OVERRIDE_BASE?m(!1):void 0),e.hasOwnProperty(t)&&(n!==b.DEFINE_MANY&&n!==b.DEFINE_MANY_MERGED?m(!1):void 0)}function o(e,t){if(t){"function"==typeof t?m(!1):void 0,d.isValidElement(t)?m(!1):void 0;var n=e.prototype;t.hasOwnProperty(C)&&x.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==C){var a=t[o];if(r(n,o),x.hasOwnProperty(o))x[o](e,a);else{var i=_.hasOwnProperty(o),l=n.hasOwnProperty(o),c="function"==typeof a,p=c&&!i&&!l&&t.autobind!==!1;if(p)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[o]=a,n[o]=a;else if(l){var f=_[o];!i||f!==b.DEFINE_MANY_MERGED&&f!==b.DEFINE_MANY?m(!1):void 0,f===b.DEFINE_MANY_MERGED?n[o]=u(n[o],a):f===b.DEFINE_MANY&&(n[o]=s(n[o],a))}else n[o]=a}}}}function a(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in x;o?m(!1):void 0;var a=n in e;a?m(!1):void 0,e[n]=r}}}function i(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:m(!1);for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]?m(!1):void 0,e[n]=t[n]);return e}function u(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return i(o,n),i(o,r),o}}function s(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var n=t.bind(e);return n}function c(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=l(e,n)}}var p=e(34),d=e(55),f=(e(79),e(78),e(74)),h=e(24),v=e(150),m=e(157),g=e(161),y=e(162),C=(e(167),y({mixins:null})),b=g({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),E=[],_={mixins:b.DEFINE_MANY,statics:b.DEFINE_MANY,propTypes:b.DEFINE_MANY,contextTypes:b.DEFINE_MANY,childContextTypes:b.DEFINE_MANY,getDefaultProps:b.DEFINE_MANY_MERGED,getInitialState:b.DEFINE_MANY_MERGED,getChildContext:b.DEFINE_MANY_MERGED,render:b.DEFINE_ONCE,componentWillMount:b.DEFINE_MANY,componentDidMount:b.DEFINE_MANY,componentWillReceiveProps:b.DEFINE_MANY,shouldComponentUpdate:b.DEFINE_ONCE,componentWillUpdate:b.DEFINE_MANY,componentDidUpdate:b.DEFINE_MANY,componentWillUnmount:b.DEFINE_MANY,updateComponent:b.OVERRIDE_BASE},x={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=h({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=h({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=h({},e.propTypes,t)},statics:function(e,t){a(e,t)},autobind:function(){}},D={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t)},isMounted:function(){return this.updater.isMounted(this)},setProps:function(e,t){this.updater.enqueueSetProps(this,e),t&&this.updater.enqueueCallback(this,t)},replaceProps:function(e,t){this.updater.enqueueReplaceProps(this,e),t&&this.updater.enqueueCallback(this,t)}},P=function(){};h(P.prototype,p.prototype,D);var T={createClass:function(e){var t=function(e,t,n){this.__reactAutoBindMap&&c(this),this.props=e,this.context=t,this.refs=v,this.updater=n||f,this.state=null;var r=this.getInitialState?this.getInitialState():null;"object"!=typeof r||Array.isArray(r)?m(!1):void 0,this.state=r};t.prototype=new P,t.prototype.constructor=t,E.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:m(!1);for(var n in _)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){E.push(e)}}};t.exports=T},{150:150,157:157,161:161,162:162,167:167,24:24,34:34,55:55,74:74,78:78,79:79}],34:[function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=a,this.updater=n||o}var o=e(74),a=e(150),i=e(157);e(167);r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?i(!1):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e)};t.exports=r},{150:150,157:157,167:167,74:74}],35:[function(e,t,n){"use strict";var r=e(45),o=e(70),a={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};t.exports=a},{45:45,70:70}],36:[function(e,t,n){"use strict";var r=e(157),o=!1,a={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o?r(!1):void 0,a.unmountIDFromEnvironment=e.unmountIDFromEnvironment,a.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,a.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};t.exports=a},{157:157}],37:[function(e,t,n){"use strict";var r=e(136),o={shouldComponentUpdate:function(e,t){return r(this,e,t)}};t.exports=o},{136:136}],38:[function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}function o(e){}var a=e(36),i=e(39),u=e(55),s=e(66),l=e(76),c=e(79),p=(e(78),e(82)),d=e(92),f=e(24),h=e(150),v=e(157),m=e(137);e(167);o.prototype.render=function(){var e=s.get(this)._currentElement.type;return e(this.props,this.context,this.updater)};var g=1,y={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=g++,this._rootNodeID=e;var r,a,i=this._processProps(this._currentElement.props),l=this._processContext(n),c=this._currentElement.type,f="prototype"in c;f&&(r=new c(i,l,d)),(!f||null===r||r===!1||u.isValidElement(r))&&(a=r,r=new o(c)),r.props=i,r.context=l,r.refs=h,r.updater=d,this._instance=r,s.set(r,this);var m=r.state;void 0===m&&(r.state=m=null),"object"!=typeof m||Array.isArray(m)?v(!1):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,r.componentWillMount&&(r.componentWillMount(),this._pendingStateQueue&&(r.state=this._processPendingState(r.props,r.context))),void 0===a&&(a=this._renderValidatedComponent()),this._renderedComponent=this._instantiateReactComponent(a);var y=p.mountComponent(this._renderedComponent,e,t,this._processChildContext(n));return r.componentDidMount&&t.getReactMountReady().enqueue(r.componentDidMount,r),y},unmountComponent:function(){var e=this._instance;e.componentWillUnmount&&e.componentWillUnmount(),p.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._instance=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,s.remove(e)},_maskContext:function(e){var t=null,n=this._currentElement.type,r=n.contextTypes;if(!r)return h;t={};for(var o in r)t[o]=e[o];return t},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._currentElement.type,n=this._instance,r=n.getChildContext&&n.getChildContext();if(r){"object"!=typeof t.childContextTypes?v(!1):void 0;for(var o in r)o in t.childContextTypes?void 0:v(!1);return f({},e,r)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var a in e)if(e.hasOwnProperty(a)){var i;try{"function"!=typeof e[a]?v(!1):void 0,i=e[a](t,a,o,n)}catch(u){i=u}i instanceof Error&&(r(this),n===c.prop)}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&p.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},updateComponent:function(e,t,n,r,o){var a,i=this._instance,u=this._context===o?i.context:this._processContext(o);t===n?a=n.props:(a=this._processProps(n.props),i.componentWillReceiveProps&&i.componentWillReceiveProps(a,u));var s=this._processPendingState(a,u),l=this._pendingForceUpdate||!i.shouldComponentUpdate||i.shouldComponentUpdate(a,s,u);l?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,a,s,u,e,o)):(this._currentElement=n,this._context=o,i.props=a,i.state=s,i.context=u)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var a=f({},o?r[0]:n.state),i=o?1:0;i<r.length;i++){var u=r[i];f(a,"function"==typeof u?u.call(n,a,e,t):u)}return a},_performComponentUpdate:function(e,t,n,r,o,a){var i,u,s,l=this._instance,c=Boolean(l.componentDidUpdate);c&&(i=l.props,u=l.state,s=l.context),l.componentWillUpdate&&l.componentWillUpdate(t,n,r),this._currentElement=e,this._context=a,l.props=t,l.state=n,l.context=r,this._updateRenderedComponent(o,a),c&&o.getReactMountReady().enqueue(l.componentDidUpdate.bind(l,i,u,s),l)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(m(r,o))p.receiveComponent(n,o,e,this._processChildContext(t));else{var a=this._rootNodeID,i=n._rootNodeID;p.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(o);var u=p.mountComponent(this._renderedComponent,a,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(i,u)}},_replaceNodeWithMarkupByID:function(e,t){a.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(){var e;i.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{i.current=null}return null===e||e===!1||u.isValidElement(e)?void 0:v(!1),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n?v(!1):void 0;var r=t.getPublicInstance(),o=n.refs===h?n.refs={}:n.refs;o[e]=r},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return e instanceof o?null:e},_instantiateReactComponent:null};l.measureMethods(y,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var C={Mixin:y};t.exports=C},{137:137,150:150,157:157,167:167,24:24,36:36,39:39,55:55,66:66,76:76,78:78,79:79,82:82,92:92}],39:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],40:[function(e,t,n){"use strict";var r=e(39),o=e(51),a=e(54),i=e(65),u=e(70),s=e(76),l=e(82),c=e(93),p=e(94),d=e(118),f=e(133);e(167);a.inject();var h=s.measure("React","render",u.render),v={findDOMNode:d,render:h,unmountComponentAtNode:u.unmountComponentAtNode,version:p,unstable_batchedUpdates:c.batchedUpdates,unstable_renderSubtreeIntoContainer:f};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:r,InstanceHandles:i,Mount:u,Reconciler:l,TextComponent:o});t.exports=v},{118:118,133:133,167:167,39:39,51:51,54:54,65:65,70:70,76:76,82:82,93:93,94:94}],41:[function(e,t,n){"use strict";var r={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},o={getNativeProps:function(e,t,n){if(!t.disabled)return t;var o={};for(var a in t)t.hasOwnProperty(a)&&!r[a]&&(o[a]=t[a]);return o}};t.exports=o},{}],42:[function(e,t,n){"use strict";function r(){return this}function o(){var e=this._reactInternalComponent;return!!e}function a(){}function i(e,t){var n=this._reactInternalComponent;n&&(I.enqueueSetPropsInternal(n,e),t&&I.enqueueCallbackInternal(n,t))}function u(e,t){var n=this._reactInternalComponent;n&&(I.enqueueReplacePropsInternal(n,e),t&&I.enqueueCallbackInternal(n,t))}function s(e,t){t&&(null!=t.dangerouslySetInnerHTML&&(null!=t.children?A(!1):void 0,"object"==typeof t.dangerouslySetInnerHTML&&"__html"in t.dangerouslySetInnerHTML?void 0:A(!1)),null!=t.style&&"object"!=typeof t.style?A(!1):void 0)}function l(e,t,n,r){var o=w.findReactContainerForID(e);if(o){var a=o.nodeType===q?o.ownerDocument:o;V(t,a)}r.getReactMountReady().enqueue(c,{id:e,registrationName:t,listener:n})}function c(){var e=this;_.putListener(e.id,e.registrationName,e.listener)}function p(){var e=this;e._rootNodeID?void 0:A(!1);var t=w.getNode(e._rootNodeID);switch(t?void 0:A(!1),e._tag){case"iframe":e._wrapperState.listeners=[_.trapBubbledEvent(E.topLevelTypes.topLoad,"load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in Y)Y.hasOwnProperty(n)&&e._wrapperState.listeners.push(_.trapBubbledEvent(E.topLevelTypes[n],Y[n],t));break;case"img":e._wrapperState.listeners=[_.trapBubbledEvent(E.topLevelTypes.topError,"error",t),_.trapBubbledEvent(E.topLevelTypes.topLoad,"load",t)];break;case"form":e._wrapperState.listeners=[_.trapBubbledEvent(E.topLevelTypes.topReset,"reset",t),_.trapBubbledEvent(E.topLevelTypes.topSubmit,"submit",t)]}}function d(){P.mountReadyWrapper(this)}function f(){M.postUpdateWrapper(this)}function h(e){Z.call($,e)||(X.test(e)?void 0:A(!1),$[e]=!0)}function v(e,t){return e.indexOf("-")>=0||null!=t.is}function m(e){h(e),this._tag=e.toLowerCase(),this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._rootNodeID=null,this._wrapperState=null,this._topLevelWrapper=null,this._nodeWithLegacyProperties=null}var g=e(2),y=e(5),C=e(10),b=e(11),E=e(15),_=e(28),x=e(35),D=e(41),P=e(46),T=e(47),M=e(48),N=e(52),w=e(70),S=e(71),R=e(76),I=e(92),k=e(24),O=e(117),A=e(157),L=(e(129),e(162)),U=e(134),F=e(135),B=(e(165),e(140),e(167),_.deleteListener),V=_.listenTo,j=_.registrationNameModules,W={string:!0,number:!0},K=L({style:null}),q=1,H=!1;try{Object.defineProperty({},"test",{get:function(){}}),H=!0}catch(z){}var Y={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},G={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},Q={listing:!0,pre:!0,textarea:!0},X=(k({menuitem:!0},G),/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/),$={},Z={}.hasOwnProperty;m.displayName="ReactDOMComponent",m.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e;var r=this._currentElement.props;switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},t.getReactMountReady().enqueue(p,this);break;case"button":r=D.getNativeProps(this,r,n);break;case"input":P.mountWrapper(this,r,n),r=P.getNativeProps(this,r,n);break;case"option":T.mountWrapper(this,r,n),r=T.getNativeProps(this,r,n);break;case"select":M.mountWrapper(this,r,n),r=M.getNativeProps(this,r,n),n=M.processChildContext(this,r,n);break;case"textarea":N.mountWrapper(this,r,n),r=N.getNativeProps(this,r,n)}s(this,r);var o;if(t.useCreateElement){var a=n[w.ownerDocumentContextKey],i=a.createElement(this._currentElement.type);b.setAttributeForID(i,this._rootNodeID),w.getID(i),this._updateDOMProperties({},r,t,i),this._createInitialChildren(t,r,n,i),o=i}else{var u=this._createOpenTagMarkupAndPutListeners(t,r),l=this._createContentMarkup(t,r,n);o=!l&&G[this._tag]?u+"/>":u+">"+l+"</"+this._currentElement.type+">"}switch(this._tag){case"input":t.getReactMountReady().enqueue(d,this);case"button":case"select":case"textarea":r.autoFocus&&t.getReactMountReady().enqueue(g.focusDOMComponent,this)}return o},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(j.hasOwnProperty(r))o&&l(this._rootNodeID,r,o,e);else{r===K&&(o&&(o=this._previousStyleCopy=k({},t.style)),o=y.createMarkupForStyles(o));var a=null;a=null!=this._tag&&v(this._tag,t)?b.createMarkupForCustomAttribute(r,o):b.createMarkupForProperty(r,o),a&&(n+=" "+a)}}if(e.renderToStaticMarkup)return n;var i=b.createMarkupForID(this._rootNodeID);return n+" "+i},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var a=W[typeof t.children]?t.children:null,i=null!=a?null:t.children;if(null!=a)r=O(a);else if(null!=i){var u=this.mountChildren(i,e,n);r=u.join("")}}return Q[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&U(r,o.__html);else{var a=W[typeof t.children]?t.children:null,i=null!=a?null:t.children;if(null!=a)F(r,a);else if(null!=i)for(var u=this.mountChildren(i,e,n),s=0;s<u.length;s++)r.appendChild(u[s])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,r){var o=t.props,a=this._currentElement.props;switch(this._tag){case"button":o=D.getNativeProps(this,o),a=D.getNativeProps(this,a);break;case"input":P.updateWrapper(this),o=P.getNativeProps(this,o),a=P.getNativeProps(this,a);break;case"option":o=T.getNativeProps(this,o),a=T.getNativeProps(this,a);break;case"select":o=M.getNativeProps(this,o),a=M.getNativeProps(this,a);break;case"textarea":N.updateWrapper(this),o=N.getNativeProps(this,o),a=N.getNativeProps(this,a)}s(this,a),this._updateDOMProperties(o,a,e,null),this._updateDOMChildren(o,a,e,r),!H&&this._nodeWithLegacyProperties&&(this._nodeWithLegacyProperties.props=a),"select"===this._tag&&e.getReactMountReady().enqueue(f,this)},_updateDOMProperties:function(e,t,n,r){var o,a,i;for(o in e)if(!t.hasOwnProperty(o)&&e.hasOwnProperty(o))if(o===K){var u=this._previousStyleCopy;for(a in u)u.hasOwnProperty(a)&&(i=i||{},i[a]="");this._previousStyleCopy=null}else j.hasOwnProperty(o)?e[o]&&B(this._rootNodeID,o):(C.properties[o]||C.isCustomAttribute(o))&&(r||(r=w.getNode(this._rootNodeID)),b.deleteValueForProperty(r,o));for(o in t){var s=t[o],c=o===K?this._previousStyleCopy:e[o];if(t.hasOwnProperty(o)&&s!==c)if(o===K)if(s?s=this._previousStyleCopy=k({},s):this._previousStyleCopy=null,c){for(a in c)!c.hasOwnProperty(a)||s&&s.hasOwnProperty(a)||(i=i||{},i[a]="");for(a in s)s.hasOwnProperty(a)&&c[a]!==s[a]&&(i=i||{},i[a]=s[a])}else i=s;else j.hasOwnProperty(o)?s?l(this._rootNodeID,o,s,n):c&&B(this._rootNodeID,o):v(this._tag,t)?(r||(r=w.getNode(this._rootNodeID)),b.setValueForAttribute(r,o,s)):(C.properties[o]||C.isCustomAttribute(o))&&(r||(r=w.getNode(this._rootNodeID)),null!=s?b.setValueForProperty(r,o,s):b.deleteValueForProperty(r,o))}i&&(r||(r=w.getNode(this._rootNodeID)),y.setValueForStyles(r,i))},_updateDOMChildren:function(e,t,n,r){var o=W[typeof e.children]?e.children:null,a=W[typeof t.children]?t.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,u=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,l=null!=a?null:t.children,c=null!=o||null!=i,p=null!=a||null!=u;null!=s&&null==l?this.updateChildren(null,n,r):c&&!p&&this.updateTextContent(""),null!=a?o!==a&&this.updateTextContent(""+a):null!=u?i!==u&&this.updateMarkup(""+u):null!=l&&this.updateChildren(l,n,r)},unmountComponent:function(){switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":var e=this._wrapperState.listeners;if(e)for(var t=0;t<e.length;t++)e[t].remove();break;case"input":P.unmountWrapper(this);break;case"html":case"head":case"body":A(!1)}if(this.unmountChildren(),_.deleteAllListeners(this._rootNodeID),x.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._wrapperState=null,this._nodeWithLegacyProperties){var n=this._nodeWithLegacyProperties;n._reactInternalComponent=null,this._nodeWithLegacyProperties=null}},getPublicInstance:function(){if(!this._nodeWithLegacyProperties){var e=w.getNode(this._rootNodeID);e._reactInternalComponent=this,e.getDOMNode=r,e.isMounted=o,e.setState=a,e.replaceState=a,e.forceUpdate=a,e.setProps=i,e.replaceProps=u,e.props=this._currentElement.props,this._nodeWithLegacyProperties=e}return this._nodeWithLegacyProperties}},R.measureMethods(m,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),k(m.prototype,m.Mixin,S.Mixin),t.exports=m},{10:10,11:11,117:117,129:129,134:134,135:135,140:140,15:15,157:157,162:162,165:165,167:167,2:2,24:24,28:28,35:35,41:41,46:46,47:47,48:48,5:5,52:52,70:70,71:71,76:76,92:92}],43:[function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=e(55),a=(e(56),e(163)),i=a({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hgroup:"hgroup",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",image:"image",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);t.exports=i},{163:163,55:55,56:56}],44:[function(e,t,n){"use strict";var r={useCreateElement:!1};t.exports=r},{}],45:[function(e,t,n){"use strict";var r=e(9),o=e(11),a=e(70),i=e(76),u=e(157),s={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.", style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:function(e,t,n){var r=a.getNode(e);s.hasOwnProperty(t)?u(!1):void 0,null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=a.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=a.getNode(e[n].parentID);r.processUpdates(e,t)}};i.measureMethods(l,"ReactDOMIDOperations",{dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),t.exports=l},{11:11,157:157,70:70,76:76,9:9}],46:[function(e,t,n){"use strict";function r(){this._rootNodeID&&d.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=i.executeOnChange(t,e);s.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var a=u.getNode(this._rootNodeID),l=a;l.parentNode;)l=l.parentNode;for(var d=l.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),f=0;f<d.length;f++){var h=d[f];if(h!==a&&h.form===a.form){var v=u.getID(h);v?void 0:c(!1);var m=p[v];m?void 0:c(!1),s.asap(r,m)}}}return n}var a=e(45),i=e(23),u=e(70),s=e(93),l=e(24),c=e(157),p={},d={getNativeProps:function(e,t,n){var r=i.getValue(t),o=i.getChecked(t),a=l({},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=r?r:e._wrapperState.initialValue,checked:null!=o?o:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange});return a},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:t.defaultChecked||!1,initialValue:null!=n?n:null,onChange:o.bind(e)}},mountReadyWrapper:function(e){p[e._rootNodeID]=e},unmountWrapper:function(e){delete p[e._rootNodeID]},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&a.updatePropertyByID(e._rootNodeID,"checked",n||!1);var r=i.getValue(t);null!=r&&a.updatePropertyByID(e._rootNodeID,"value",""+r)}};t.exports=d},{157:157,23:23,24:24,45:45,70:70,93:93}],47:[function(e,t,n){"use strict";var r=e(32),o=e(48),a=e(24),i=(e(167),o.valueContextKey),u={mountWrapper:function(e,t,n){var r=n[i],o=null;if(null!=r)if(o=!1,Array.isArray(r)){for(var a=0;a<r.length;a++)if(""+r[a]==""+t.value){o=!0;break}}else o=""+r==""+t.value;e._wrapperState={selected:o}},getNativeProps:function(e,t,n){var o=a({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(o.selected=e._wrapperState.selected);var i="";return r.forEach(t.children,function(e){null!=e&&("string"==typeof e||"number"==typeof e)&&(i+=e)}),o.children=i,o}};t.exports=u},{167:167,24:24,32:32,48:48}],48:[function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=i.getValue(e);null!=t&&o(this,e,t)}}function o(e,t,n){var r,o,a=u.getNode(e._rootNodeID).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<a.length;o++){var i=r.hasOwnProperty(a[o].value);a[o].selected!==i&&(a[o].selected=i)}}else{for(r=""+n,o=0;o<a.length;o++)if(a[o].value===r)return void(a[o].selected=!0);a.length&&(a[0].selected=!0)}}function a(e){var t=this._currentElement.props,n=i.executeOnChange(t,e);return this._wrapperState.pendingUpdate=!0,s.asap(r,this),n}var i=e(23),u=e(70),s=e(93),l=e(24),c=(e(167),"__ReactDOMSelect_value$"+Math.random().toString(36).slice(2)),p={valueContextKey:c,getNativeProps:function(e,t,n){return l({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=i.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,onChange:a.bind(e),wasMultiple:Boolean(t.multiple)}},processChildContext:function(e,t,n){var r=l({},n);return r[c]=e._wrapperState.initialValue,r},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=i.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};t.exports=p},{167:167,23:23,24:24,70:70,93:93}],49:[function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var a=o.text.length,i=a+r;return{start:a,end:i}}function a(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,a=t.focusNode,i=t.focusOffset,u=t.getRangeAt(0);try{u.startContainer.nodeType,u.endContainer.nodeType}catch(s){return null}var l=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=l?0:u.toString().length,p=u.cloneRange();p.selectNodeContents(e),p.setEnd(u.startContainer,u.startOffset);var d=r(p.startContainer,p.startOffset,p.endContainer,p.endOffset),f=d?0:p.toString().length,h=f+c,v=document.createRange();v.setStart(n,o),v.setEnd(a,i);var m=v.collapsed;return{start:m?h:f,end:m?f:h}}function i(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function u(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),a="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>a){var i=a;a=o,o=i}var u=l(e,o),s=l(e,a);if(u&&s){var p=document.createRange();p.setStart(u.node,u.offset),n.removeAllRanges(),o>a?(n.addRange(p),n.extend(s.node,s.offset)):(p.setEnd(s.node,s.offset),n.addRange(p))}}}var s=e(143),l=e(126),c=e(127),p=s.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:a,setOffsets:p?i:u};t.exports=d},{126:126,127:127,143:143}],50:[function(e,t,n){"use strict";var r=e(54),o=e(86),a=e(94);r.inject();var i={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:a};t.exports=i},{54:54,86:86,94:94}],51:[function(e,t,n){"use strict";var r=e(9),o=e(11),a=e(35),i=e(70),u=e(24),s=e(117),l=e(135),c=(e(140),function(e){});u(c.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){if(this._rootNodeID=e,t.useCreateElement){var r=n[i.ownerDocumentContextKey],a=r.createElement("span");return o.setAttributeForID(a,e),i.getID(a),l(a,this._stringText),a}var u=s(this._stringText);return t.renderToStaticMarkup?u:"<span "+o.createMarkupForID(e)+">"+u+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var o=i.getNode(this._rootNodeID);r.updateTextContent(o,n)}}},unmountComponent:function(){a.unmountIDFromEnvironment(this._rootNodeID)}}),t.exports=c},{11:11,117:117,135:135,140:140,24:24,35:35,70:70,9:9}],52:[function(e,t,n){"use strict";function r(){this._rootNodeID&&c.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);return u.asap(r,this),n}var a=e(23),i=e(45),u=e(93),s=e(24),l=e(157),c=(e(167),{getNativeProps:function(e,t,n){null!=t.dangerouslySetInnerHTML?l(!1):void 0;var r=s({},t,{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return r},mountWrapper:function(e,t){var n=t.defaultValue,r=t.children;null!=r&&(null!=n?l(!1):void 0,Array.isArray(r)&&(r.length<=1?void 0:l(!1),r=r[0]),n=""+r),null==n&&(n="");var i=a.getValue(t);e._wrapperState={initialValue:""+(null!=i?i:n),onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=a.getValue(t);null!=n&&i.updatePropertyByID(e._rootNodeID,"value",""+n)}});t.exports=c},{157:157,167:167,23:23,24:24,45:45,93:93}],53:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=e(93),a=e(110),i=e(24),u=e(149),s={initialize:u,close:function(){d.isBatchingUpdates=!1}},l={initialize:u,close:o.flushBatchedUpdates.bind(o)},c=[l,s];i(r.prototype,a.Mixin,{getTransactionWrappers:function(){return c}});var p=new r,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,a){var i=d.isBatchingUpdates;d.isBatchingUpdates=!0,i?e(t,n,r,o,a):p.perform(e,null,t,n,r,o,a)}};t.exports=d},{110:110,149:149,24:24,93:93}],54:[function(e,t,n){"use strict";function r(){P||(P=!0,g.EventEmitter.injectReactEventListener(m),g.EventPluginHub.injectEventPluginOrder(u),g.EventPluginHub.injectInstanceHandle(y),g.EventPluginHub.injectMount(C),g.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:x,EnterLeaveEventPlugin:s,ChangeEventPlugin:a,SelectEventPlugin:E,BeforeInputEventPlugin:o}),g.NativeComponent.injectGenericComponentClass(h),g.NativeComponent.injectTextComponentClass(v),g.Class.injectMixin(p),g.DOMProperty.injectDOMPropertyConfig(c),g.DOMProperty.injectDOMPropertyConfig(D),g.EmptyComponent.injectEmptyComponent("noscript"),g.Updates.injectReconcileTransaction(b),g.Updates.injectBatchingStrategy(f),g.RootIndex.injectCreateReactRootIndex(l.canUseDOM?i.createReactRootIndex:_.createReactRootIndex),g.Component.injectEnvironment(d))}var o=e(3),a=e(7),i=e(8),u=e(13),s=e(14),l=e(143),c=e(21),p=e(27),d=e(35),f=e(53),h=e(42),v=e(51),m=e(61),g=e(63),y=e(65),C=e(70),b=e(81),E=e(96),_=e(97),x=e(98),D=e(95),P=!1;t.exports={inject:r}},{13:13,14:14,143:143,21:21,27:27,3:3,35:35,42:42,51:51,53:53,61:61,63:63,65:65,7:7,70:70,8:8,81:81,95:95,96:96,97:97,98:98}],55:[function(e,t,n){"use strict";var r=e(39),o=e(24),a="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103,i={key:!0,ref:!0,__self:!0,__source:!0},u=function(e,t,n,r,o,i,u){var s={$$typeof:a,type:e,key:t,ref:n,props:u,_owner:i};return s};u.createElement=function(e,t,n){var o,a={},s=null,l=null,c=null,p=null;if(null!=t){l=void 0===t.ref?null:t.ref,s=void 0===t.key?null:""+t.key,c=void 0===t.__self?null:t.__self,p=void 0===t.__source?null:t.__source;for(o in t)t.hasOwnProperty(o)&&!i.hasOwnProperty(o)&&(a[o]=t[o])}var d=arguments.length-2;if(1===d)a.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];a.children=f}if(e&&e.defaultProps){var v=e.defaultProps;for(o in v)"undefined"==typeof a[o]&&(a[o]=v[o])}return u(e,s,l,c,p,r.current,a)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceKey=function(e,t){var n=u(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},u.cloneAndReplaceProps=function(e,t){var n=u(e.type,e.key,e.ref,e._self,e._source,e._owner,t);return n},u.cloneElement=function(e,t,n){var a,s=o({},e.props),l=e.key,c=e.ref,p=e._self,d=e._source,f=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,f=r.current),void 0!==t.key&&(l=""+t.key);for(a in t)t.hasOwnProperty(a)&&!i.hasOwnProperty(a)&&(s[a]=t[a])}var h=arguments.length-2;if(1===h)s.children=n;else if(h>1){for(var v=Array(h),m=0;h>m;m++)v[m]=arguments[m+2];s.children=v}return u(e.type,l,c,p,d,f,s)},u.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===a},t.exports=u},{24:24,39:39}],56:[function(e,t,n){"use strict";function r(){if(p.current){var e=p.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e,t){e._store&&!e._store.validated&&null==e.key&&(e._store.validated=!0,a("uniqueKey",e,t))}function a(e,t,n){var o=r();if(!o){var a="string"==typeof n?n:n.displayName||n.name;a&&(o=" Check the top-level render call using <"+a+">.")}var i=h[e]||(h[e]={});if(i[o])return null;i[o]=!0;var u={parentOrOwner:o,url:" See https://fb.me/react-warning-keys for more information.",childOwner:null};return t&&t._owner&&t._owner!==p.current&&(u.childOwner=" It was passed a child from "+t._owner.getName()+"."),u}function i(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];l.isValidElement(r)&&o(r,t)}else if(l.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var a=d(e);if(a&&a!==e.entries)for(var i,u=a.call(e);!(i=u.next()).done;)l.isValidElement(i.value)&&o(i.value,t)}}function u(e,t,n,o){for(var a in t)if(t.hasOwnProperty(a)){var i;try{"function"!=typeof t[a]?f(!1):void 0,i=t[a](n,a,e,o)}catch(u){i=u}i instanceof Error&&!(i.message in v)&&(v[i.message]=!0,r())}}function s(e){var t=e.type;if("function"==typeof t){var n=t.displayName||t.name;t.propTypes&&u(n,t.propTypes,e.props,c.prop),"function"==typeof t.getDefaultProps}}var l=e(55),c=e(79),p=(e(78),e(39)),d=e(125),f=e(157),h=(e(167),{}),v={},m={createElement:function(e,t,n){var r="string"==typeof e||"function"==typeof e,o=l.createElement.apply(this,arguments);if(null==o)return o;if(r)for(var a=2;a<arguments.length;a++)i(arguments[a],e);return s(o),o},createFactory:function(e){var t=m.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=l.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)i(arguments[o],r.type);return s(r),r}};t.exports=m},{125:125,157:157,167:167,39:39,55:55,78:78,79:79}],57:[function(e,t,n){"use strict";var r,o=e(55),a=e(58),i=e(82),u=e(24),s={injectEmptyComponent:function(e){r=o.createElement(e)}},l=function(e){this._currentElement=null,this._rootNodeID=null,this._renderedComponent=e(r)};u(l.prototype,{construct:function(e){},mountComponent:function(e,t,n){return a.registerNullComponentID(e),this._rootNodeID=e,i.mountComponent(this._renderedComponent,e,t,n)},receiveComponent:function(){},unmountComponent:function(e,t,n){i.unmountComponent(this._renderedComponent),a.deregisterNullComponentID(this._rootNodeID),this._rootNodeID=null,this._renderedComponent=null}}),l.injection=s,t.exports=l},{24:24,55:55,58:58,82:82}],58:[function(e,t,n){"use strict";function r(e){return!!i[e]}function o(e){i[e]=!0}function a(e){delete i[e]}var i={},u={isNullComponentID:r,registerNullComponentID:o,deregisterNullComponentID:a};t.exports=u},{}],59:[function(e,t,n){"use strict";function r(e,t,n,r){try{return t(n,r)}catch(a){return void(null===o&&(o=a))}}var o=null,a={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};t.exports=a},{}],60:[function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=e(16),a={handleTopLevel:function(e,t,n,a,i){var u=o.extractEvents(e,t,n,a,i);r(u)}};t.exports=a},{16:16}],61:[function(e,t,n){"use strict";function r(e){var t=d.getID(e),n=p.getReactRootIDFromNodeID(t),r=d.findReactContainerForID(n),o=d.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function a(e){i(e)}function i(e){for(var t=d.getFirstReactDOM(v(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0;o<e.ancestors.length;o++){t=e.ancestors[o];var a=d.getID(t)||"";g._handleTopLevel(e.topLevelType,t,a,e.nativeEvent,v(e.nativeEvent))}}function u(e){var t=m(window);e(t)}var s=e(142),l=e(143),c=e(25),p=e(65),d=e(70),f=e(93),h=e(24),v=e(124),m=e(154);h(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),c.addPoolingTo(o,c.twoArgumentPooler);var g={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:l.canUseDOM?window:null,setHandleTopLevel:function(e){g._handleTopLevel=e},setEnabled:function(e){g._enabled=!!e},isEnabled:function(){return g._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?s.listen(r,t,g.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?s.capture(r,t,g.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=u.bind(null,e);s.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(g._enabled){var n=o.getPooled(e,t);try{f.batchedUpdates(a,n)}finally{o.release(n)}}}};t.exports=g},{124:124,142:142,143:143,154:154,24:24,25:25,65:65,70:70,93:93}],62:[function(e,t,n){"use strict";var r=e(32),o=e(55),a=e(149),i=e(157),u=(e(167),{create:function(e){if("object"!=typeof e||!e||Array.isArray(e))return e;if(o.isValidElement(e))return e;1===e.nodeType?i(!1):void 0;var t=[];for(var n in e)r.mapIntoWithKeyPrefixInternal(e[n],t,n,a.thatReturnsArgument);return t}});t.exports=u},{149:149,157:157,167:167,32:32,55:55}],63:[function(e,t,n){"use strict";var r=e(10),o=e(16),a=e(36),i=e(33),u=e(57),s=e(28),l=e(73),c=e(76),p=e(84),d=e(93),f={Component:a.injection,Class:i.injection,DOMProperty:r.injection,EmptyComponent:u.injection,EventPluginHub:o.injection,EventEmitter:s.injection,NativeComponent:l.injection,Perf:c.injection,RootIndex:p.injection,Updates:d.injection};t.exports=f},{10:10,16:16,28:28,33:33,36:36,57:57,73:73,76:76,84:84,93:93}],64:[function(e,t,n){"use strict";function r(e){return a(document.documentElement,e)}var o=e(49),a=e(146),i=e(151),u=e(152),s={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=u();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=u(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,o),i(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var a=e.createTextRange();a.collapse(!0),a.moveStart("character",n),a.moveEnd("character",r-n),a.select()}else o.setOffsets(e,t)}};t.exports=s},{146:146,151:151,152:152,49:49}],65:[function(e,t,n){"use strict";function r(e){return f+e.toString(36)}function o(e,t){return e.charAt(t)===f||t===e.length}function a(e){return""===e||e.charAt(0)===f&&e.charAt(e.length-1)!==f}function i(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function u(e){return e?e.substr(0,e.lastIndexOf(f)):""}function s(e,t){if(a(e)&&a(t)?void 0:d(!1),i(e,t)?void 0:d(!1),e===t)return e;var n,r=e.length+h;for(n=r;n<t.length&&!o(t,n);n++);return t.substr(0,n)}function l(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,i=0;n>=i;i++)if(o(e,i)&&o(t,i))r=i;else if(e.charAt(i)!==t.charAt(i))break;var u=e.substr(0,r);return a(u)?void 0:d(!1),u}function c(e,t,n,r,o,a){e=e||"",t=t||"",e===t?d(!1):void 0;var l=i(t,e);l||i(e,t)?void 0:d(!1);for(var c=0,p=l?u:s,f=e;;f=p(f,t)){var h;if(o&&f===e||a&&f===t||(h=n(f,l,r)),h===!1||f===t)break;c++<v?void 0:d(!1)}}var p=e(84),d=e(157),f=".",h=f.length,v=1e4,m={createReactRootID:function(){return r(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===f&&e.length>1){var t=e.indexOf(f,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var a=l(e,t);a!==e&&c(e,a,n,r,!1,!0),a!==t&&c(a,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseTwoPhaseSkipTarget:function(e,t,n){e&&(c("",e,t,n,!0,!0),c(e,"",t,n,!0,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},getFirstCommonAncestorID:l,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:f};t.exports=m},{157:157,84:84}],66:[function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=r},{}],67:[function(e,t,n){"use strict";var r=e(32),o=e(34),a=e(33),i=e(43),u=e(55),s=(e(56),e(80)),l=e(94),c=e(24),p=e(131),d=u.createElement,f=u.createFactory,h=u.cloneElement,v={Children:{map:r.map,forEach:r.forEach,count:r.count,toArray:r.toArray,only:p},Component:o,createElement:d,cloneElement:h,isValidElement:u.isValidElement,PropTypes:s,createClass:a.createClass,createFactory:f,createMixin:function(e){return e},DOM:i,version:l,__spread:c};t.exports=v},{131:131,24:24,32:32,33:33,34:34,43:43,55:55,56:56,80:80,94:94}],68:[function(e,t,n){"use strict";function r(e,t){this.value=e,this.requestChange=t}function o(e){var t={value:"undefined"==typeof e?a.PropTypes.any.isRequired:e.isRequired,requestChange:a.PropTypes.func.isRequired};return a.PropTypes.shape(t)}var a=e(26);r.PropTypes={link:o},t.exports=r},{26:26}],69:[function(e,t,n){"use strict";var r=e(113),o=/\/?>/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(o," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};t.exports=a},{113:113}],70:[function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===W?e.documentElement:e.firstChild:null}function a(e){var t=o(e);return t&&X.getID(t)}function i(e){var t=u(e);if(t)if(V.hasOwnProperty(t)){var n=V[t];n!==e&&(p(n,t)?L(!1):void 0,V[t]=e)}else V[t]=e;return t}function u(e){return e&&e.getAttribute&&e.getAttribute(B)||""}function s(e,t){var n=u(e);n!==t&&delete V[n],e.setAttribute(B,t),V[t]=e}function l(e){return V.hasOwnProperty(e)&&p(V[e],e)||(V[e]=X.findReactNodeByID(e)),V[e]}function c(e){var t=T.get(e)._rootNodeID;return D.isNullComponentID(t)?null:(V.hasOwnProperty(t)&&p(V[t],t)||(V[t]=X.findReactNodeByID(t)),V[t])}function p(e,t){if(e){u(e)!==t?L(!1):void 0;var n=X.findReactContainerForID(t);if(n&&O(n,e))return!0}return!1}function d(e){delete V[e]}function f(e){var t=V[e];return t&&p(t,e)?void(G=t):!1}function h(e){G=null,P.traverseAncestors(e,f);var t=G;return G=null,t}function v(e,t,n,r,o,a){_.useCreateElement&&(a=I({},a),n.nodeType===W?a[q]=n:a[q]=n.ownerDocument);var i=w.mountComponent(e,t,r,a);e._renderedComponent._topLevelWrapper=e,X._mountImageIntoNode(i,n,o,r)}function m(e,t,n,r,o){var a=R.ReactReconcileTransaction.getPooled(r);a.perform(v,null,e,t,n,a,r,o),R.ReactReconcileTransaction.release(a)}function g(e,t){for(w.unmountComponent(e),t.nodeType===W&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function y(e){var t=a(e);return t?t!==P.getReactRootIDFromNodeID(t):!1}function C(e){for(;e&&e.parentNode!==e;e=e.parentNode)if(1===e.nodeType){var t=u(e);if(t){var n,r=P.getReactRootIDFromNodeID(t),o=e;do if(n=u(o),o=o.parentNode,null==o)return null;while(n!==r);if(o===z[r])return e}}return null}var b=e(10),E=e(28),_=(e(39),e(44)),x=e(55),D=e(58),P=e(65),T=e(66),M=e(69),N=e(76),w=e(82),S=e(92),R=e(93),I=e(24),k=e(150),O=e(146),A=e(128),L=e(157),U=e(134),F=e(137),B=(e(140),e(167),b.ID_ATTRIBUTE_NAME),V={},j=1,W=9,K=11,q="__ReactMount_ownerDocument$"+Math.random().toString(36).slice(2),H={},z={},Y=[],G=null,Q=function(){};Q.prototype.isReactComponent={},Q.prototype.render=function(){return this.props};var X={TopLevelWrapper:Q,_instancesByReactRootID:H,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return X.scrollMonitor(n,function(){S.enqueueElementInternal(e,t),r&&S.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){!t||t.nodeType!==j&&t.nodeType!==W&&t.nodeType!==K?L(!1):void 0,E.ensureScrollValueMonitoring();var n=X.registerContainer(t);return H[n]=e,n},_renderNewRootComponent:function(e,t,n,r){var o=A(e,null),a=X._registerComponent(o,t);return R.batchedUpdates(m,o,a,t,n,r),o},renderSubtreeIntoContainer:function(e,t,n,r){return null==e||null==e._reactInternalInstance?L(!1):void 0,X._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){x.isValidElement(t)?void 0:L(!1);var i=new x(Q,null,null,null,null,null,t),s=H[a(n)];if(s){var l=s._currentElement,c=l.props;if(F(c,t))return X._updateRootComponent(s,i,n,r)._renderedComponent.getPublicInstance();X.unmountComponentAtNode(n)}var p=o(n),d=p&&!!u(p),f=y(n),h=d&&!s&&!f,v=X._renderNewRootComponent(i,n,h,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):k)._renderedComponent.getPublicInstance();return r&&r.call(v),v},render:function(e,t,n){return X._renderSubtreeIntoContainer(null,e,t,n)},registerContainer:function(e){var t=a(e);return t&&(t=P.getReactRootIDFromNodeID(t)),t||(t=P.createReactRootID()),z[t]=e,t},unmountComponentAtNode:function(e){!e||e.nodeType!==j&&e.nodeType!==W&&e.nodeType!==K?L(!1):void 0;var t=a(e),n=H[t];if(!n){var r=(y(e),u(e));return r&&r===P.getReactRootIDFromNodeID(r),!1}return R.batchedUpdates(g,n,e),delete H[t],delete z[t],!0},findReactContainerForID:function(e){var t=P.getReactRootIDFromNodeID(e),n=z[t];return n},findReactNodeByID:function(e){var t=X.findReactContainerForID(e);return X.findComponentRoot(t,e)},getFirstReactDOM:function(e){return C(e)},findComponentRoot:function(e,t){var n=Y,r=0,o=h(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var a,i=n[r++];i;){var u=X.getID(i);u?t===u?a=i:P.isAncestorIDOf(u,t)&&(n.length=r=0,n.push(i.firstChild)):n.push(i.firstChild),i=i.nextSibling}if(a)return n.length=0,a}n.length=0,L(!1)},_mountImageIntoNode:function(e,t,n,a){if(!t||t.nodeType!==j&&t.nodeType!==W&&t.nodeType!==K?L(!1):void 0,n){var i=o(t);if(M.canReuseMarkup(e,i))return;var u=i.getAttribute(M.CHECKSUM_ATTR_NAME);i.removeAttribute(M.CHECKSUM_ATTR_NAME);var s=i.outerHTML;i.setAttribute(M.CHECKSUM_ATTR_NAME,u);var l=e,c=r(l,s);" (client) "+l.substring(c-20,c+20)+"\n (server) "+s.substring(c-20,c+20),t.nodeType===W?L(!1):void 0}if(t.nodeType===W?L(!1):void 0,a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);t.appendChild(e)}else U(t,e)},ownerDocumentContextKey:q,getReactRootID:a,getID:i,setID:s,getNode:l,getNodeFromInstance:c,isValid:p,purgeID:d};N.measureMethods(X,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),t.exports=X},{10:10,128:128,134:134,137:137,140:140,146:146,150:150,157:157,167:167,24:24,28:28,39:39,44:44,55:55,58:58,65:65,66:66,69:69,76:76,82:82,92:92,93:93}],71:[function(e,t,n){"use strict";function r(e,t,n){m.push({parentID:e,parentNode:null,type:p.INSERT_MARKUP,markupIndex:g.push(t)-1,content:null,fromIndex:null,toIndex:n})}function o(e,t,n){m.push({parentID:e,parentNode:null,type:p.MOVE_EXISTING,markupIndex:null,content:null,fromIndex:t,toIndex:n})}function a(e,t){m.push({parentID:e,parentNode:null,type:p.REMOVE_NODE,markupIndex:null,content:null,fromIndex:t,toIndex:null})}function i(e,t){m.push({parentID:e,parentNode:null,type:p.SET_MARKUP,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function u(e,t){m.push({parentID:e,parentNode:null,type:p.TEXT_CONTENT,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function s(){m.length&&(c.processChildrenUpdates(m,g),l())}function l(){m.length=0,g.length=0}var c=e(36),p=e(72),d=(e(39),e(82)),f=e(31),h=e(119),v=0,m=[],g=[],y={Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return f.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r){var o;return o=h(t),f.updateChildren(e,o,n,r)},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],a=0;for(var i in r)if(r.hasOwnProperty(i)){var u=r[i],s=this._rootNodeID+i,l=d.mountComponent(u,s,t,n);u._mountIndex=a++,o.push(l)}return o},updateTextContent:function(e){v++;var t=!0;try{var n=this._renderedChildren;f.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChild(n[r]);this.setTextContent(e),t=!1}finally{v--,v||(t?l():s())}},updateMarkup:function(e){v++;var t=!0;try{var n=this._renderedChildren;f.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setMarkup(e),t=!1}finally{v--,v||(t?l():s())}},updateChildren:function(e,t,n){v++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{v--,v||(r?l():s())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=this._reconcilerUpdateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var a,i=0,u=0;for(a in o)if(o.hasOwnProperty(a)){var s=r&&r[a],l=o[a];s===l?(this.moveChild(s,u,i),i=Math.max(s._mountIndex,i),s._mountIndex=u):(s&&(i=Math.max(s._mountIndex,i),this._unmountChild(s)),this._mountChildByNameAtIndex(l,a,u,t,n)),u++}for(a in r)!r.hasOwnProperty(a)||o&&o.hasOwnProperty(a)||this._unmountChild(r[a])}},unmountChildren:function(){var e=this._renderedChildren;f.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){a(this._rootNodeID,e._mountIndex)},setTextContent:function(e){u(this._rootNodeID,e)},setMarkup:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var a=this._rootNodeID+t,i=d.mountComponent(e,a,r,o);e._mountIndex=n,this.createChild(e,i)},_unmountChild:function(e){this.removeChild(e),e._mountIndex=null}}};t.exports=y},{119:119,31:31,36:36,39:39,72:72,82:82}],72:[function(e,t,n){"use strict";var r=e(161),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});t.exports=o},{161:161}],73:[function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=l(t)),n}function o(e){return c?void 0:s(!1),new c(e.type,e.props)}function a(e){return new d(e)}function i(e){return e instanceof d}var u=e(24),s=e(157),l=null,c=null,p={},d=null,f={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){u(p,e)}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:a,isTextComponent:i,injection:f};t.exports=h},{157:157,24:24}],74:[function(e,t,n){"use strict";function r(e,t){}var o=(e(167),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")},enqueueSetProps:function(e,t){r(e,"setProps")},enqueueReplaceProps:function(e,t){r(e,"replaceProps")}});t.exports=o},{167:167}],75:[function(e,t,n){"use strict";var r=e(157),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};t.exports=o},{157:157}],76:[function(e,t,n){"use strict";function r(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:r,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){o.storedMeasure=e}}};t.exports=o},{}],77:[function(e,t,n){"use strict";function r(e){return function(t,n,r){t.hasOwnProperty(n)?t[n]=e(t[n],r):t[n]=r}}function o(e,t){for(var n in t)if(t.hasOwnProperty(n)){var r=l[n];r&&l.hasOwnProperty(n)?r(e,n,t[n]):e.hasOwnProperty(n)||(e[n]=t[n])}return e}var a=e(24),i=e(149),u=e(160),s=r(function(e,t){return a({},t,e)}),l={children:i,className:r(u),style:s},c={mergeProps:function(e,t){return o(a({},e),t)}};t.exports=c},{149:149,160:160,24:24}],78:[function(e,t,n){"use strict";var r={};t.exports=r},{}],79:[function(e,t,n){"use strict";var r=e(161),o=r({prop:null,context:null,childContext:null});t.exports=o},{161:161}],80:[function(e,t,n){"use strict";function r(e){function t(t,n,r,o,a,i){if(o=o||_,i=i||r,null==n[r]){var u=C[a];return t?new Error("Required "+u+" `"+i+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,a,i); }var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o,a){var i=t[n],u=v(i);if(u!==e){var s=C[o],l=m(i);return new Error("Invalid "+s+" `"+a+"` of type "+("`"+l+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return r(t)}function a(){return r(b.thatReturns(null))}function i(e){function t(t,n,r,o,a){var i=t[n];if(!Array.isArray(i)){var u=C[o],s=v(i);return new Error("Invalid "+u+" `"+a+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var l=0;l<i.length;l++){var c=e(i,l,r,o,a+"["+l+"]");if(c instanceof Error)return c}return null}return r(t)}function u(){function e(e,t,n,r,o){if(!y.isValidElement(e[t])){var a=C[r];return new Error("Invalid "+a+" `"+o+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return r(e)}function s(e){function t(t,n,r,o,a){if(!(t[n]instanceof e)){var i=C[o],u=e.name||_,s=g(t[n]);return new Error("Invalid "+i+" `"+a+"` of type "+("`"+s+"` supplied to `"+r+"`, expected ")+("instance of `"+u+"`."))}return null}return r(t)}function l(e){function t(t,n,r,o,a){for(var i=t[n],u=0;u<e.length;u++)if(i===e[u])return null;var s=C[o],l=JSON.stringify(e);return new Error("Invalid "+s+" `"+a+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+l+"."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function c(e){function t(t,n,r,o,a){var i=t[n],u=v(i);if("object"!==u){var s=C[o];return new Error("Invalid "+s+" `"+a+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an object."))}for(var l in i)if(i.hasOwnProperty(l)){var c=e(i,l,r,o,a+"."+l);if(c instanceof Error)return c}return null}return r(t)}function p(e){function t(t,n,r,o,a){for(var i=0;i<e.length;i++){var u=e[i];if(null==u(t,n,r,o,a))return null}var s=C[o];return new Error("Invalid "+s+" `"+a+"` supplied to "+("`"+r+"`."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function d(){function e(e,t,n,r,o){if(!h(e[t])){var a=C[r];return new Error("Invalid "+a+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function f(e){function t(t,n,r,o,a){var i=t[n],u=v(i);if("object"!==u){var s=C[o];return new Error("Invalid "+s+" `"+a+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `object`."))}for(var l in e){var c=e[l];if(c){var p=c(i,l,r,o,a+"."+l);if(p)return p}}return null}return r(t)}function h(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(h);if(null===e||y.isValidElement(e))return!0;var t=E(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!h(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!h(o[1]))return!1}return!0;default:return!1}}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function g(e){return e.constructor&&e.constructor.name?e.constructor.name:"<<anonymous>>"}var y=e(55),C=e(78),b=e(149),E=e(125),_="<<anonymous>>",x={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:a(),arrayOf:i,element:u(),instanceOf:s,node:d(),objectOf:c,oneOf:l,oneOfType:p,shape:f};t.exports=x},{125:125,149:149,55:55,78:78}],81:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.useCreateElement=!e&&u.useCreateElement}var o=e(6),a=e(25),i=e(28),u=e(44),s=e(64),l=e(110),c=e(24),p={initialize:s.getSelectionInformation,close:s.restoreSelection},d={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h=[p,d,f],v={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null}};c(r.prototype,l.Mixin,v),a.addPoolingTo(r),t.exports=r},{110:110,24:24,25:25,28:28,44:44,6:6,64:64}],82:[function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=e(83),a={mountComponent:function(e,t,n,o){var a=e.mountComponent(t,n,o);return e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e),a},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,a){var i=e._currentElement;if(t!==i||a!==e._context){var u=o.shouldUpdateRefs(i,t);u&&o.detachRefs(e,i),e.receiveComponent(t,n,a),u&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};t.exports=a},{83:83}],83:[function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):a.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):a.removeComponentAsRefFrom(t,e,n)}var a=e(75),i={};i.attachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&r(n,e,t._owner)}},i.shouldUpdateRefs=function(e,t){var n=null===e||e===!1,r=null===t||t===!1;return n||r||t._owner!==e._owner||t.ref!==e.ref},i.detachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&o(n,e,t._owner)}},t.exports=i},{75:75}],84:[function(e,t,n){"use strict";var r={injectCreateReactRootIndex:function(e){o.createReactRootIndex=e}},o={createReactRootIndex:null,injection:r};t.exports=o},{}],85:[function(e,t,n){"use strict";var r={isBatchingUpdates:!1,batchedUpdates:function(e){}};t.exports=r},{}],86:[function(e,t,n){"use strict";function r(e){i.isValidElement(e)?void 0:h(!1);var t;try{p.injection.injectBatchingStrategy(l);var n=u.createReactRootID();return t=c.getPooled(!1),t.perform(function(){var r=f(e,null),o=r.mountComponent(n,t,d);return s.addChecksumToMarkup(o)},null)}finally{c.release(t),p.injection.injectBatchingStrategy(a)}}function o(e){i.isValidElement(e)?void 0:h(!1);var t;try{p.injection.injectBatchingStrategy(l);var n=u.createReactRootID();return t=c.getPooled(!0),t.perform(function(){var r=f(e,null);return r.mountComponent(n,t,d)},null)}finally{c.release(t),p.injection.injectBatchingStrategy(a)}}var a=e(53),i=e(55),u=e(65),s=e(69),l=e(85),c=e(87),p=e(93),d=e(150),f=e(128),h=e(157);t.exports={renderToString:r,renderToStaticMarkup:o}},{128:128,150:150,157:157,53:53,55:55,65:65,69:69,85:85,87:87,93:93}],87:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=a.getPooled(null),this.useCreateElement=!1}var o=e(25),a=e(6),i=e(110),u=e(24),s=e(149),l={initialize:function(){this.reactMountReady.reset()},close:s},c=[l],p={getTransactionWrappers:function(){return c},getReactMountReady:function(){return this.reactMountReady},destructor:function(){a.release(this.reactMountReady),this.reactMountReady=null}};u(r.prototype,i.Mixin,p),o.addPoolingTo(r),t.exports=r},{110:110,149:149,24:24,25:25,6:6}],88:[function(e,t,n){"use strict";function r(e,t){var n={};return function(r){n[t]=r,e.setState(n)}}var o={createStateSetter:function(e,t){return function(n,r,o,a,i,u){var s=t.call(e,n,r,o,a,i,u);s&&e.setState(s)}},createStateKeySetter:function(e,t){var n=e.__keySetters||(e.__keySetters={});return n[t]||(n[t]=r(e,t))}};o.Mixin={createStateSetter:function(e){return o.createStateSetter(this,e)},createStateKeySetter:function(e){return o.createStateKeySetter(this,e)}},t.exports=o},{}],89:[function(e,t,n){"use strict";var r=e(119),o={getChildMapping:function(e){return e?r(e):e},mergeChildMappings:function(e,t){function n(n){return t.hasOwnProperty(n)?t[n]:e[n]}e=e||{},t=t||{};var r={},o=[];for(var a in e)t.hasOwnProperty(a)?o.length&&(r[a]=o,o=[]):o.push(a);var i,u={};for(var s in t){if(r.hasOwnProperty(s))for(i=0;i<r[s].length;i++){var l=r[s][i];u[r[s][i]]=n(l)}u[s]=n(s)}for(i=0;i<o.length;i++)u[o[i]]=n(o[i]);return u}};t.exports=o},{119:119}],90:[function(e,t,n){"use strict";function r(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete u.animationend.animation,"TransitionEvent"in window||delete u.transitionend.transition;for(var n in u){var r=u[n];for(var o in r)if(o in t){s.push(r[o]);break}}}function o(e,t,n){e.addEventListener(t,n,!1)}function a(e,t,n){e.removeEventListener(t,n,!1)}var i=e(143),u={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},s=[];i.canUseDOM&&r();var l={addEndEventListener:function(e,t){return 0===s.length?void window.setTimeout(t,0):void s.forEach(function(n){o(e,n,t)})},removeEndEventListener:function(e,t){0!==s.length&&s.forEach(function(n){a(e,n,t)})}};t.exports=l},{143:143}],91:[function(e,t,n){"use strict";var r=e(26),o=e(89),a=e(24),i=e(149),u=r.createClass({displayName:"ReactTransitionGroup",propTypes:{component:r.PropTypes.any,childFactory:r.PropTypes.func},getDefaultProps:function(){return{component:"span",childFactory:i.thatReturnsArgument}},getInitialState:function(){return{children:o.getChildMapping(this.props.children)}},componentWillMount:function(){this.currentlyTransitioningKeys={},this.keysToEnter=[],this.keysToLeave=[]},componentDidMount:function(){var e=this.state.children;for(var t in e)e[t]&&this.performAppear(t)},componentWillReceiveProps:function(e){var t=o.getChildMapping(e.children),n=this.state.children;this.setState({children:o.mergeChildMappings(n,t)});var r;for(r in t){var a=n&&n.hasOwnProperty(r);!t[r]||a||this.currentlyTransitioningKeys[r]||this.keysToEnter.push(r)}for(r in n){var i=t&&t.hasOwnProperty(r);!n[r]||i||this.currentlyTransitioningKeys[r]||this.keysToLeave.push(r)}},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performAppear:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillAppear?t.componentWillAppear(this._handleDoneAppearing.bind(this,e)):this._handleDoneAppearing(e)},_handleDoneAppearing:function(e){var t=this.refs[e];t.componentDidAppear&&t.componentDidAppear(),delete this.currentlyTransitioningKeys[e];var n=o.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performEnter:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillEnter?t.componentWillEnter(this._handleDoneEntering.bind(this,e)):this._handleDoneEntering(e)},_handleDoneEntering:function(e){var t=this.refs[e];t.componentDidEnter&&t.componentDidEnter(),delete this.currentlyTransitioningKeys[e];var n=o.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performLeave:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillLeave?t.componentWillLeave(this._handleDoneLeaving.bind(this,e)):this._handleDoneLeaving(e)},_handleDoneLeaving:function(e){var t=this.refs[e];t.componentDidLeave&&t.componentDidLeave(),delete this.currentlyTransitioningKeys[e];var n=o.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)?this.performEnter(e):this.setState(function(t){var n=a({},t.children);return delete n[e],{children:n}})},render:function(){var e=[];for(var t in this.state.children){var n=this.state.children[t];n&&e.push(r.cloneElement(this.props.childFactory(n),{ref:t,key:t}))}return r.createElement(this.props.component,this.props,e)}});t.exports=u},{149:149,24:24,26:26,89:89}],92:[function(e,t,n){"use strict";function r(e){u.enqueueUpdate(e)}function o(e,t){var n=i.get(e);return n?n:null}var a=(e(39),e(55)),i=e(66),u=e(93),s=e(24),l=e(157),c=(e(167),{isMounted:function(e){var t=i.get(e);return t?!!t._renderedComponent:!1},enqueueCallback:function(e,t){"function"!=typeof t?l(!1):void 0;var n=o(e);return n?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){"function"!=typeof t?l(!1):void 0,e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var a=n._pendingStateQueue||(n._pendingStateQueue=[]);a.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");n&&c.enqueueSetPropsInternal(n,t)},enqueueSetPropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:l(!1);var o=n._pendingElement||n._currentElement,i=o.props,u=s({},i.props,t);n._pendingElement=a.cloneAndReplaceProps(o,a.cloneAndReplaceProps(i,u)),r(n)},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");n&&c.enqueueReplacePropsInternal(n,t)},enqueueReplacePropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:l(!1);var o=n._pendingElement||n._currentElement,i=o.props;n._pendingElement=a.cloneAndReplaceProps(o,a.cloneAndReplaceProps(i,t)),r(n)},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});t.exports=c},{157:157,167:167,24:24,39:39,55:55,66:66,93:93}],93:[function(e,t,n){"use strict";function r(){T.ReactReconcileTransaction&&b?void 0:m(!1)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=T.ReactReconcileTransaction.getPooled(!1)}function a(e,t,n,o,a,i){r(),b.batchedUpdates(e,t,n,o,a,i)}function i(e,t){return e._mountOrder-t._mountOrder}function u(e){var t=e.dirtyComponentsLength;t!==g.length?m(!1):void 0,g.sort(i);for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,f.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var a=0;a<o.length;a++)e.callbackQueue.enqueue(o[a],r.getPublicInstance())}}function s(e){return r(),b.isBatchingUpdates?void g.push(e):void b.batchedUpdates(s,e)}function l(e,t){b.isBatchingUpdates?void 0:m(!1),y.enqueue(e,t),C=!0}var c=e(6),p=e(25),d=e(76),f=e(82),h=e(110),v=e(24),m=e(157),g=[],y=c.getPooled(),C=!1,b=null,E={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),D()):g.length=0}},_={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},x=[E,_];v(o.prototype,h.Mixin,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,T.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return h.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var D=function(){for(;g.length||C;){if(g.length){var e=o.getPooled();e.perform(u,null,e),o.release(e)}if(C){C=!1;var t=y;y=c.getPooled(),t.notifyAll(),c.release(t)}}};D=d.measure("ReactUpdates","flushBatchedUpdates",D);var P={injectReconcileTransaction:function(e){e?void 0:m(!1),T.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:m(!1),"function"!=typeof e.batchedUpdates?m(!1):void 0,"boolean"!=typeof e.isBatchingUpdates?m(!1):void 0,b=e}},T={ReactReconcileTransaction:null,batchedUpdates:a,enqueueUpdate:s,flushBatchedUpdates:D,injection:P,asap:l};t.exports=T},{110:110,157:157,24:24,25:25,6:6,76:76,82:82}],94:[function(e,t,n){"use strict";t.exports="0.14.0"},{}],95:[function(e,t,n){"use strict";var r=e(10),o=r.injection.MUST_USE_ATTRIBUTE,a={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},i={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,xlinkActuate:o,xlinkArcrole:o,xlinkHref:o,xlinkRole:o,xlinkShow:o,xlinkTitle:o,xlinkType:o,xmlBase:o,xmlLang:o,xmlSpace:o,y1:o,y2:o,y:o},DOMAttributeNamespaces:{xlinkActuate:a.xlink,xlinkArcrole:a.xlink,xlinkHref:a.xlink,xlinkRole:a.xlink,xlinkShow:a.xlink,xlinkTitle:a.xlink,xlinkType:a.xlink,xmlBase:a.xml,xmlLang:a.xml,xmlSpace:a.xml},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xml:space"}};t.exports=i},{10:10}],96:[function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&s.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(b||null==g||g!==c())return null;var n=r(g);if(!C||!f(C,n)){C=n;var o=l.getPooled(m.select,y,e,t);return o.type="select",o.target=g,i.accumulateTwoPhaseDispatches(o),o}return null}var a=e(15),i=e(19),u=e(143),s=e(64),l=e(102),c=e(152),p=e(130),d=e(162),f=e(165),h=a.topLevelTypes,v=u.canUseDOM&&"documentMode"in document&&document.documentMode<=11,m={select:{phasedRegistrationNames:{bubbled:d({onSelect:null}),captured:d({onSelectCapture:null})},dependencies:[h.topBlur,h.topContextMenu,h.topFocus,h.topKeyDown,h.topMouseDown,h.topMouseUp,h.topSelectionChange]}},g=null,y=null,C=null,b=!1,E=!1,_=d({onSelect:null}),x={eventTypes:m,extractEvents:function(e,t,n,r,a){if(!E)return null;switch(e){case h.topFocus:(p(t)||"true"===t.contentEditable)&&(g=t,y=n,C=null);break;case h.topBlur:g=null,y=null,C=null;break;case h.topMouseDown:b=!0;break;case h.topContextMenu:case h.topMouseUp:return b=!1,o(r,a);case h.topSelectionChange:if(v)break;case h.topKeyDown:case h.topKeyUp:return o(r,a)}return null},didPutListener:function(e,t,n){t===_&&(E=!0)}};t.exports=x},{102:102,130:130,143:143,15:15,152:152,162:162,165:165,19:19,64:64}],97:[function(e,t,n){"use strict";var r=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*r)}};t.exports=o},{}],98:[function(e,t,n){"use strict";var r=e(15),o=e(142),a=e(19),i=e(70),u=e(99),s=e(102),l=e(103),c=e(105),p=e(106),d=e(101),f=e(107),h=e(108),v=e(109),m=e(149),g=e(121),y=e(157),C=e(162),b=r.topLevelTypes,E={abort:{phasedRegistrationNames:{bubbled:C({onAbort:!0}),captured:C({onAbortCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:C({onBlur:!0}),captured:C({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:C({onCanPlay:!0}),captured:C({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:C({onCanPlayThrough:!0}),captured:C({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:C({onClick:!0}),captured:C({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:C({onContextMenu:!0}),captured:C({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:C({onCopy:!0}),captured:C({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:C({onCut:!0}),captured:C({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:C({onDoubleClick:!0}),captured:C({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:C({onDrag:!0}),captured:C({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:C({onDragEnd:!0}),captured:C({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:C({onDragEnter:!0}),captured:C({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:C({onDragExit:!0}),captured:C({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:C({onDragLeave:!0}),captured:C({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:C({onDragOver:!0}),captured:C({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:C({onDragStart:!0}),captured:C({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:C({onDrop:!0}),captured:C({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:C({onDurationChange:!0}),captured:C({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:C({onEmptied:!0}),captured:C({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:C({onEncrypted:!0}),captured:C({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:C({onEnded:!0}),captured:C({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:C({onError:!0}),captured:C({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:C({onFocus:!0}),captured:C({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:C({onInput:!0}),captured:C({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:C({onKeyDown:!0}),captured:C({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:C({onKeyPress:!0}),captured:C({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:C({onKeyUp:!0}),captured:C({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:C({onLoad:!0}),captured:C({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:C({onLoadedData:!0}),captured:C({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:C({onLoadedMetadata:!0}),captured:C({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:C({onLoadStart:!0}),captured:C({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:C({onMouseDown:!0}),captured:C({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:C({onMouseMove:!0}),captured:C({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:C({onMouseOut:!0}),captured:C({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:C({onMouseOver:!0}),captured:C({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:C({onMouseUp:!0}),captured:C({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:C({onPaste:!0}),captured:C({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:C({onPause:!0}),captured:C({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:C({onPlay:!0}),captured:C({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:C({onPlaying:!0}),captured:C({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:C({onProgress:!0}),captured:C({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:C({onRateChange:!0}),captured:C({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:C({onReset:!0}),captured:C({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:C({onScroll:!0}),captured:C({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:C({onSeeked:!0}),captured:C({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:C({onSeeking:!0}),captured:C({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:C({onStalled:!0}),captured:C({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:C({onSubmit:!0}),captured:C({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:C({onSuspend:!0}),captured:C({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:C({onTimeUpdate:!0}),captured:C({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:C({onTouchCancel:!0}),captured:C({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:C({onTouchEnd:!0}),captured:C({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:C({onTouchMove:!0}),captured:C({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:C({onTouchStart:!0}),captured:C({onTouchStartCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:C({onVolumeChange:!0}),captured:C({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:C({onWaiting:!0}),captured:C({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:C({onWheel:!0}),captured:C({onWheelCapture:!0})}}},_={topAbort:E.abort,topBlur:E.blur,topCanPlay:E.canPlay,topCanPlayThrough:E.canPlayThrough,topClick:E.click,topContextMenu:E.contextMenu,topCopy:E.copy,topCut:E.cut,topDoubleClick:E.doubleClick,topDrag:E.drag,topDragEnd:E.dragEnd,topDragEnter:E.dragEnter,topDragExit:E.dragExit,topDragLeave:E.dragLeave,topDragOver:E.dragOver,topDragStart:E.dragStart,topDrop:E.drop,topDurationChange:E.durationChange,topEmptied:E.emptied,topEncrypted:E.encrypted,topEnded:E.ended,topError:E.error,topFocus:E.focus,topInput:E.input,topKeyDown:E.keyDown,topKeyPress:E.keyPress,topKeyUp:E.keyUp,topLoad:E.load,topLoadedData:E.loadedData,topLoadedMetadata:E.loadedMetadata,topLoadStart:E.loadStart,topMouseDown:E.mouseDown,topMouseMove:E.mouseMove,topMouseOut:E.mouseOut,topMouseOver:E.mouseOver,topMouseUp:E.mouseUp,topPaste:E.paste,topPause:E.pause,topPlay:E.play,topPlaying:E.playing,topProgress:E.progress,topRateChange:E.rateChange,topReset:E.reset,topScroll:E.scroll,topSeeked:E.seeked,topSeeking:E.seeking,topStalled:E.stalled,topSubmit:E.submit,topSuspend:E.suspend,topTimeUpdate:E.timeUpdate,topTouchCancel:E.touchCancel,topTouchEnd:E.touchEnd,topTouchMove:E.touchMove,topTouchStart:E.touchStart,topVolumeChange:E.volumeChange,topWaiting:E.waiting,topWheel:E.wheel};for(var x in _)_[x].dependencies=[x];var D=C({onClick:null}),P={},T={eventTypes:E,extractEvents:function(e,t,n,r,o){var i=_[e];if(!i)return null;var m;switch(e){case b.topAbort:case b.topCanPlay:case b.topCanPlayThrough:case b.topDurationChange:case b.topEmptied:case b.topEncrypted:case b.topEnded:case b.topError:case b.topInput:case b.topLoad:case b.topLoadedData:case b.topLoadedMetadata:case b.topLoadStart:case b.topPause:case b.topPlay:case b.topPlaying:case b.topProgress:case b.topRateChange:case b.topReset:case b.topSeeked:case b.topSeeking:case b.topStalled:case b.topSubmit:case b.topSuspend:case b.topTimeUpdate:case b.topVolumeChange:case b.topWaiting:m=s;break;case b.topKeyPress:if(0===g(r))return null;case b.topKeyDown:case b.topKeyUp:m=c;break;case b.topBlur:case b.topFocus:m=l;break;case b.topClick:if(2===r.button)return null;case b.topContextMenu:case b.topDoubleClick:case b.topMouseDown:case b.topMouseMove:case b.topMouseOut:case b.topMouseOver:case b.topMouseUp:m=p;break;case b.topDrag:case b.topDragEnd:case b.topDragEnter:case b.topDragExit:case b.topDragLeave:case b.topDragOver:case b.topDragStart:case b.topDrop:m=d;break;case b.topTouchCancel:case b.topTouchEnd:case b.topTouchMove:case b.topTouchStart:m=f;break;case b.topScroll:m=h;break;case b.topWheel:m=v;break;case b.topCopy:case b.topCut:case b.topPaste:m=u}m?void 0:y(!1);var C=m.getPooled(i,n,r,o);return a.accumulateTwoPhaseDispatches(C),C},didPutListener:function(e,t,n){if(t===D){var r=i.getNode(e);P[e]||(P[e]=o.listen(r,"click",m))}},willDeleteListener:function(e,t){t===D&&(P[e].remove(),delete P[e])}};t.exports=T},{101:101,102:102,103:103,105:105,106:106,107:107,108:108,109:109,121:121,142:142,149:149,15:15,157:157,162:162,19:19,70:70,99:99}],99:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(102),a={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,a),t.exports=r},{102:102}],100:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(102),a={data:null};o.augmentClass(r,a),t.exports=r},{102:102}],101:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(106),a={dataTransfer:null};o.augmentClass(r,a),t.exports=r},{106:106}],102:[function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n,this.target=r,this.currentTarget=r;var o=this.constructor.Interface;for(var a in o)if(o.hasOwnProperty(a)){var u=o[a];u?this[a]=u(n):this[a]=n[a]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;s?this.isDefaultPrevented=i.thatReturnsTrue:this.isDefaultPrevented=i.thatReturnsFalse,this.isPropagationStopped=i.thatReturnsFalse}var o=e(25),a=e(24),i=e(149),u=(e(167),{type:null,currentTarget:i.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null});a(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=i.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=i.thatReturnsTrue)},persist:function(){this.isPersistent=i.thatReturnsTrue},isPersistent:i.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=u,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);a(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=a({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.fourArgumentPooler)},o.addPoolingTo(r,o.fourArgumentPooler),t.exports=r},{149:149,167:167,24:24,25:25}],103:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(108),a={relatedTarget:null};o.augmentClass(r,a),t.exports=r},{108:108}],104:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(102),a={data:null};o.augmentClass(r,a),t.exports=r},{102:102}],105:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(108),a=e(121),i=e(122),u=e(123),s={key:i,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:u,charCode:function(e){return"keypress"===e.type?a(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?a(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,s),t.exports=r},{108:108,121:121,122:122,123:123}],106:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(108),a=e(111),i=e(123),u={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:i,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+a.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+a.currentScrollTop}};o.augmentClass(r,u),t.exports=r},{108:108,111:111,123:123}],107:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(108),a=e(123),i={touches:null,targetTouches:null,changedTouches:null,altKey:null, metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:a};o.augmentClass(r,i),t.exports=r},{108:108,123:123}],108:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(102),a=e(124),i={view:function(e){if(e.view)return e.view;var t=a(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,i),t.exports=r},{102:102,124:124}],109:[function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=e(106),a={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,a),t.exports=r},{106:106}],110:[function(e,t,n){"use strict";var r=e(157),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,a,i,u,s){this.isInTransaction()?r(!1):void 0;var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=e.call(t,n,o,a,i,u,s),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=a.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===a.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){this.isInTransaction()?void 0:r(!1);for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,i=t[n],u=this.wrapperInitData[n];try{o=!0,u!==a.OBSERVED_ERROR&&i.close&&i.close.call(this,u),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(s){}}}this.wrapperInitData.length=0}},a={Mixin:o,OBSERVED_ERROR:{}};t.exports=a},{157:157}],111:[function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{}],112:[function(e,t,n){"use strict";function r(e,t){if(null==t?o(!1):void 0,null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=e(157);t.exports=r},{157:157}],113:[function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0,a=e.length,i=-4&a;i>r;){for(;r<Math.min(r+4096,i);r+=4)n+=(t+=e.charCodeAt(r))+(t+=e.charCodeAt(r+1))+(t+=e.charCodeAt(r+2))+(t+=e.charCodeAt(r+3));t%=o,n%=o}for(;a>r;r++)n+=t+=e.charCodeAt(r);return t%=o,n%=o,t|n<<16}var o=65521;t.exports=r},{}],114:[function(e,t,n){"use strict";function r(e,t){var n=a.mergeProps(t,e.props);return!n.hasOwnProperty(u)&&e.props.hasOwnProperty(u)&&(n.children=e.props.children),o.createElement(e.type,n)}var o=e(55),a=e(77),i=e(162),u=(e(167),i({children:null}));t.exports=r},{162:162,167:167,55:55,77:77}],115:[function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||a.hasOwnProperty(e)&&a[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=e(4),a=o.isUnitlessNumber;t.exports=r},{4:4}],116:[function(e,t,n){"use strict";function r(e,t,n,r,o){return o}e(24),e(167);t.exports=r},{167:167,24:24}],117:[function(e,t,n){"use strict";function r(e){return a[e]}function o(e){return(""+e).replace(i,r)}var a={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},i=/[&><"']/g;t.exports=o},{}],118:[function(e,t,n){"use strict";function r(e){return null==e?null:1===e.nodeType?e:o.has(e)?a.getNodeFromInstance(e):(null!=e.render&&"function"==typeof e.render?i(!1):void 0,void i(!1))}var o=(e(39),e(66)),a=e(70),i=e(157);e(167);t.exports=r},{157:157,167:167,39:39,66:66,70:70}],119:[function(e,t,n){"use strict";function r(e,t,n){var r=e,o=void 0===r[n];o&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return a(e,r,t),t}var a=e(138);e(167);t.exports=o},{138:138,167:167}],120:[function(e,t,n){"use strict";var r=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=r},{}],121:[function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=r},{}],122:[function(e,t,n){"use strict";function r(e){if(e.key){var t=a[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":""}var o=e(121),a={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},i={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=r},{121:121}],123:[function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=a[e];return r?!!n[r]:!1}function o(e){return r}var a={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=o},{}],124:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=r},{}],125:[function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[a]);return"function"==typeof t?t:void 0}var o="function"==typeof Symbol&&Symbol.iterator,a="@@iterator";t.exports=r},{}],126:[function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function a(e,t){for(var n=r(e),a=0,i=0;n;){if(3===n.nodeType){if(i=a+n.textContent.length,t>=a&&i>=t)return{node:n,offset:t-a};a=i}n=r(o(n))}}t.exports=a},{}],127:[function(e,t,n){"use strict";function r(){return!a&&o.canUseDOM&&(a="textContent"in document.documentElement?"textContent":"innerText"),a}var o=e(143),a=null;t.exports=r},{143:143}],128:[function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e){var t;if(null===e||e===!1)t=new i(o);else if("object"==typeof e){var n=e;!n||"function"!=typeof n.type&&"string"!=typeof n.type?l(!1):void 0,t="string"==typeof n.type?u.createInternalComponent(n):r(n.type)?new n.type(n):new c}else"string"==typeof e||"number"==typeof e?t=u.createInstanceForText(e):l(!1);return t.construct(e),t._mountIndex=0,t._mountImage=null,t}var a=e(38),i=e(57),u=e(73),s=e(24),l=e(157),c=(e(167),function(){});s(c.prototype,a.Mixin,{_instantiateReactComponent:o}),t.exports=o},{157:157,167:167,24:24,38:38,57:57,73:73}],129:[function(e,t,n){"use strict";function r(e,t){if(!a.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var i=document.createElement("div");i.setAttribute(n,"return;"),r="function"==typeof i[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,a=e(143);a.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{143:143}],130:[function(e,t,n){"use strict";function r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&o[e.type]||"textarea"===t)}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=r},{}],131:[function(e,t,n){"use strict";function r(e){return o.isValidElement(e)?void 0:a(!1),e}var o=e(55),a=e(157);t.exports=r},{157:157,55:55}],132:[function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=e(117);t.exports=r},{117:117}],133:[function(e,t,n){"use strict";var r=e(70);t.exports=r.renderSubtreeIntoContainer},{70:70}],134:[function(e,t,n){"use strict";var r=e(143),o=/^[ \r\n\t\f]/,a=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,i=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(i=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var u=document.createElement("div");u.innerHTML=" ",""===u.innerHTML&&(i=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&a.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=i},{143:143}],135:[function(e,t,n){"use strict";var r=e(143),o=e(117),a=e(134),i=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(i=function(e,t){a(e,o(t))})),t.exports=i},{117:117,134:134,143:143}],136:[function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=e(165);t.exports=r},{165:165}],137:[function(e,t,n){"use strict";function r(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,a=typeof t;return"string"===o||"number"===o?"string"===a||"number"===a:"object"===a&&e.type===t.type&&e.key===t.key}t.exports=r},{}],138:[function(e,t,n){"use strict";function r(e){return v[e]}function o(e,t){return e&&null!=e.key?i(e.key):t.toString(36)}function a(e){return(""+e).replace(m,r)}function i(e){return"$"+a(e)}function u(e,t,n,r){var a=typeof e;if(("undefined"===a||"boolean"===a)&&(e=null),null===e||"string"===a||"number"===a||l.isValidElement(e))return n(r,e,""===t?f+o(e,0):t),1;var s,c,v=0,m=""===t?f:t+h;if(Array.isArray(e))for(var g=0;g<e.length;g++)s=e[g],c=m+o(s,g),v+=u(s,c,n,r);else{var y=p(e);if(y){var C,b=y.call(e);if(y!==e.entries)for(var E=0;!(C=b.next()).done;)s=C.value,c=m+o(s,E++),v+=u(s,c,n,r);else for(;!(C=b.next()).done;){var _=C.value;_&&(s=_[1],c=m+i(_[0])+h+o(s,0),v+=u(s,c,n,r))}}else"object"===a&&(String(e),d(!1))}return v}function s(e,t,n){return null==e?0:u(e,"",t,n)}var l=(e(39),e(55)),c=e(65),p=e(125),d=e(157),f=(e(167),c.SEPARATOR),h=":",v={"=":"=0",".":"=1",":":"=2"},m=/[=.:]/g;t.exports=s},{125:125,157:157,167:167,39:39,55:55,65:65}],139:[function(e,t,n){"use strict";function r(e){return Array.isArray(e)?e.concat():e&&"object"==typeof e?i(new e.constructor,e):e}function o(e,t,n){Array.isArray(e)?void 0:s(!1);var r=t[n];Array.isArray(r)?void 0:s(!1)}function a(e,t){if("object"!=typeof t?s(!1):void 0,l.call(t,f))return 1!==Object.keys(t).length?s(!1):void 0,t[f];var n=r(e);if(l.call(t,h)){var u=t[h];u&&"object"==typeof u?void 0:s(!1),n&&"object"==typeof n?void 0:s(!1),i(n,t[h])}l.call(t,c)&&(o(e,t,c),t[c].forEach(function(e){n.push(e)})),l.call(t,p)&&(o(e,t,p),t[p].forEach(function(e){n.unshift(e)})),l.call(t,d)&&(Array.isArray(e)?void 0:s(!1),Array.isArray(t[d])?void 0:s(!1),t[d].forEach(function(e){Array.isArray(e)?void 0:s(!1),n.splice.apply(n,e)})),l.call(t,v)&&("function"!=typeof t[v]?s(!1):void 0,n=t[v](n));for(var m in t)g.hasOwnProperty(m)&&g[m]||(n[m]=a(e[m],t[m]));return n}var i=e(24),u=e(162),s=e(157),l={}.hasOwnProperty,c=u({$push:null}),p=u({$unshift:null}),d=u({$splice:null}),f=u({$set:null}),h=u({$merge:null}),v=u({$apply:null}),m=[c,p,d,f,h,v],g={};m.forEach(function(e){g[e]=!0}),t.exports=a},{157:157,162:162,24:24}],140:[function(e,t,n){"use strict";var r=(e(24),e(149)),o=(e(167),r);t.exports=o},{149:149,167:167,24:24}],141:[function(e,t,n){"use strict";var r=e(157),o={addClass:function(e,t){return/\s/.test(t)?r(!1):void 0,t&&(e.classList?e.classList.add(t):o.hasClass(e,t)||(e.className=e.className+" "+t)),e},removeClass:function(e,t){return/\s/.test(t)?r(!1):void 0,t&&(e.classList?e.classList.remove(t):o.hasClass(e,t)&&(e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),e},conditionClass:function(e,t,n){return(n?o.addClass:o.removeClass)(e,t)},hasClass:function(e,t){return/\s/.test(t)?r(!1):void 0,e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")>-1}};t.exports=o},{157:157}],142:[function(e,t,n){"use strict";var r=e(149),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};t.exports=o},{149:149}],143:[function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};t.exports=o},{}],144:[function(e,t,n){"use strict";function r(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;t.exports=r},{}],145:[function(e,t,n){"use strict";function r(e){return o(e.replace(a,"ms-"))}var o=e(144),a=/^-ms-/;t.exports=r},{144:144}],146:[function(e,t,n){"use strict";function r(e,t){var n=!0;e:for(;n;){var r=e,a=t;if(n=!1,r&&a){if(r===a)return!0;if(o(r))return!1;if(o(a)){e=r,t=a.parentNode,n=!0;continue e}return r.contains?r.contains(a):r.compareDocumentPosition?!!(16&r.compareDocumentPosition(a)):!1}return!1}}var o=e(159);t.exports=r},{159:159}],147:[function(e,t,n){"use strict";function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return r(e)?Array.isArray(e)?e.slice():a(e):[e]}var a=e(166);t.exports=o},{166:166}],148:[function(e,t,n){"use strict";function r(e){var t=e.match(c);return t&&t[1].toLowerCase()}function o(e,t){var n=l;l?void 0:s(!1);var o=r(e),a=o&&u(o);if(a){n.innerHTML=a[1]+e+a[2];for(var c=a[0];c--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(t?void 0:s(!1),i(p).forEach(t));for(var d=i(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return d}var a=e(143),i=e(147),u=e(153),s=e(157),l=a.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=o},{143:143,147:147,153:153,157:157}],149:[function(e,t,n){"use strict";function r(e){return function(){return e}}function o(){}o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},t.exports=o},{}],150:[function(e,t,n){"use strict";var r={};t.exports=r},{}],151:[function(e,t,n){"use strict";function r(e){try{e.focus()}catch(t){}}t.exports=r},{}],152:[function(e,t,n){"use strict";function r(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=r},{}],153:[function(e,t,n){"use strict";function r(e){return i?void 0:a(!1),d.hasOwnProperty(e)||(e="*"),u.hasOwnProperty(e)||("*"===e?i.innerHTML="<link />":i.innerHTML="<"+e+"></"+e+">",u[e]=!i.firstChild),u[e]?d[e]:null}var o=e(143),a=e(157),i=o.canUseDOM?document.createElement("div"):null,u={},s=[1,'<select multiple="true">',"</select>"],l=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],d={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c},f=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];f.forEach(function(e){d[e]=p,u[e]=!0}),t.exports=r},{143:143,157:157}],154:[function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=r},{}],155:[function(e,t,n){"use strict";function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;t.exports=r},{}],156:[function(e,t,n){"use strict";function r(e){return o(e).replace(a,"-ms-")}var o=e(155),a=/^ms-/;t.exports=r},{155:155}],157:[function(e,t,n){"use strict";var r=function(e,t,n,r,o,a,i,u){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,a,i,u],c=0;s=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return l[c++]}))}throw s.framesToPop=1,s}};t.exports=r},{}],158:[function(e,t,n){"use strict";function r(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=r},{}],159:[function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=e(158);t.exports=r},{158:158}],160:[function(e,t,n){"use strict";function r(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e=(e?e+" ":"")+t);return e}t.exports=r},{}],161:[function(e,t,n){"use strict";var r=e(157),o=function(e){var t,n={};e instanceof Object&&!Array.isArray(e)?void 0:r(!1);for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};t.exports=o},{157:157}],162:[function(e,t,n){"use strict";var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=r},{}],163:[function(e,t,n){"use strict";function r(e,t,n){if(!e)return null;var r={};for(var a in e)o.call(e,a)&&(r[a]=t.call(n,e[a],a,e));return r}var o=Object.prototype.hasOwnProperty;t.exports=r},{}],164:[function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=r},{}],165:[function(e,t,n){"use strict";function r(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var a=o.bind(t),i=0;i<n.length;i++)if(!a(n[i])||e[n[i]]!==t[n[i]])return!1;return!0}var o=Object.prototype.hasOwnProperty;t.exports=r},{}],166:[function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?o(!1):void 0,"number"!=typeof t?o(!1):void 0,0===t||t-1 in e?void 0:o(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),a=0;t>a;a++)r[a]=e[a];return r}var o=e(157);t.exports=r},{157:157}],167:[function(e,t,n){"use strict";var r=e(149),o=r;t.exports=o},{149:149}]},{},[1])(1)}); /** * ReactDOM v0.14.0 * * 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. * */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e(require("react"));else if("function"==typeof define&&define.amd)define(["react"],e);else{var f;f="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,f.ReactDOM=e(f.React)}}(function(e){return e.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED});
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getPropValue; exports.getLiteralPropValue = getLiteralPropValue; var _values = require('./values'); var _values2 = _interopRequireDefault(_values); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var extractValue = function extractValue(attribute, extractor) { if (attribute && attribute.type === 'JSXAttribute') { if (attribute.value === null) { // Null valued attributes imply truthiness. // For example: <div aria-hidden /> // See: https://facebook.github.io/react/docs/jsx-in-depth.html#boolean-attributes return true; } return extractor(attribute.value); } return undefined; }; /** * Returns the value of a given attribute. * Different types of attributes have their associated * values in different properties on the object. * * This function should return the most *closely* associated * value with the intention of the JSX. * * @param attribute - The JSXAttribute collected by AST parser. */ function getPropValue(attribute) { return extractValue(attribute, _values2.default); } /** * Returns the value of a given attribute. * Different types of attributes have their associated * values in different properties on the object. * * This function should return a value only if we can extract * a literal value from its attribute (i.e. values that have generic * types in JavaScript - strings, numbers, booleans, etc.) * * @param attribute - The JSXAttribute collected by AST parser. */ function getLiteralPropValue(attribute) { return extractValue(attribute, _values.getLiteralValue); }
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v3.0.7 (2013-10-24) * * (c) 2009-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch = doc.documentElement.ontouchstart !== UNDEFINED, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () {}, charts = [], PRODUCT = 'Highcharts', VERSION = '3.0.7', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', /* * Empirical lowest possible opacities for TRACKER_FILL * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable //TRACKER_FILL = 'rgba(192,192,192,0.5)', NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', MILLISECOND = 'millisecond', SECOND = 'second', MINUTE = 'minute', HOUR = 'hour', DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', // constants for attributes LINEAR_GRADIENT = 'linearGradient', STOPS = 'stops', STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used makeTime, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}; // The Highcharts namespace win.Highcharts = win.Highcharts ? error(16, true) : {}; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Deep merge two or more objects and return a third object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, len = arguments.length, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // For each argument, extend the return for (i = 0; i < len; i++) { ret = doCopy(ret, arguments[i]); } return ret; } /** * Take an array and turn into a hash with even number arguments as keys and odd numbers as * values. Allows creating constants for commonly used style properties, attributes etc. * Avoid it in performance critical situations like looping */ function hash() { var i = 0, args = arguments, length = args.length, obj = {}; for (; i < length; i++) { obj[args[i++]] = args[i]; } return obj; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, setAttribute = 'setAttribute', ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem[setAttribute](prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem[setAttribute](key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof arg !== 'undefined' && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE) { if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () {}; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? (n.toString().split('.')[1] || '').length : // preserve decimals (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; val = numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, options) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (options && options.allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ function normalizeTimeTickInterval(tickInterval, unitsOption) { var units = unitsOption || [[ MILLISECOND, // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ SECOND, [1, 2, 5, 10, 15, 30] ], [ MINUTE, [1, 2, 5, 10, 15, 30] ], [ HOUR, [1, 2, 3, 4, 6, 8, 12] ], [ DAY, [1, 2] ], [ WEEK, [1, 2] ], [ MONTH, [1, 2, 3, 4, 6] ], [ YEAR, null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === YEAR ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; } /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ function getTimeTicks(normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits[SECOND]) { // second minDate.setMilliseconds(0); minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits[MINUTE]) { // minute minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits[HOUR]) { // hour minDate[setHours](interval >= timeUnits[DAY] ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits[DAY]) { // day minDate[setDate](interval >= timeUnits[MONTH] ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits[MONTH]) { // month minDate[setMonth](interval >= timeUnits[YEAR] ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits[YEAR]) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits[WEEK]) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), timezoneOffset = useUTC ? 0 : (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits[YEAR]) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits[MONTH]) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits[DAY] ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset; }), function (time) { higherRanks[time] = DAY; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; } /** * Helper class that contains variuos counters that are local to the chart. */ function ChartCounters() { this.color = 0; this.symbol = 0; } ChartCounters.prototype = { /** * Wraps the color counter if it reaches the specified length. */ wrapColor: function (length) { if (this.color >= length) { this.color = 0; } }, /** * Wraps the symbol counter if it reaches the specified length. */ wrapSymbol: function (length) { if (this.symbol >= length) { this.symbol = 0; } } }; /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } else if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ /*jslint white: true*/ timeUnits = hash( MILLISECOND, 1, SECOND, 1000, MINUTE, 60000, HOUR, 3600000, DAY, 24 * 3600000, WEEK, 7 * 24 * 3600000, MONTH, 31 * 24 * 3600000, YEAR, 31556952000 ); /*jslint white: false*/ /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx, Step = Fx.step, dSetter, Tween = $.Tween, propHooks = Tween && Tween.propHooks, opacityHook = $.cssHooks.opacity; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Step, base, elem; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && Tween) { // jQuery 1.8 model obj = propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap(opacityHook, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) dSetter = function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }; // jQuery 1.8 style if (Tween) { propHooks.d = { set: dSetter }; // pre 1.8 } else { // animate paths Step.d = dSetter; } /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } return ret; }; }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { $(el).stop(); } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, // align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#666', cursor: 'default', fontSize: '11px', lineHeight: '14px' } }; defaultOptions = { colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, canvasToolsURL: 'http://code.highcharts.com/3.0.7/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/3.0.7/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 5, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, style: { fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#274b6d',//#3E576F', fontSize: '16px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#4d759e' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { align: 'center', enabled: false, formatter: function () { return this.y === null ? '' : numberFormat(this.y, -1); }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 } }, select: { marker: {} } }, stickyTracking: true //tooltip: { //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} // turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, borderWidth: 1, borderColor: '#909090', borderRadius: 5, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 10, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { cursor: 'pointer', color: '#274b6d', fontSize: '12px' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '1em' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(255, 255, 255, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', shadow: true, //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Pull out axis options and apply them to the respective default axis options /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis); defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis); options.xAxis = options.yAxis = UNDEFINED;*/ // Merge in the default options defaultOptions = merge(defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Merely exposing defaultOptions for outside modules * isn't enough because the setOptions method creates a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; /** * A collection of attribute setters. These methods, if defined, are called right before a certain * attribute is set on an element wrapper. Returning false prevents the default attribute * setter to run. Returning a value causes the default setter to set that value. Used in * Renderer.label. */ wrapper.attrSetters = {}; }, /** * Default base for animation */ opacity: 1, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions); if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var wrapper = this, key, value, result, i, child, element = wrapper.element, nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text" renderer = wrapper.renderer, skipAttr, titleNode, attrSetters = wrapper.attrSetters, shadows = wrapper.shadows, hasSetSymbolSize, doTransform, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (isString(hash)) { key = hash; if (nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } else if (key === 'strokeWidth') { key = 'stroke-width'; } ret = attr(element, key) || wrapper[key] || 0; if (key !== 'd' && key !== 'visibility' && key !== 'fill') { // 'd' is string in animation step ret = parseFloat(ret); } // setter } else { for (key in hash) { skipAttr = false; // reset value = hash[key]; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false) { if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // paths if (key === 'd') { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } //wrapper.d = value; // shortcut for animations // update child tspans x values } else if (key === 'x' && nodeName === 'text') { for (i = 0; i < element.childNodes.length; i++) { child = element.childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (attr(child, 'x') === attr(element, 'x')) { //child.setAttribute('x', value); attr(child, 'x', value); } } } else if (wrapper.rotation && (key === 'x' || key === 'y')) { doTransform = true; // apply gradients } else if (key === 'fill') { value = renderer.color(value, element, key); // circle x and y } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) { key = { x: 'cx', y: 'cy' }[key] || key; // rectangle border radius } else if (nodeName === 'rect' && key === 'r') { attr(element, { rx: value, ry: value }); skipAttr = true; // translation and text rotation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' || key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') { doTransform = true; skipAttr = true; // apply opacity as subnode (required by legacy WebKit and Batik) } else if (key === 'stroke') { value = renderer.color(value, element, key); // emulate VML's dashstyle implementation } else if (key === 'dashstyle') { key = 'stroke-dasharray'; value = value && value.toLowerCase(); if (value === 'solid') { value = NONE; } else if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * pick(hash['stroke-width'], wrapper['stroke-width']); } value = value.join(','); } // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2 // is unable to cast them. Test again with final IE9. } else if (key === 'width') { value = pInt(value); // Text alignment } else if (key === 'align') { key = 'text-anchor'; value = { left: 'start', center: 'middle', right: 'end' }[value]; // Title requires a subnode, #431 } else if (key === 'title') { titleNode = element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); element.appendChild(titleNode); } titleNode.textContent = value; } // jQuery animate changes case if (key === 'strokeWidth') { key = 'stroke-width'; } // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke- // width is 0. #1369 if (key === 'stroke-width' || key === 'stroke') { wrapper[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (wrapper.stroke && wrapper['stroke-width']) { attr(element, 'stroke', wrapper.stroke); attr(element, 'stroke-width', wrapper['stroke-width']); wrapper.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) { element.removeAttribute('stroke'); wrapper.hasStroke = false; } skipAttr = true; } // symbols if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } // let the shadow follow the main element if (shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { i = shadows.length; while (i--) { attr( shadows[i], key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : value ); } } // validate heights if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) { value = 0; } // Record for animation and quick access without polling the DOM wrapper[key] = value; if (key === 'text') { // Delete bBox memo when the text changes if (value !== wrapper.textStr) { delete wrapper.bBox; } wrapper.textStr = value; if (wrapper.added) { renderer.buildText(wrapper); } } else if (!skipAttr) { attr(element, key, value); } } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (doTransform) { wrapper.updateTransform(); } } return ret; }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (strokeWidth, x, y, width, height) { var wrapper = this, key, attribs = {}, values = {}, normalizer; strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges values.x = mathFloor(x || wrapper.x || 0) + normalizer; values.y = mathFloor(y || wrapper.y || 0) + normalizer; values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer); values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer); values.strokeWidth = strokeWidth; for (key in values) { if (wrapper[key] !== values[key]) { // only set attribute if changed wrapper[key] = attribs[key] = values[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { /*jslint unparam: true*//* allow unused param a in the regexp function below */ var elemWrapper = this, elem = elemWrapper.element, textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width), n, serializedCss = '', hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Merge the new styles with the old ones styles = extend( elemWrapper.styles, styles ); // store object elemWrapper.styles = styles; if (textWidth) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { css(elemWrapper.element, styles); } else { for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], nonLeft = align && align !== 'left', shadows = wrapper.shadows; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, height, rotation = wrapper.rotation, baseline, radians = 0, costheta = 1, sintheta = 0, quad, textWidth = pInt(wrapper.textWidth), xCorr = wrapper.xCorr || 0, yCorr = wrapper.yCorr || 0, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed if (defined(rotation)) { radians = rotation * deg2rad; // deg to rad costheta = mathCos(radians); sintheta = mathSin(radians); wrapper.setSpanRotation(rotation, sintheta, costheta); } width = pick(wrapper.elemWidth, elem.offsetWidth); height = pick(wrapper.elemHeight, elem.offsetHeight); // update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } // correct x and y baseline = renderer.fontMetrics(elem.style.fontSize).b; xCorr = costheta < 0 && -width; yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(elem, { textAlign: align }); } // record correction wrapper.xCorr = xCorr; wrapper.yCorr = yCorr; } // apply position with correction css(elem, { left: (x + xCorr) + PX, top: (y + yCorr) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { height = elem.offsetHeight; // assigned to height for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; css(this.element, rotationStyle); }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { attr(wrapper.element, 'transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad; if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } wrapper.bBox = bBox; } return bBox; }, /** * Show the element */ show: function () { return this.attr({ visibility: VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.hide(); } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = this.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks fireEvent(this, 'add'); return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393). while (parentToClean && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, lines = pick(wrapper.textStr, '').toString() .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g), childNodes = textNode.childNodes, styleRegex = /style="([^"]+)"/, hrefRegex = /href="(http[^"]+)"/, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, i = childNodes.length; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left attributes.x = parentX; } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', textLineHeight || renderer.fontMetrics( /px$/.test(tspan.style.fontSize) ? tspan.style.fontSize : textStyles.fontSize ).h, // Safari 6.0.2 - too optimized for its own good (#1539) // TODO: revisit this with future versions of Safari isWebKit && tspan.offsetHeight ); } // Append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 tooLong, actualWidth, clipHeight = wrapper._clipHeight, rest = [], dy = pInt(textLineHeight || 16), softLineNo = 1, bBox; while (words.length || rest.length) { delete wrapper.bBox; // delete cache bBox = wrapper.getBBox(); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { softLineNo++; if (clipHeight && softLineNo * dy > clipHeight) { words = ['...']; wrapper.attr('title', wrapper.textStr); } else { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } } } }); }); }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, STYLE = 'style', verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState[STYLE]; delete normalState[STYLE]; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState[STYLE]; delete hoverState[STYLE]; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState[STYLE]; delete pressedState[STYLE]; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState[STYLE]; delete disabledState[STYLE]; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function () { if (curState !== 3) { callback.call(label); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }; return this.createElement('circle').attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect').attr({ rx: r, ry: r, fill: NONE }); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc]; // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. // obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object. Prior to Highstock, an array was used to define * a linear gradient with pixel positions relative to the SVG. In newer versions * we change the coordinates to apply relative to the shape, using coordinates * 0-1 within the shape. To preserve backwards compatibility, linearGradient * in this definition is an object of x1, y1, x2 and y2. * * @param {Object} color The color or config object */ color: function (color, elem, prop) { var renderer = this, colorObject, regexRgba = /^rgba/, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color && color.linearGradient) { gradName = 'linearGradient'; } else if (color && color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].id; } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Return the reference to the gradient object return 'url(' + renderer.url + '#' + id + ')'; // Webkit and Batik can't show rgba. } else if (regexRgba.test(color)) { colorObject = Color(color); attr(elem, prop + '-opacity', colorObject.get('a')); return colorObject.get('rgb'); } else { // Remove the opacity attribute added above. Does not throw if the attribute is not there. elem.removeAttribute(prop + '-opacity'); return color; } }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, defaultChartStyle = defaultOptions.chart.style, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } x = mathRound(pick(x, 0)); y = mathRound(pick(y, 0)); wrapper = renderer.createElement('text') .attr({ x: x, y: y, text: str }) .css({ fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } wrapper.x = x; wrapper.y = y; return wrapper; }, /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var defaultChartStyle = defaultOptions.chart.style, wrapper = this.createElement('span'), attrSetters = wrapper.attrSetters, element = wrapper.element, renderer = wrapper.renderer; // Text setter attrSetters.text = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = value; return false; }; // Various setters which rely on update transform attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); return false; }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup.attrSetters, { translateX: function (value) { htmlGroupStyle.left = value + PX; }, translateY: function (value) { htmlGroupStyle.top = value + PX; }, visibility: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize) { fontSize = pInt(fontSize || 11); // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, attrSetters = wrapper.attrSetters, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(merge({ width: wrapper.width, height: wrapper.height }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr({ x: x, y: y }); } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } function getSizeAfterAdd() { text.add(wrapper); wrapper.attr({ text: str, // alignment is available now x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ addEvent(wrapper, 'add', getSizeAfterAdd); /* * Add specific attribute setters. */ // only change local variables attrSetters.width = function (value) { width = value; return false; }; attrSetters.height = function (value) { height = value; return false; }; attrSetters.padding = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } return false; }; attrSetters.paddingLeft = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } return false; }; // change local variable and set attribue as well attrSetters.align = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; return false; // prevent setting text-anchor on the group }; // apply these to the box and the text alike attrSetters.text = function (value, key) { text.attr(key, value); updateBoxSize(); updateTextPadding(); return false; }; // apply these to the box but not to the text attrSetters[STROKE_WIDTH] = function (value, key) { needsBox = true; crispAdjust = value % 2 / 2; boxAttr(key, value); return false; }; attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) { if (key === 'fill') { needsBox = true; } boxAttr(key, value); return false; }; attrSetters.anchorX = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); return false; }; attrSetters.anchorY = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); return false; }; // rename attributes attrSetters.x = function (value) { wrapper.x = value; // for animation getter value -= alignFactor * ((width || bBox.width) + padding); wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); return false; }; attrSetters.y = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); return false; }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { removeEvent(wrapper, 'add', getSizeAfterAdd); // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ Highcharts.VMLElement = VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; wrapper.attrSetters = {}; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks fireEvent(wrapper, 'add'); return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function (rotation, sintheta, costheta) { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://highcharts.com/tests/?file=text-rotation css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = [], clockwise; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract 1 from the end X // position. #760, #1371. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { clockwise = value[i] === 'wa' ? 1 : -1; // #1642 if (path[i + 5] === path[i + 7]) { path[i + 7] -= clockwise; } // Start and end Y (#1410) if (path[i + 6] === path[i + 8]) { path[i + 8] -= clockwise; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Get or set attributes */ attr: function (hash, val) { var wrapper = this, key, value, i, result, element = wrapper.element || {}, elemStyle = element.style, nodeName = element.nodeName, renderer = wrapper.renderer, symbolName = wrapper.symbolName, hasSetSymbolSize, shadows = wrapper.shadows, skipAttr, attrSetters = wrapper.attrSetters, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter, val is undefined if (isString(hash)) { key = hash; if (key === 'strokeWidth' || key === 'stroke-width') { ret = wrapper.strokeweight; } else { ret = wrapper[key]; } // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false && value !== null) { // #620 if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // prepare paths // symbols if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) { // if one of the symbol size affecting parameters are changed, // check all the others only once for each call to an element's // .attr() method if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } else if (key === 'd') { value = value || []; wrapper.d = value.join(' '); // used in getter for animation element.path = value = wrapper.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } skipAttr = true; // handle visibility } else if (key === 'visibility') { // let the shadow follow the main element if (shadows) { i = shadows.length; while (i--) { shadows[i].style[key] = value; } } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { elemStyle[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } elemStyle[key] = value; skipAttr = true; // directly mapped to css } else if (key === 'zIndex') { if (value) { elemStyle[key] = value; } skipAttr = true; // x, y, width, height } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) { wrapper[key] = value; // used in getter if (key === 'x' || key === 'y') { key = { x: 'left', y: 'top' }[key]; } else { value = mathMax(0, value); // don't set width or height below zero (#311) } // clipping rectangle special if (wrapper.updateClipping) { wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' wrapper.updateClipping(); } else { // normal elemStyle[key] = value; } skipAttr = true; // class name } else if (key === 'class' && nodeName === 'DIV') { // IE8 Standards mode has problems retrieving the className element.className = value; // stroke } else if (key === 'stroke') { value = renderer.color(value, element, key); key = 'strokecolor'; // stroke width } else if (key === 'stroke-width' || key === 'strokeWidth') { element.stroked = value ? true : false; key = 'strokeweight'; wrapper[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } // dashStyle } else if (key === 'dashstyle') { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; wrapper.dashstyle = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ skipAttr = true; // fill } else if (key === 'fill') { if (nodeName === 'SPAN') { // text color elemStyle.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE ? true : false; value = renderer.color(value, element, key, wrapper); key = 'fillcolor'; } // opacity: don't bother - animation is too slow and filters introduce artifacts } else if (key === 'opacity') { /*css(element, { opacity: value });*/ skipAttr = true; // rotation on VML elements } else if (nodeName === 'shape' && key === 'rotation') { wrapper[key] = element.style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; element.style.top = mathRound(mathCos(value * deg2rad)) + PX; // translation for animation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') { wrapper[key] = value; wrapper.updateTransform(); skipAttr = true; // text for rotated and non-rotated elements } else if (key === 'text') { this.bBox = null; element.innerHTML = value; skipAttr = true; } if (!skipAttr) { if (docMode8) { // IE8 setAttribute bug element[key] = value; } else { attr(element, key, value); } } } } } return ret; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; } }; VMLElement = extendClass(SVGElement, VMLElement); /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV); box = boxWrapper.element; box.style.position = RELATIVE; // for freeform drawing using renderer directly container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { member.css(clipRect.getCSS(member)); }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right addEvent(wrapper, 'add', applyRadialGradient); } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * VML uses a shape for rect to overcome bugs and rotation problems */ rect: function (x, y, width, height, r, strokeWidth) { var wrapper = this.symbol('rect'); wrapper.r = isObject(x) ? x.r : r; //return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var parentStyle = parentNode.style; css(element, { flip: 'x', left: pInt(parentStyle.width) - 1, top: pInt(parentStyle.height) - 1, rotation: -90 }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape * * @param {Number} left Left position * @param {Number} top Top position * @param {Number} r Border radius * @param {Object} options Width and height */ rect: function (left, top, width, height, options) { var right = left + width, bottom = top + height, ret, r; // No radius, return the more lightweight square if (!defined(options) || !options.r) { ret = SVGRenderer.prototype.symbols.square.apply(0, arguments); // Has radius add arcs for the corners } else { r = mathMin(options.r, width, height); ret = [ M, left + r, top, L, right - r, top, 'wa', right - 2 * r, top, right, top + 2 * r, right - r, top, right, top + r, L, right, bottom - r, 'wa', right - 2 * r, bottom - 2 * r, right, bottom, right, bottom - r, right - r, bottom, L, left + r, bottom, 'wa', left, bottom - 2 * r, left + 2 * r, bottom, left + r, bottom, left, bottom - r, L, left, top + r, 'wa', left, top, left + 2 * r, top + 2 * r, left, top + r, left + r, top, 'x', 'e' ]; } return ret; } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); return measuringSpan.offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; css = extend(css, labelOptions.style); // first call if (!defined(label)) { attr = { align: axis.labelAlign }; if (isNumber(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } if (width && labelOptions.ellipsis) { attr._clipHeight = axis.len / tickPositions.length; } tick.label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(css) .add(axis.labelGroup) : null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.labelBBox, // assume getLabelSize has run at this point axis = this.axis, options = axis.options, labelOptions = options.labels, width = bBox.width, leftSide = width * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] - labelOptions.x; return [-leftSide, width - leftSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, chart = axis.chart, isFirst = this.isFirst, isLast = this.isLast, x = xy.x, reversed = axis.reversed, tickPositions = axis.tickPositions; if (isFirst || isLast) { var sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], plotLeft = chart.plotLeft, plotRight = plotLeft + axis.len, neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]], neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (x + leftSide < plotLeft) { // Align it to plot left x = plotLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (x + rightSide > plotRight) { // Align it to plot right x = plotRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = x; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b, rotation = labelOptions.rotation; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for rotation (#1764) if (rotation && axis.side === 2) { y -= baseline - baseline * mathCos(rotation * deg2rad); } // Vertically centered if (!defined(labelOptions.y) && !rotation) { // #1951 y += baseline - label.getBBox().height / 2; } // Correct for staggered labels if (staggerLines) { y += (index / (step || 1) % staggerLines) * (axis.labelOffset / staggerLines); } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1, // #1480, #1687 staggerLines = axis.staggerLines; this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) { show = false; } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ function PlotLineOrBand(axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } } PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, halfPointRange = (axis.pointRange || 0) / 2, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); attribs = { fill: color }; if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; if (label) { plotLine.label = label = label.destroy(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr({ align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, zIndex: zIndex }) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], pick(path[6], path[1])]; ys = [path[2], path[5], pick(path[7], path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption, stacking) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; this.percent = stacking === 'percent'; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label.attr({ visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }); } } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 5, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#4d759e', //font: defaultFont.replace('normal', 'bold') fontWeight: 'bold' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return numberFormat(this.total, -1); }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -8, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 8, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { x: 0, y: 14 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { x: 0, y: -5 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.xOrY = isXAxis ? 'x' : 'y'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = []; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0; // Major ticks axis.ticks = {}; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; // Dictionary for stacks max values axis.stackExtremes = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() chart.axes.push(axis); chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053) userOptions ) ); }, /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = this.userMin = this.userMax = UNDEFINED; // #1611, #2306 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.xOrY + 'Axis'; // xAxis or yAxis // Remove associated series each(this.series, function (series) { series.remove(false); }); // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (value >= 1000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1); } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // reset dataMin and dataMax in case we're redrawing axis.dataMin = axis.dataMax = null; // reset cached stacking extremes axis.stackExtremes = {}; axis.buildStacks(); // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this, axisLength = axis.len, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axisLength; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * axisLength; } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, translatedValue = axis.translate(value, null, null, old), cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0); }, /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Set the tick positions of a logarithmic axis */ getLogTickPositions: function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max)) { // #1670 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( getTimeTicks( normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, transA = axis.transA; // adjust translation for padding if (axis.isXAxis) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = series.pointRange, pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, keepTwoTicksOnly, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; if (secondPass) { axis.range = null; // don't use it when running setExtremes } } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); // For squished axes, set only two ticks if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial) { keepTwoTicksOnly = true; axis.tickInterval /= 4; // tick extremes closer to the real values } } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { // Too many ticks if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) { error(19, true); } if (isDatetimeAxis) { tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)( normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } if (keepTwoTicksOnly) { tickPositions.splice(1, tickPositions.length - 2); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (options.startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = 0.001; // The lowest possible number to avoid extra padding on columns axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (!axis.isXAxis) { if (axis.oldStacks) { stacks = axis.stacks = axis.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { // Prevent pinch zooming out of range. Check for defined is for #1946. if (!this.allowZoomOutside) { if (defined(this.dataMin) && newMin <= this.dataMin) { newMin = UNDEFINED; } if (defined(this.dataMax) && newMax >= this.dataMax) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width, height, top, left; // Expose basic values to use in Series object and navigator this.left = left = pick(options.left, chart.plotLeft + offsetLeft); this.top = top = pick(options.top, chart.plotTop); this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight); this.height = height = pick(options.height, chart.plotHeight); this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, addPlotBand: function (options) { this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n, i, autoStaggerLines = 1, maxStaggerLines = pick(labelOptions.maxStaggerLines, 5), sortedPositions, lastRight, overlap, pos, bBox, x, w, lineNo; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .add(); } if (hasData || axis.isLinked) { // Set the explicit or automatic label alignment axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation)); // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); // Handle automatic stagger lines if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) { sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions; while (autoStaggerLines < maxStaggerLines) { lastRight = []; overlap = false; for (i = 0; i < sortedPositions.length; i++) { pos = sortedPositions[i]; bBox = ticks[pos].label && ticks[pos].label.getBBox(); w = bBox ? bBox.width : 0; lineNo = i % autoStaggerLines; if (w) { x = axis.translate(pos); // don't handle log if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) { overlap = true; } lastRight[lineNo] = x + w; } } if (overlap) { autoStaggerLines++; } else { break; } } if (autoStaggerLines > 1) { axis.staggerLines = autoStaggerLines; } } each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); titleOffsetOption = axisTitleOptions.offset; } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.axisTitleMargin = pick(titleOffsetOption, labelOffset + titleMargin + (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x']) ); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, stacks = axis.stacks, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, to; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) { // Reorganize the indices i = (i === tickPositions.length - 1) ? 0 : i + 1; // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true); } ticks[pos].render(i, false, 1); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && axis.min === 0) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { var stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } } // End stacked totals axis.isDirty = false; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { var axis = this, chart = axis.chart, pointer = chart.pointer; // hide tooltip and hover states if (pointer.reset) { pointer.reset(true); } // render the axis axis.render(); // move plot lines and bands each(axis.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(axis.series, function (series) { series.isDirty = true; }); }, /** * Build the stacks from top down */ buildStacks: function () { var series = this.series, i = series.length; if (!this.isXAxis) { while (i--) { series[i].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); } }; // end Axis /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ function Tooltip() { this.init.apply(this, arguments); } Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -999 }); // #2301 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.destroy(); } }); // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden; // get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY }); // move to the intermediate value tooltip.label.attr(now); // run on next tick of the mouse tracker if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) { // never allow two timeouts clearTimeout(this.tooltipTimeout); // set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function () { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Hide the crosshairs */ hideCrosshairs: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.hide(); } }); }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { // Set up the variables var chart = this.chart, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, distance = pick(this.options.distance, 12), pointX = point.plotX, pointY = point.plotY, x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance), y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip alignedRight; // It is too far to the left, adjust it if (x < 7) { x = plotLeft + mathMax(pointX, 0) + distance; } // Test to see if the tooltip is too far to the right, // if it is, move it back to be inside and then up to not cover the point. if ((x + boxWidth) > (plotLeft + plotWidth)) { x -= (x + boxWidth) - (plotLeft + plotWidth); y = pointY - boxHeight + plotTop - distance; alignedRight = true; } // If it is now above the plot area, align it to the top of the plot area if (y < plotTop + 5) { y = plotTop + 5; // If the tooltip is still covering the point, move it below instead if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) { y = pointY + plotTop + distance; // below } } // Now if the tooltip is below the chart, move it up. It's better to cover the // point than to disappear outside the chart. #834. if (y + boxHeight > plotTop + plotHeight) { y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below } return {x: x, y: y}; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), series = items[0].series, s; // build the header s = [series.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, crosshairsOptions = options.crosshairs, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y }); this.isHidden = false; } // crosshairs if (crosshairsOptions) { crosshairsOptions = splat(crosshairsOptions); // [x, y] var path, i = crosshairsOptions.length, attribs, axis, val, series; while (i--) { series = point.series; axis = series[i ? 'yAxis' : 'xAxis']; if (crosshairsOptions[i] && axis) { val = i ? pick(point.stackY, point.y) : point.x; // #814 if (axis.isLog) { // #1671 val = log2lin(val); } if (i === 1 && series.modifyValue) { // #1205, #2316 val = series.modifyValue(val); } path = axis.getPlotLinePath( val, 1 ); if (tooltip.crosshairs[i]) { tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE }); } else { attribs = { 'stroke-width': crosshairsOptions[i].width || 1, stroke: crosshairsOptions[i].color || '#C0C0C0', zIndex: crosshairsOptions[i].zIndex || 2 }; if (crosshairsOptions[i].dashStyle) { attribs.dashstyle = crosshairsOptions[i].dashStyle; } tooltip.crosshairs[i] = chart.renderer.path(path) .attr(attribs) .add(); } } } } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); } }; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ function Pointer(chart, options) { this.init(chart, options); } Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Framework specific normalizing (#1165) e = washMouseEvent(e); // iOS ePos = e.touches ? e.touches.item(0) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point && point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); tooltip.hideCrosshairs(); } pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Run translation operations */ pinchTranslate: function (zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (zoomHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (zoomVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, zoomHor = self.zoomHor || self.pinchHor, zoomVert = self.zoomVert || self.pinchVert, hasZoom = zoomHor || zoomVert, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || chart.runChartClick), clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if ((hasZoom || followTouchMove) && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(axis.dataMin), max = axis.toPixels(axis.dataMax), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } self.pinchTranslate(zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } } }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.x, selectionTop = selectionBox.y, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)), selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height)); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.xOrY + 'Axis'].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { this.drop(e); }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { this.reset(); this.chartPosition = null; // also reset the chart position, used in #149 fix }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; // normalize e = this.normalize(e); // #295 e.returnValue = false; if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries; if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop, inverted = chart.inverted, chartPosition, plotX, plotY; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { chartPosition = this.chartPosition; plotX = hoverPoint.plotX; plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: chartPosition.left + plotLeft + (inverted ? chart.plotWidth - plotY : plotX), pageY: chartPosition.top + plotTop + (inverted ? chart.plotHeight - plotX : plotY) }); // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, onContainerTouchStart: function (e) { var chart = this.chart; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Prevent the click pseudo event from firing unless it is set in the options /*if (!chart.runChartClick) { e.preventDefault(); }*/ // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } else { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { this.drop(e); }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container, events; this._events = events = [ [container, 'onmousedown', 'onContainerMouseDown'], [container, 'onmousemove', 'onContainerMouseMove'], [container, 'onclick', 'onContainerClick'], [container, 'mouseleave', 'onContainerMouseLeave'], [doc, 'mousemove', 'onDocumentMouseMove'], [doc, 'mouseup', 'onDocumentMouseUp'] ]; if (hasTouch) { events.push( [container, 'ontouchstart', 'onContainerTouchStart'], [container, 'ontouchmove', 'onContainerTouchMove'], [doc, 'touchend', 'onDocumentTouchEnd'] ); } each(events, function (eventConfig) { // First, create the callback function that in turn calls the method on Pointer pointer['_' + eventConfig[2]] = function (e) { pointer[eventConfig[2]](e); }; // Now attach the function, either as a direct property or through addEvent if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]]; } else { addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var pointer = this; // Release all DOM events each(pointer._events, function (eventConfig) { if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE } else { removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); delete pointer._events; // memory and CPU leak clearInterval(pointer.tooltipTimeout); } }; /** * The overview of the chart's series */ function Legend(chart, options) { this.init(chart, options); } Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.lastLineHeight = 0; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? item.color : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { stroke: symbolColor, fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = options.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 8) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series || item, itemOptions = series.options, showCheckbox = itemOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? li : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); li.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { li.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (itemOptions && showCheckbox) { item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, options.itemCheckboxStyle, chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.legendItemWidth = options.itemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = bBox.height; // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = []; each(chart.series, function (serie) { var seriesOptions = serie.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, seriesOptions.linkedTo === UNDEFINED ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( serie.legendItems || (seriesOptions.legendType === 'point' ? serie.data : serie) ); }); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp(null, null, null, legendWidth, legendHeight) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, pageCount, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight; this.pageCount = pageCount = mathCeil(legendHeight / clipHeight); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, 0, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pageCount = this.pageCount, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + this.pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1; this.scrollGroup.animate({ translateY: scrollOffset }); pager.attr({ text: currentPage + '/' + pageCount }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview. // TODO: When IE11 is released, check again for this bug, and remove the fix // or make a better one. if (/Trident\/7\.0/.test(userAgent)) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { proceed.call(legend, item); }; if (legend.chart.renderer.forExport) { runPositionItem(); } else { setTimeout(runPositionItem); } }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = 0; chart.counters = new ChartCounters(); chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (chart.hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); chart.getMargins(); // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer && pointer.reset) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv; var loadingOptions = options.loading; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '', left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Generate stacks for each series and calculate stacks total values */ getStacks: function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }, /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange; if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function () { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: 15 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; // Adjust for browser consistency + backwards compat after #776 fix if (titleOffset >= 18 && titleOffset <= 25) { titleOffset = 15; } } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } this.titleOffset = titleOffset; // used in getMargins }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) chart.containerWidth = adapterRun(renderTo, 'width'); chart.containerHeight = adapterRun(renderTo, 'height'); chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(optionsChart.height, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex]) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly if (!renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, true) : new Renderer(container, chartWidth, chartHeight); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, spacing = chart.spacing, axisOffset, legend = chart.legend, margin = chart.margin, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 10), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset = chart.titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(margin[1])) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacing[1] ); } } else if (align === 'left') { if (!defined(margin[3])) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacing[3] ); } } else if (verticalAlign === 'top') { if (!defined(margin[0])) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacing[0] ); } } else if (verticalAlign === 'bottom') { if (!defined(margin[2])) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacing[2] ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(margin[3])) { chart.plotLeft += axisOffset[3]; } if (!defined(margin[0])) { chart.plotTop += axisOffset[0]; } if (!defined(margin[2])) { chart.marginBottom += axisOffset[2]; } if (!defined(margin[1])) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Add the event handlers necessary for auto resizing * */ initReflow: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, reflowTimeout; function reflow(e) { var width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win; // #805 - MooTools doesn't supply e // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(reflowTimeout); chart.reflowTimeout = reflowTimeout = setTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }, 100); } chart.containerWidth = width; chart.containerHeight = height; } } chart.reflow = reflow; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } css(chart.container, { width: chartWidth + PX, height: chartHeight + PX }); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, spacing = chart.spacing, margin = chart.margin; chart.plotTop = pick(margin[0], spacing[0]); chart.marginRight = pick(margin[1], spacing[1]); chart.marginBottom = pick(margin[2], spacing[2]); chart.plotLeft = pick(margin[3], spacing[3]); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight) ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }); }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; var labels = options.labels, credits = options.credits, creditsHref; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); chart.getStacks(); // render stacks // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } each(chart.series, function (serie) { serie.translate(); serie.setTooltipPoints(); serie.render(); }); // Labels if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; chart.credits = renderer.text( credits.text, 0, 0 ) .on('click', function () { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } // Set flag chart.hasRendered = true; }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set chart.pointer = new Pointer(chart, options); chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887 this.firePointEvent('mouseOut'); this.setState(); chart.hoverPoint = null; } }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation) { var point = this, series = point.series, graphic = point.graphic, i, data = series.data, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function () { point.applyOptions(options); // update visuals if (isObject(options)) { series.getAttribs(); if (graphic) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || '']); } } } // record changes in the parallel arrays i = inArray(point, data); series.xData[i] = point.x; series.yData[i] = series.toYData ? series.toYData(point) : point.y; series.zData[i] = point.z; seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.legend.destroyItem(point); } if (redraw) { chart.redraw(animation); } }); }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, points = series.points, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.xData.splice(i, 1); series.yData.splice(i, 1); series.zData.splice(i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, newSymbol, pointAttr = point.pointAttr; state = state || NORMAL_STATE; // empty string if ( // already has this state state === point.state || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr[state].r; point.graphic.attr(merge( pointAttr[state], radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr[state]) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; // Move the existing graphic } else { stateMarkerGraphic.attr({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide'](); } } point.state = state; } }; /** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, colorCounter: 0, init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // set the data series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123) stableSort(chartSeries, function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, a._i); }); each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; if (series.isCartesian) { each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS]) { error(18, true); } }); } }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // the tooltip options are merged between global and series specific options this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip); // Delte marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, /** * Get the series' color */ getColor: function () { var options = this.options, userOptions = this.userOptions, defaultColors = this.chart.options.colors, counters = this.chart.counters, color, colorIndex; color = options.color || defaultPlotOptions[this.type].color; if (!color && !options.colorByPoint) { if (defined(userOptions._colorIndex)) { // after Series.update() colorIndex = userOptions._colorIndex; } else { userOptions._colorIndex = counters.color; colorIndex = counters.color++; } color = defaultColors[colorIndex]; } this.color = color; counters.wrapColor(defaultColors.length); }, /** * Get the series' symbol */ getSymbol: function () { var series = this, userOptions = series.userOptions, seriesMarkerOption = series.options.marker, chart = series.chart, defaultSymbols = chart.options.symbols, counters = chart.counters, symbolIndex; series.symbol = seriesMarkerOption.symbol; if (!series.symbol) { if (defined(userOptions._symbolIndex)) { // after Series.update() symbolIndex = userOptions._symbolIndex; } else { userOptions._symbolIndex = counters.symbol; symbolIndex = counters.symbol++; } series.symbol = defaultSymbols[symbolIndex]; } // don't substract radius in image symbols (#604) if (/^url/.test(series.symbol)) { seriesMarkerOption.radius = 0; } counters.wrapSymbol(defaultSymbols.length); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLegendSymbol: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legendOptions.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } }, /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, xData = series.xData, yData = series.yData, zData = series.zData, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, isInTheMiddle, x, i; setAnimation(animation, chart); // Make graph animate sideways if (shift) { each([graph, area, series.graphNeg, series.areaNeg], function (shape) { if (shape) { shape.shift = currentShift + 1; } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } xData.splice(i, 0, x); yData.splice(i, 0, series.toYData ? series.toYData(point) : point.y); zData.splice(i, 0, point.z); if (names) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); xData.shift(); yData.shift(); zData.shift(); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw) { var series = this, oldData = series.points, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, names = xAxis && xAxis.names, i; // reset properties series.xIncrement = null; series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // parallel arrays var xData = [], yData = [], zData = [], dataLength = data ? data.length : [], turboThreshold = pick(options.turboThreshold, 1000), pt, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length, hasToYData = !!series.toYData; // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); xData[i] = pt.x; yData[i] = hasToYData ? series.toYData(pt) : pt.y; zData[i] = pt.z; if (names && pt.name) { names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; series.xData = xData; series.yData = yData; series.zData = zData; // destroy old points i = (oldData && oldData.length) || 0; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(false); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { var min = xAxis.min, max = xAxis.max; // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Adds series' points value to corresponding stack */ setStackedPoints: function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, isNegative, stack, other, key, i, x, y; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < threshold; key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption, stacking); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; stack.points[series.index] = [stack.cum || 0]; // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total += mathAbs(y) || 0; } } else { stack.total += y || 0; } stack.cum = (stack.cum || 0) + (y || 0); stack.points[series.index].push(stack.cum); stackedYData[i] = stack.cum; } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }, /** * Iterate over all stacks and compute the absolute values to percent */ setPercentStacks: function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks; each([stackKey, '-' + stackKey], function (key) { var i = series.xData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = series.xData[i]; stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[series.index]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }, /** * Calculate Y extremes for visible data */ getExtremes: function () { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yData = this.stackedYData || this.processedYData, yDataLength = yData.length, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, dataMin, dataMax, x, y, i, j; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = pick(dataMin, arrayMin(activeYData)); this.dataMax = pick(dataMax, arrayMax(activeYData)); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; stackValues = pointStack.points[series.index]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === 0) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = stacking === 'percent' && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ? //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 yAxis.translate(yValue, 0, 1, 0, 1) : UNDEFINED; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Memoize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, xExtremes = xAxis && xAxis.getExtremes(), axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, pointX, nextPoint, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Polar needs additional shaping if (series.orderTooltipPoints) { series.orderTooltipPoints(points); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; pointX = point.x; if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149 nextPoint = points[i + 1]; // Set this range's low to the last range's high plus one low = high === UNDEFINED ? 0 : high + 1; // Now find the new high high = points[i + 1] ? mathMin(mathMax(0, mathFloor( // #2070 (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2 )), axisLength) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } } series.tooltipPoints = tooltipPoints; }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = this, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime', headerFormat = tooltipOptions.headerFormat, closestPointRange = xAxis && xAxis.closestPointRange, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { if (closestPointRange) { for (n in timeUnits) { if (timeUnits[n] >= closestPointRange) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } } // Insert the header date format if any if (isDateTime && xDateFormat && isNumber(point.key)) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); }, /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = '_sharedClip' + animation.duration + animation.easing; // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animation.duration); } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group; if (group && this.options.clip !== false) { group.clip(chart.clipRect); this.markerGroup.clip(); // no clip } // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, pointMarkerOptions, enabled, isInside, markerGroup = series.markerGroup; if (seriesMarkerOptions.enabled || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858 // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic .attr({ // Since the marker group isn't clipped, each individual marker must be toggled visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }) .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, defaultLineColor = normalOptions.lineColor, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // if no hover color is given, brighten the normal color pointStateOptionsHover.color = Color(pointStateOptionsHover.color || point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness).get(); } // normal point state inherits series wide normal state pointAttr[NORMAL_STATE] = series.convertAttribs(extend({ color: point.color, // #868 fillColor: point.color, // Individual point color or negative color markers (#2219) lineColor: defaultLineColor === null ? point.color : UNDEFINED // Bubbles take point color, line markers use white }, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, n; // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); for (n in proto) { // Overwrite series-type specific methods (#2270) if (proto.hasOwnProperty(n)) { this[n] = UNDEFINED; } } extend(this, seriesTypes[newOptions.type || oldType].prototype); this.init(chart, newOptions); if (pick(redraw, true)) { chart.redraw(false); } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(['xAxis', 'yAxis'], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; axis.stacks = {}; // Rebuild stacks when updating (#2229) } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Draw the data labels */ drawDataLabels: function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', series.visible ? VISIBLE : HIDDEN, options.zIndex || 6 ); // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(extend(options.style, cursor && { cursor: cursor })) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }, /** * Align each individual data label */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), visible = this.visible && chart.isInsidePlot(point.plotX, point.plotY, inverted), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text alignAttr = { align: options.align, x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } } } // Show or hide based on the final aligned position if (!visible) { dataLabel.attr({ y: -999 }); } }, /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ justifyDataLabel: function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified; // Off left off = alignAttr.x; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor || options.negativeFillColor, translatedThreshold, posAttr, negAttr, graph = this.graph, area = this.area, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), yAxis = this.yAxis, above, below; if (negativeColor && (graph || area)) { translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true)); above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax }; if (chart.inverted) { above.height = below.y = chart.plotWidth - translatedThreshold; if (renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } } if (yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.negClip = negClip = renderer.clipRect(negAttr); if (graph && this.graphNeg) { graph.clip(posClip); this.graphNeg.clip(negClip); } if (area) { area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { return { translateX: this.xAxis ? this.xAxis.left : this.chart.plotLeft, translateY: this.yAxis ? this.yAxis.top : this.chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, doAnimation = animation && !!series.animate && chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (doAnimation) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.clipNeg(); } // draw the data labels (inn pies they go before the points) series.drawDataLabels(); // draw the points series.drawPoints(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (doAnimation) { series.animate(); } else if (!hasRendered) { series.afterAnimate(); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.setTooltipPoints(true); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + 1; } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTracker: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; // end Series prototype /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, val, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(+x); } } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836 return; // The point exists, push it to the segment } else if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { plotX = xAxis.translate(x); val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991 plotY = yAxis.toPixels(val, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length, translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181 yBottom; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { yBottom = pick(segment[i].yBottom, translatedThreshold); // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, yBottom); } areaSegmentPath.push(segment[i].plotX, yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment, translatedThreshold); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment, translatedThreshold) { path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, negativeColor = options.negativeColor, negativeFillColor = options.negativeFillColor, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color if (negativeColor || negativeFillColor) { props.push(['areaNeg', negativeColor, negativeFillColor]); } each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, legend.options.symbolWidth, 12, 2 ).attr({ zIndex: 3 }).add(item.legendGroup); } }); seriesTypes.area = AreaSeries;/** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph, drawLegendSymbol: areaProto.drawLegendSymbol }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1), xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = options.borderWidth, yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1; if (chart.renderer.isVML && chart.inverted) { yCrisp += 1; } Series.prototype.translate.apply(series); // record the new values each(series.points, function (point) { var yBottom = pick(point.yBottom, translatedThreshold), plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), right, bottom, fromTop, fromLeft, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485) } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Round off to obtain crisp edges fromLeft = mathAbs(barX) < 0.5; right = mathRound(barX + barW) + xCrisp; barX = mathRound(barX) + xCrisp; barW = right - barX; fromTop = mathAbs(barY) < 0.5; bottom = mathRound(barY + barH) + yCrisp; barY = mathRound(barY) + yCrisp; barH = bottom - barY; // Top and left edges are exceptions if (fromLeft) { barX += 1; barW -= 1; } if (fromTop) { barY -= 1; barH += 1; } // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: barW, height: barH }; }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, options = series.options, renderer = series.chart.renderer, shapeArgs; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic.animate(merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ drawTracker: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; if (chart.hoverSeries !== series) { series.onMouseOver(); } while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Override the basic data label alignment by adjusting for the position of the column */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, tooltip: { headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>', followPointer: true }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup'], takeOrdinalPosition: false, // #2342 drawTracker: ColumnSeries.prototype.drawTracker, setTooltipPoints: noop }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { return this.point.name; } // softConnector: true, //y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; // Disallow negative values (#1530) if (point.y < 0) { point.y = null; } //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart, method; // if called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][method](); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw) { Series.prototype.setData.call(this, data, false); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(); } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { var i, total = 0, points, len, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; Series.prototype.generatePoints.call(this); // Populate local vars points = this.points; len = points.length; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; point.percentage = total > 0 ? (point.y / total) * 100 : 0; point.total = total; } }, /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), isPercent; return map(positions, function (length, i) { isPercent = /%$/.test(length); handleSlicingRoom = i < 2 || (i === 2 && isPercent); return (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length) + (handleSlicingRoom ? slicingRoom : 0); }); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((options.endAngle || (startAngle + 360)) - 90), circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // center for the sliced out slice angle = (end + start) / 2; if (angle > 0.75 * circ) { angle -= 2 * mathPI; } point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, setTooltipPoints: noop, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { point.graphic = graphic = renderer.arc(shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility if (point.visible === false) { point.setVisible(false); } }); }, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Override the base drawDataLabels method by pie specific functionality */ drawDataLabels: function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel) { // it may have been cancelled in the base method (#407) halves[point.half].push(point); } }); // assume equal label heights i = 0; while (!labelHeight && data[i]) { // #1569 labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968 i++; } /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, length = points.length, slotIndex; // Sort by angle series.sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // build the slots for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) { slots.push(pos); // visualize the slot /* var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver' }) .add(); chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4) .attr({ fill: 'silver' }).add(); } */ } slotsLength = slots.length; // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = naturalY; } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility }) .add(series.group); } } else if (connector) { point.connector = connector.destroy(); } }); } } }, /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ verifyDataLabelOverflow: function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); this.drawDataLabels(); // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }, /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ placeDataLabels: function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }, alignDataLabel: noop, /** * Draw point specific tracker objects. Inherit directly from column series. */ drawTracker: ColumnSeries.prototype.drawTracker, /** * Use a simple symbol from column prototype */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Legend: Legend, Pointer: Pointer, Point: Point, Tick: Tick, Tooltip: Tooltip, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
!function(e,t){"undefined"==typeof process&&(e.process={argv:[],cwd:function(){return""},browser:!0,env:{NODE_ENV:"development"},version:"",platform:e.navigator&&e.navigator.userAgent&&/Windows/.test(e.navigator.userAgent)?"win":""})}("object"==typeof self&&self.Object==Object?self:"object"==typeof process&&"[object process]"===Object.prototype.toString.call(process)?global:window),function(u,l,t){var f=l.define,d=function(e){var t,n=e.split("."),r=l;for(t=0;t<n.length&&r;t++)r=r[n[t]];return r},p=l.define&&l.define.modules||l._define&&l._define.modules||{},h=l.define=function(e,t,n){var r;"function"==typeof t&&(n=t,t=[]);var a,i,o=[];for(a=0;a<t.length;a++)o.push(u[t[a]]?d(u[t[a]]):p[t[a]]||d(t[a]));"require"===(i=t)[0]&&"exports"===i[1]&&"module"===i[2]||!t.length&&n.length?(r={exports:{}},o[0]=function(e){return u[e]?d(u[e]):p[e]},o[1]=r.exports,o[2]=r):o[0]||"exports"!==t[0]?o[0]||"module"!==t[0]||(o[0]={id:e}):(r={exports:{}},o[0]=r.exports,"module"===t[1]&&(o[1]=r)),l.define=f;var s=n?n.apply(null,o):void 0;l.define=h,s=r&&r.exports?r.exports:s,p[e]=s;var c=u[e];c&&!d(c)&&(function(e){if(!e||!e.__esModule)return!1;var t={__esModule:!0,default:!0};for(var n in e)if(!t[n])return!1;return!0}(s)&&(s=s.default),function(e,t){var n,r,a,i=e.split("."),o=l;for(n=0;n<i.length-1;n++)(a=o[r=i[n]])||(a=o[r]={}),o=a;o[r=i[i.length-1]]=t}(c,s))};l.define.orig=f,l.define.modules=p,l.define.amd=!0,h("@loader",[],function(){var e=function(){};return{get:function(){return{prepareGlobal:e,retrieveGlobal:e}},global:l,__exec:function(e){t(e.source,l)}}})}({jquery:"jQuery","can-namespace":"can",kefir:"Kefir","validate.js":"validate",react:"React"},"object"==typeof self&&self.Object==Object?self:"object"==typeof process&&"[object process]"===Object.prototype.toString.call(process)?global:window,function(__$source__,__$global__){eval("(function() { "+__$source__+" \n }).call(__$global__);")}),define("can-namespace",function(e,t,n){n.exports={}}),define("can-symbol",["require","exports","module","can-namespace"],function(u,e,t){!function(e,t,n,r){"use strict";var a,i=u("can-namespace");if("undefined"!=typeof Symbol&&"function"==typeof Symbol.for&&"symbol"==typeof Symbol("a symbol for testing symbols"))a=Symbol;else{var o=0,s={},c={};(a=function(e){var t="@@symbol"+o+++e,n={};return Object.defineProperties(n,{toString:{value:function(){return t}}}),n}).for=function(e){var t=s[e];return t||(t=s[e]=a(e),c[t]=e),t},a.keyFor=function(e){return c[e]},["hasInstance","isConcatSpreadable","iterator","match","prototype","replace","search","species","split","toPrimitive","toStringTag","unscopables"].forEach(function(e){a[e]=a("Symbol."+e)})}["isMapLike","isListLike","isValueLike","isFunctionLike","getOwnKeys","getOwnKeyDescriptor","proto","getOwnEnumerableKeys","hasOwnKey","hasKey","size","getName","getIdentity","assignDeep","updateDeep","getValue","setValue","getKeyValue","setKeyValue","updateValues","addValue","removeValues","apply","new","onValue","offValue","onKeyValue","offKeyValue","getKeyDependencies","getValueDependencies","keyHasDependencies","valueHasDependencies","onKeys","onKeysAdded","onKeysRemoved","onPatches"].forEach(function(e){a.for("can."+e)}),r.exports=i.Symbol=a}(0,0,0,t)}),define("can-reflect/reflections/helpers",["require","exports","module","can-symbol"],function(e,t,n){"use strict";var a=e("can-symbol");n.exports={makeGetFirstSymbolValue:function(e){var n=e.map(function(e){return a.for(e)}),r=n.length;return function(e){for(var t=-1;++t<r;)if(void 0!==e[n[t]])return e[n[t]]}},hasLength:function(e){var t=typeof e;if("string"===t||Array.isArray(e))return!0;var n=e&&"boolean"!==t&&"number"!==t&&"length"in e&&e.length;return"function"!=typeof e&&(0===n||"number"==typeof n&&0<n&&n-1 in e)}}}),define("can-reflect/reflections/type/type",["require","exports","module","can-symbol","can-reflect/reflections/helpers"],function(e,t,n){"use strict";var o=e("can-symbol"),r=e("can-reflect/reflections/helpers"),s=Object.getOwnPropertyNames(function(){}.prototype),c=Object.getPrototypeOf(function(){}.prototype);var a=r.makeGetFirstSymbolValue(["can.new","can.apply"]);function i(e){var t=typeof e;return null==e||"function"!==t&&"object"!==t}var u=Object.prototype.hasOwnProperty,l=Function.prototype.toString,f=l.call(Object);function d(e){if(!e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);if(t===Object.prototype||null===t)return!0;var n=u.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&l.call(n)===f}var p,h=o.for("can.onValue"),v=o.for("can.onKeyValue"),y=o.for("can.onPatches");if("undefined"!=typeof Symbol&&"function"==typeof Symbol.for&&"symbol"==typeof Symbol("a symbol for testing symbols"))p=function(e){return"symbol"==typeof e};else{var g="@@symbol";p=function(e){return"object"==typeof e&&!Array.isArray(e)&&e.toString().substr(0,g.length)===g}}n.exports={isConstructorLike:function(e){var t=e[o.for("can.new")];if(void 0!==t)return t;if("function"!=typeof e)return!1;var n=e.prototype;if(!n)return!1;if(c!==Object.getPrototypeOf(n))return!0;var r=Object.getOwnPropertyNames(n);if(r.length!==s.length)return!0;for(var a=0,i=r.length;a<i;a++)if(r[a]!==s[a])return!0;return!1},isFunctionLike:function(e){var t,n=!!e&&e[o.for("can.isFunctionLike")];return void 0!==n?n:void 0!==(t=a(e))?!!t:"function"==typeof e},isListLike:function(e){var t;if("string"==typeof e)return!0;if(i(e))return!1;if(void 0!==(t=e[o.for("can.isListLike")]))return t;var n=e[o.iterator];return void 0!==n?!!n:!!Array.isArray(e)||r.hasLength(e)},isMapLike:function(e){if(i(e))return!1;var t=e[o.for("can.isMapLike")];if(void 0!==t)return!!t;var n=e[o.for("can.getKeyValue")];return void 0===n||!!n},isObservableLike:function(e){return!i(e)&&Boolean(e[h]||e[v]||e[y])},isPrimitive:i,isBuiltIn:function(e){return!!(i(e)||Array.isArray(e)||d(e)||"[object Object]"!==Object.prototype.toString.call(e)&&-1!==Object.prototype.toString.call(e).indexOf("[object "))},isValueLike:function(e){var t;if(i(e))return!0;if(void 0!==(t=e[o.for("can.isValueLike")]))return t;var n=e[o.for("can.getValue")];return void 0!==n?!!n:void 0},isSymbolLike:p,isMoreListLikeThanMapLike:function(e){if(Array.isArray(e))return!0;if(e instanceof Array)return!0;if(null==e)return!1;var t=e[o.for("can.isMoreListLikeThanMapLike")];if(void 0!==t)return t;var n=this.isListLike(e),r=this.isMapLike(e);return!(!n||r)||!(!n&&r)&&void 0},isIteratorLike:function(e){return e&&"object"==typeof e&&"function"==typeof e.next&&0===e.next.length},isPromise:function(e){return e instanceof Promise||"[object Promise]"===Object.prototype.toString.call(e)},isPlainObject:d}}),define("can-reflect/reflections/call/call",["require","exports","module","can-symbol","can-reflect/reflections/type/type"],function(e,t,n){"use strict";var i=e("can-symbol"),o=e("can-reflect/reflections/type/type");n.exports={call:function(e,t){var n=[].slice.call(arguments,2),r=e[i.for("can.apply")];return r?r.call(e,t,n):e.apply(t,n)},apply:function(e,t,n){var r=e[i.for("can.apply")];return r?r.call(e,t,n):e.apply(t,n)},new:function(e){var t=[].slice.call(arguments,1),n=e[i.for("can.new")];if(n)return n.apply(e,t);var r=Object.create(e.prototype),a=e.apply(r,t);return o.isPrimitive(a)?r:a}}}),define("can-reflect/reflections/get-set/get-set",["require","exports","module","can-symbol","can-reflect/reflections/type/type"],function(e,t,n){"use strict";var s=e("can-symbol"),a=e("can-reflect/reflections/type/type"),i=s.for("can.setKeyValue"),r=s.for("can.getKeyValue"),o=s.for("can.getValue"),c=s.for("can.setValue"),u={setKeyValue:function(e,t,n){if(a.isSymbolLike(t))"symbol"==typeof t?e[t]=n:Object.defineProperty(e,t,{enumerable:!1,configurable:!0,value:n,writable:!0});else{var r=e[i];if(void 0!==r)return r.call(e,t,n);e[t]=n}},getKeyValue:function(e,t){var n=e[r];return n?n.call(e,t):e[t]},deleteKeyValue:function(e,t){var n=e[s.for("can.deleteKeyValue")];if(n)return n.call(e,t);delete e[t]},getValue:function(e){if(a.isPrimitive(e))return e;var t=e[o];return t?t.call(e):e},setValue:function(e,t){var n=e&&e[c];if(n)return n.call(e,t);throw new Error("can-reflect.setValue - Can not set value.")},splice:function(e,t,n,r){var a;if("number"!=typeof n){var i=e[s.for("can.updateValues")];if(i)return i.call(e,t,n,r);a=n.length}else a=n;arguments.length<=3&&(r=[]);var o=e[s.for("can.splice")];return o?o.call(e,t,a,r):[].splice.apply(e,[t,a].concat(r))},addValues:function(e,t,n){var r=e[s.for("can.addValues")];return r?r.call(e,t,n):Array.isArray(e)&&void 0===n?e.push.apply(e,t):u.splice(e,n,[],t)},removeValues:function(n,e,t){var r=n[s.for("can.removeValues")];return r?r.call(n,e,t):Array.isArray(n)&&void 0===t?void e.forEach(function(e){var t=n.indexOf(e);0<=t&&n.splice(t,1)}):u.splice(n,t,e,[])}};u.get=u.getKeyValue,u.set=u.setKeyValue,u.delete=u.deleteKeyValue,n.exports=u}),define("can-reflect/reflections/observe/observe",["require","exports","module","can-symbol"],function(e,t,n){"use strict";var s=e("can-symbol"),i=[].slice;function r(i,o){return function(e,t,n,r){var a=e[s.for(i)];return void 0!==a?a.call(e,t,n,r):this[o].apply(this,arguments)}}function a(r,a){return function(e){var t=e[s.for(r)];if(void 0===t)throw new Error(a);var n=i.call(arguments,1);return t.apply(e,n)}}n.exports={onKeyValue:r("can.onKeyValue","onEvent"),offKeyValue:r("can.offKeyValue","offEvent"),onKeys:a("can.onKeys","can-reflect: can not observe an onKeys event"),onKeysAdded:a("can.onKeysAdded","can-reflect: can not observe an onKeysAdded event"),onKeysRemoved:a("can.onKeysRemoved","can-reflect: can not unobserve an onKeysRemoved event"),getKeyDependencies:a("can.getKeyDependencies","can-reflect: can not determine dependencies"),getWhatIChange:a("can.getWhatIChange","can-reflect: can not determine dependencies"),getChangesDependencyRecord:function(e){var t=e[s.for("can.getChangesDependencyRecord")];if("function"==typeof t)return t()},keyHasDependencies:a("can.keyHasDependencies","can-reflect: can not determine if this has key dependencies"),onValue:a("can.onValue","can-reflect: can not observe value change"),offValue:a("can.offValue","can-reflect: can not unobserve value change"),getValueDependencies:a("can.getValueDependencies","can-reflect: can not determine dependencies"),valueHasDependencies:a("can.valueHasDependencies","can-reflect: can not determine if value has dependencies"),onPatches:a("can.onPatches","can-reflect: can not observe patches on object"),offPatches:a("can.offPatches","can-reflect: can not unobserve patches on object"),onInstancePatches:a("can.onInstancePatches","can-reflect: can not observe onInstancePatches on Type"),offInstancePatches:a("can.offInstancePatches","can-reflect: can not unobserve onInstancePatches on Type"),onInstanceBoundChange:a("can.onInstanceBoundChange","can-reflect: can not observe bound state change in instances."),offInstanceBoundChange:a("can.offInstanceBoundChange","can-reflect: can not unobserve bound state change"),isBound:a("can.isBound","can-reflect: cannot determine if object is bound"),onEvent:function(e,t,n,r){if(e){var a=e[s.for("can.onEvent")];if(void 0!==a)return a.call(e,t,n,r);e.addEventListener&&e.addEventListener(t,n,r)}},offEvent:function(e,t,n,r){if(e){var a=e[s.for("can.offEvent")];if(void 0!==a)return a.call(e,t,n,r);e.removeEventListener&&e.removeEventListener(t,n,r)}},setPriority:function(e,t){if(e){var n=e[s.for("can.setPriority")];if(void 0!==n)return n.call(e,t),!0}return!1},getPriority:function(e){if(e){var t=e[s.for("can.getPriority")];if(void 0!==t)return t.call(e)}}}}),define("can-reflect/reflections/shape/shape",["require","exports","module","can-symbol","can-reflect/reflections/get-set/get-set","can-reflect/reflections/type/type","can-reflect/reflections/helpers"],function(e,t,n){"use strict";var r,s=e("can-symbol"),f=e("can-reflect/reflections/get-set/get-set"),d=e("can-reflect/reflections/type/type"),a=e("can-reflect/reflections/helpers"),i=!0;try{Object.getPrototypeOf(1)}catch(e){i=!1}if("function"==typeof Map)r=Map;else{(r=function(){this.contents=[]}).prototype={_getIndex:function(e){for(var t;-1!==(t=this.contents.indexOf(e,t))&&t%2!=0;);return t},has:function(e){return-1!==this._getIndex(e)},get:function(e){var t=this._getIndex(e);if(-1!==t)return this.contents[t+1]},set:function(e,t){var n=this._getIndex(e);-1!==n?this.contents[n+1]=t:(this.contents.push(e),this.contents.push(t))},delete:function(e){var t=this._getIndex(e);-1!==t&&this.contents.splice(t,2)}}}var c,o,u,l=Object.prototype.hasOwnProperty,p=function(t){return function(){var e=[this];return e.push.apply(e,arguments),t.apply(null,e)}},h=s.for("can.getKeyValue"),v=p(f.getKeyValue),y=s.for("can.setKeyValue"),g=p(f.setKeyValue),m=s.for("can.size"),b=a.makeGetFirstSymbolValue(["can.updateDeep","can.assignDeep","can.setKeyValue"]),w=function(e){return d.isPlainObject(e)||Array.isArray(e)||!!b(e)};function x(e){return!!d.isPrimitive(e)||!b(e)&&(d.isBuiltIn(e)&&!d.isPlainObject(e)&&!Array.isArray(e))}try{Object.keys(1),o=Object.keys}catch(e){o=function(e){return d.isPrimitive(e)?[]:Object.keys(e)}}function _(c,u){var n=null;function l(e){var t;this.first=!n,this.first&&(n={unwrap:new(t=e||r),serialize:new t,isSerializing:{unwrap:new t,serialize:new t},circularReferenceIsSerializing:{unwrap:new t,serialize:new t}}),this.map=n,this.result=null}return l.prototype.end=function(){return this.first&&(n=null),this.result},function(e,t){if(x(e))return e;var n=new l(t);if(d.isValueLike(e))n.result=this[c](f.getValue(e));else{var r=d.isIteratorLike(e)||d.isMoreListLikeThanMapLike(e);if(n.result=r?[]:{},n.map[c].has(e))return n.map.isSerializing[c].has(e)&&n.map.circularReferenceIsSerializing[c].set(e,!0),n.map[c].get(e);n.map[c].set(e,n.result);for(var a=0,i=u.length;a<i;a++){var o=e[u[a]];if(o){n.map.isSerializing[c].set(e,!0);var s=n.result;if(n.result=o.call(e,s),n.map.isSerializing[c].delete(e),n.result!==s){if(n.map.circularReferenceIsSerializing[c].has(e))throw n.end(),new Error("Cannot serialize cirular reference!");n.map[c].set(e,n.result)}return n.end()}}"function"==typeof obj?(n.map[c].set(e,e),n.result=e):r?this.eachIndex(e,function(e,t){n.result[t]=this[c](e)},this):this.eachKey(e,function(e,t){n.result[t]=this[c](e)},this)}return n.end()}}u="undefined"!=typeof Map?function(e){var t=new Map;return c.eachIndex(e,function(e){t.set(e,!0)}),t}:function(e){var n={};return e.forEach(function(e){n[e]=!0}),{get:function(e){return n[e]},set:function(e,t){n[e]=t},keys:function(){return e}}};var k=function(e){var t=e[s.for("can.hasOwnKey")];if(t)return t.bind(e);var n=u(c.getOwnEnumerableKeys(e));return function(e){return n.get(e)}};function O(e,t){var n=e[e.length-1];if(n&&n.deleteCount===n.insert.length&&t.index-n.index===n.deleteCount)return n.insert.push.apply(n.insert,t.insert),void(n.deleteCount+=t.deleteCount);e.push(t)}function E(r,e,a){var i=this.toArray(e),o=[],s=-1;this.eachIndex(r,function(e,t){if((s=t)>=i.length)return a||O(o,{index:t,deleteCount:r.length-t+1,insert:[]}),!1;var n=i[t];d.isPrimitive(e)||d.isPrimitive(n)||!1===w(e)?O(o,{index:t,deleteCount:1,insert:[n]}):!0===a?this.assignDeep(e,n):this.updateDeep(e,n)},this),i.length>s&&O(o,{index:s+1,deleteCount:0,insert:i.slice(s+1)});for(var t=0,n=o.length;t<n;t++){var c=o[t];f.splice(r,c.index,c.deleteCount,c.insert)}return r}(c={each:function(e,t,n){return d.isIteratorLike(e)||d.isMoreListLikeThanMapLike(e)?c.eachIndex(e,t,n):c.eachKey(e,t,n)},eachIndex:function(e,t,n){if(Array.isArray(e))return c.eachListLike(e,t,n);var r,a=e[s.iterator];if(d.isIteratorLike(e)?r=e:a&&(r=a.call(e)),r)for(var i,o=0;!(i=r.next()).done&&!1!==t.call(n||e,i.value,o++,e););else c.eachListLike(e,t,n);return e},eachListLike:function(e,t,n){var r=-1,a=e.length;if(void 0===a){var i=e[m];if(!i)throw new Error("can-reflect: unable to iterate.");a=i.call(e)}for(;++r<a;){var o=e[r];if(!1===t.call(n||o,o,r,e))break}return e},toArray:function(e){var t=[];return c.each(e,function(e){t.push(e)}),t},eachKey:function(n,r,a){if(n){var e=c.getOwnEnumerableKeys(n),i=n[h]||v;return c.eachIndex(e,function(e){var t=i.call(n,e);return r.call(a||n,t,e,n)})}return n},hasOwnKey:function(e,t){var n=e[s.for("can.hasOwnKey")];if(n)return n.call(e,t);var r=e[s.for("can.getOwnKeys")];if(r){var a=!1;return c.eachIndex(r.call(e),function(e){if(e===t)return!(a=!0)}),a}return l.call(e,t)},getOwnEnumerableKeys:function(t){var e=t[s.for("can.getOwnEnumerableKeys")];if(e)return e.call(t);if(t[s.for("can.getOwnKeys")]&&t[s.for("can.getOwnKeyDescriptor")]){var n=[];return c.eachIndex(c.getOwnKeys(t),function(e){c.getOwnKeyDescriptor(t,e).enumerable&&n.push(e)},this),n}return o(t)},getOwnKeys:function(e){var t=e[s.for("can.getOwnKeys")];return t?t.call(e):Object.getOwnPropertyNames(e)},getOwnKeyDescriptor:function(e,t){var n=e[s.for("can.getOwnKeyDescriptor")];return n?n.call(e,t):Object.getOwnPropertyDescriptor(e,t)},unwrap:_("unwrap",[s.for("can.unwrap")]),serialize:_("serialize",[s.for("can.serialize"),s.for("can.unwrap")]),assignMap:function(n,e){var r=k(n),a=n[h]||v,i=n[y]||g;return c.eachKey(e,function(e,t){r(t)&&a.call(n,t)===e||i.call(n,t,e)}),n},assignList:function(e,t){var n=c.toArray(t);return f.splice(e,0,n,n),e},assign:function(e,t){return d.isIteratorLike(t)||d.isMoreListLikeThanMapLike(t)?c.assignList(e,t):c.assignMap(e,t),e},assignDeepMap:function(r,e){var a=k(r),i=r[h]||v,o=r[y]||g;return c.eachKey(e,function(e,t){if(a(t)){var n=i.call(r,t);e===n||(d.isPrimitive(n)||d.isPrimitive(e)||!1===w(n)?o.call(r,t,e):c.assignDeep(n,e))}else f.setKeyValue(r,t,e)},this),r},assignDeepList:function(e,t){return E.call(this,e,t,!0)},assignDeep:function(e,t){var n=e[s.for("can.assignDeep")];return n?n.call(e,t):d.isMoreListLikeThanMapLike(t)?c.assignDeepList(e,t):c.assignDeepMap(e,t),e},updateMap:function(r,a){var i=u(c.getOwnEnumerableKeys(a)),o=a[h]||v,s=r[y]||g;return c.eachKey(r,function(e,t){if(i.get(t)){i.set(t,!1);var n=o.call(a,t);n!==e&&s.call(r,t,n)}else f.deleteKeyValue(r,t)},this),c.eachIndex(i.keys(),function(e){i.get(e)&&s.call(r,e,o.call(a,e))}),r},updateList:function(e,t){var n=c.toArray(t);return f.splice(e,0,e,n),e},update:function(e,t){return d.isIteratorLike(t)||d.isMoreListLikeThanMapLike(t)?c.updateList(e,t):c.updateMap(e,t),e},updateDeepMap:function(r,a){var i=u(c.getOwnEnumerableKeys(a)),o=a[h]||v,s=r[y]||g;return c.eachKey(r,function(e,t){if(i.get(t)){i.set(t,!1);var n=o.call(a,t);d.isPrimitive(e)||d.isPrimitive(n)||!1===w(e)?s.call(r,t,n):c.updateDeep(e,n)}else f.deleteKeyValue(r,t)},this),c.eachIndex(i.keys(),function(e){i.get(e)&&s.call(r,e,o.call(a,e))}),r},updateDeepList:function(e,t){return E.call(this,e,t)},updateDeep:function(e,t){var n=e[s.for("can.updateDeep")];return n?n.call(e,t):d.isMoreListLikeThanMapLike(t)?c.updateDeepList(e,t):c.updateDeepMap(e,t),e},hasKey:function(e,t){if(null==e)return!1;var n;if(d.isPrimitive(e))return!!l.call(e,t)||(void 0!==(n=i?Object.getPrototypeOf(e):e.__proto__)?t in n:void 0!==e[t]);var r=e[s.for("can.hasKey")];return r?r.call(e,t):c.hasOwnKey(e,t)||t in e},getAllEnumerableKeys:function(){},getAllKeys:function(){},assignSymbols:function(r,e){return c.eachKey(e,function(e,t){var n=d.isSymbolLike(s[t])?s[t]:s.for(t);f.setKeyValue(r,n,e)}),r},isSerialized:x,size:function(e){if(null==e)return 0;var t=e[m],n=0;return t?t.call(e):a.hasLength(e)?e.length:d.isListLike(e)?(c.eachIndex(e,function(){n++}),n):e?c.getOwnEnumerableKeys(e).length:void 0},defineInstanceKey:function(e,t,n){var r=e[s.for("can.defineInstanceKey")];if(r)return r.call(e,t,n);var a=e.prototype;(r=a[s.for("can.defineInstanceKey")])?r.call(a,t,n):Object.defineProperty(a,t,c.assign({configurable:!0,enumerable:!d.isSymbolLike(t),writable:!0},n))}}).isSerializable=c.isSerialized,c.keys=c.getOwnEnumerableKeys,n.exports=c}),define("can-reflect/reflections/shape/schema/schema",["require","exports","module","can-symbol","can-reflect/reflections/type/type","can-reflect/reflections/get-set/get-set","can-reflect/reflections/shape/shape"],function(e,t,n){"use strict";var r=e("can-symbol"),s=e("can-reflect/reflections/type/type"),a=e("can-reflect/reflections/get-set/get-set"),i=e("can-reflect/reflections/shape/shape"),o=r.for("can.getSchema"),c=r.for("can.isMember"),u=r.for("can.new");function l(e,t){return e.localeCompare(t)}var f={getSchema:function(e){if(void 0!==e){var t=e[o];return void 0===t&&(t=(e=e.constructor)&&e[o]),void 0!==t?t.call(e):void 0}},getIdentity:function(t,e){if(void 0===(e=e||f.getSchema(t)))throw new Error("can-reflect.getIdentity - Unable to find a schema for the given value.");var n=e.identity;if(n&&0!==n.length){if(1===n.length)return a.getKeyValue(t,n[0]);var r={};return n.forEach(function(e){r[e]=a.getKeyValue(t,e)}),JSON.stringify(f.cloneKeySort(r))}throw new Error("can-reflect.getIdentity - Provided schema lacks an identity property.")},cloneKeySort:function(e){return function t(n){return s.isPrimitive(n)?n:s.isListLike(n)?(r=[],i.eachKey(n,function(e){r.push(t(e))}),r):s.isMapLike(n)?(r={},i.getOwnKeys(n).sort(l).forEach(function(e){r[e]=t(a.getKeyValue(n,e))}),r):n;var r}(e)},convert:function(e,t){if((n=t)===Number||n===String||n===Boolean)return t(e);var n,r=t[c],a=!1,i=typeof t,o=t[u];if(void 0!==r?a=r.call(t,e):"function"===i&&s.isConstructorLike(t)&&(a=e instanceof t),a)return e;if(void 0!==o)return o.call(t,e);if("function"===i)return s.isConstructorLike(t)?new t(e):t(e);throw new Error("can-reflect: Can not convert values into type. Type must provide `can.new` symbol.")}};n.exports=f}),define("can-reflect/reflections/get-name/get-name",["require","exports","module","can-symbol","can-reflect/reflections/type/type"],function(e,t,n){"use strict";var r=e("can-symbol"),i=e("can-reflect/reflections/type/type"),o=r.for("can.getName");var s=0;n.exports={setName:function(e,t){if("function"!=typeof t){var n=t;t=function(){return n}}Object.defineProperty(e,o,{value:t})},getName:function e(t){var n=typeof t;if(null===t||"object"!==n&&"function"!==n)return""+t;var r=t[o];if(r)return r.call(t);if("function"===n)return"name"in t||(t.name="functionIE"+s++),t.name;if(t.constructor&&t!==t.constructor){var a=e(t.constructor);if(a){if(i.isValueLike(t))return a+"<>";if(i.isMoreListLikeThanMapLike(t))return a+"[]";if(i.isMapLike(t))return a+"{}"}}}}}),define("can-reflect/types/map",["require","exports","module","can-reflect/reflections/shape/shape","can-symbol"],function(e,t,n){"use strict";var r=e("can-reflect/reflections/shape/shape"),a=e("can-symbol");"undefined"!=typeof Map&&(r.assignSymbols(Map.prototype,{"can.getOwnEnumerableKeys":Map.prototype.keys,"can.setKeyValue":Map.prototype.set,"can.getKeyValue":Map.prototype.get,"can.deleteKeyValue":Map.prototype.delete,"can.hasOwnKey":Map.prototype.has}),"function"!=typeof Map.prototype.keys&&(Map.prototype.keys=Map.prototype[a.for("can.getOwnEnumerableKeys")]=function(){var n=[],e=0;return this.forEach(function(e,t){n.push(t)}),{next:function(){return{value:n[e],done:e++===n.length}}}})),"undefined"!=typeof WeakMap&&r.assignSymbols(WeakMap.prototype,{"can.getOwnEnumerableKeys":function(){throw new Error("can-reflect: WeakMaps do not have enumerable keys.")},"can.setKeyValue":WeakMap.prototype.set,"can.getKeyValue":WeakMap.prototype.get,"can.deleteKeyValue":WeakMap.prototype.delete,"can.hasOwnKey":WeakMap.prototype.has})}),define("can-reflect/types/set",["require","exports","module","can-reflect/reflections/shape/shape","can-symbol"],function(e,t,n){"use strict";var r=e("can-reflect/reflections/shape/shape"),a=e("can-symbol");"undefined"!=typeof Set&&(r.assignSymbols(Set.prototype,{"can.isMoreListLikeThanMapLike":!0,"can.updateValues":function(e,t,n){t!==n&&r.each(t,function(e){this.delete(e)},this),r.each(n,function(e){this.add(e)},this)},"can.size":function(){return this.size}}),"function"!=typeof Set.prototype[a.iterator]&&(Set.prototype[a.iterator]=function(){var t=[],e=0;return this.forEach(function(e){t.push(e)}),{next:function(){return{value:t[e],done:e++===t.length}}}})),"undefined"!=typeof WeakSet&&r.assignSymbols(WeakSet.prototype,{"can.isListLike":!0,"can.isMoreListLikeThanMapLike":!0,"can.updateValues":function(e,t,n){t!==n&&r.each(t,function(e){this.delete(e)},this),r.each(n,function(e){this.add(e)},this)},"can.size":function(){throw new Error("can-reflect: WeakSets do not have enumerable keys.")}})}),define("can-reflect",["require","exports","module","can-reflect/reflections/call/call","can-reflect/reflections/get-set/get-set","can-reflect/reflections/observe/observe","can-reflect/reflections/shape/shape","can-reflect/reflections/shape/schema/schema","can-reflect/reflections/type/type","can-reflect/reflections/get-name/get-name","can-namespace","can-reflect/types/map","can-reflect/types/set"],function(e,t,n){"use strict";var r=e("can-reflect/reflections/call/call"),a=e("can-reflect/reflections/get-set/get-set"),i=e("can-reflect/reflections/observe/observe"),o=e("can-reflect/reflections/shape/shape"),s=e("can-reflect/reflections/shape/schema/schema"),c=e("can-reflect/reflections/type/type"),u=e("can-reflect/reflections/get-name/get-name"),l=e("can-namespace"),f={};[r,a,i,o,c,u,s].forEach(function(e){for(var t in e)f[t]=e[t]}),e("can-reflect/types/map"),e("can-reflect/types/set"),n.exports=l.Reflect=f}),define("can-globals/can-globals-proto",["require","exports","module","can-reflect"],function(s,e,t){!function(e,t,n,r){"use strict";var a=s("can-reflect");function i(e){var t=this.eventHandlers[e];if(t)for(var n=t.slice(),r=this.getKeyValue(e),a=0;a<n.length;a++)n[a](r)}function o(){this.eventHandlers={},this.properties={}}o.prototype.define=function(e,t,n){return void 0===n&&(n=!0),this.properties[e]||(this.properties[e]={default:t,value:t,enableCache:n}),this},o.prototype.getKeyValue=function(e){var t=this.properties[e];if(t)return"function"==typeof t.value?t.cachedValue?t.cachedValue:t.enableCache?(t.cachedValue=t.value(),t.cachedValue):t.value():t.value},o.prototype.makeExport=function(t){return function(e){return 0===arguments.length?this.getKeyValue(t):null!=e?("function"==typeof e?this.setKeyValue(t,function(){return e}):this.setKeyValue(t,e),e):void this.deleteKeyValue(t)}.bind(this)},o.prototype.offKeyValue=function(e,t){if(this.properties[e]){var n=this.eventHandlers[e];if(n){var r=n.indexOf(t);n.splice(r,1)}}return this},o.prototype.onKeyValue=function(e,t){return this.properties[e]&&(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(t)),this},o.prototype.deleteKeyValue=function(e){var t=this.properties[e];return void 0!==t&&(t.value=t.default,t.cachedValue=void 0,i.call(this,e)),this},o.prototype.setKeyValue=function(e,t){if(!this.properties[e])return this.define(e,t);var n=this.properties[e];return n.value=t,n.cachedValue=void 0,i.call(this,e),this},o.prototype.reset=function(){for(var e in this.properties)this.properties.hasOwnProperty(e)&&(this.properties[e].value=this.properties[e].default,this.properties[e].cachedValue=void 0,i.call(this,e));return this},a.assignSymbols(o.prototype,{"can.getKeyValue":o.prototype.getKeyValue,"can.setKeyValue":o.prototype.setKeyValue,"can.deleteKeyValue":o.prototype.deleteKeyValue,"can.onKeyValue":o.prototype.onKeyValue,"can.offKeyValue":o.prototype.offKeyValue}),r.exports=o}(0,0,0,t)}),define("can-globals/can-globals-instance",["require","exports","module","can-namespace","can-globals/can-globals-proto"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-namespace"),i=new(t("can-globals/can-globals-proto"));if(a.globals)throw new Error("You can't have two versions of can-globals, check your dependencies");r.exports=a.globals=i}(0,e,0,n)}),define("can-globals/global/global",["require","exports","module","can-globals/can-globals-instance"],function(i,e,t){!function(e,t,n,r){"use strict";var a=i("can-globals/can-globals-instance");a.define("global",function(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:"object"==typeof process&&"[object process]"==={}.toString.call(process)?e:window}),r.exports=a.makeExport("global")}(function(){return this}(),0,0,t)}),define("can-globals/document/document",["require","exports","module","can-globals/global/global","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,r){"use strict";t("can-globals/global/global");var a=t("can-globals/can-globals-instance");a.define("document",function(){return a.getKeyValue("global").document}),r.exports=a.makeExport("document")}(0,e,0,n)}),define("can-globals/location/location",["require","exports","module","can-globals/global/global","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,r){"use strict";t("can-globals/global/global");var a=t("can-globals/can-globals-instance");a.define("location",function(){return a.getKeyValue("global").location}),r.exports=a.makeExport("location")}(0,e,0,n)}),define("can-globals/mutation-observer/mutation-observer",["require","exports","module","can-globals/global/global","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,r){"use strict";t("can-globals/global/global");var a=t("can-globals/can-globals-instance");a.define("MutationObserver",function(){var e=a.getKeyValue("global");return e.MutationObserver||e.WebKitMutationObserver||e.MozMutationObserver}),r.exports=a.makeExport("MutationObserver")}(0,e,0,n)}),define("can-globals/is-node/is-node",["require","exports","module","can-globals/can-globals-instance"],function(i,e,t){!function(e,t,n,r){"use strict";var a=i("can-globals/can-globals-instance");a.define("isNode",function(){return"object"==typeof process&&"[object process]"==={}.toString.call(process)}),r.exports=a.makeExport("isNode")}(0,0,0,t)}),define("can-globals/is-browser-window/is-browser-window",["require","exports","module","can-globals/can-globals-instance","can-globals/is-node/is-node"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-globals/can-globals-instance");t("can-globals/is-node/is-node"),a.define("isBrowserWindow",function(){var e=a.getKeyValue("isNode");return"undefined"!=typeof window&&"undefined"!=typeof document&&!1===e}),r.exports=a.makeExport("isBrowserWindow")}(0,e,0,n)}),define("can-globals/custom-elements/custom-elements",["require","exports","module","can-globals/global/global","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,r){"use strict";t("can-globals/global/global");var a=t("can-globals/can-globals-instance");a.define("customElements",function(){return a.getKeyValue("global").customElements}),r.exports=a.makeExport("customElements")}(0,e,0,n)}),define("can-globals",["require","exports","module","can-globals/can-globals-instance","can-globals/global/global","can-globals/document/document","can-globals/location/location","can-globals/mutation-observer/mutation-observer","can-globals/is-browser-window/is-browser-window","can-globals/is-node/is-node","can-globals/custom-elements/custom-elements"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-globals/can-globals-instance");t("can-globals/global/global"),t("can-globals/document/document"),t("can-globals/location/location"),t("can-globals/mutation-observer/mutation-observer"),t("can-globals/is-browser-window/is-browser-window"),t("can-globals/is-node/is-node"),t("can-globals/custom-elements/custom-elements"),r.exports=a}(0,e,0,n)}),define("can-debug/src/proxy-namespace",function(e,t,i){!function(e,t,n,r){"use strict";var a=!1;i.exports=function(e){return new Proxy(e,{get:function(e,t){return a||(console.warn("Warning: use of 'can' global should be for debugging purposes only."),a=!0),e[t]}})}}()}),define("can-debug/src/temporarily-bind",["require","exports","module","can-symbol","can-reflect"],function(e,t,n){"use strict";var r=e("can-symbol"),l=e("can-reflect"),f=r.for("can.onValue"),d=r.for("can.offValue"),p=r.for("can.onKeyValue"),h=r.for("can.offKeyValue"),v=function(){};function y(e){return"function"==typeof e}n.exports=function(u){return function(e,t){var n,r,a,i,o,s,c;return 2===arguments.length?(o=t,s=u,y((i=e)[p])&&l.onKeyValue(i,o,v),c=s(i,o),y(i[h])&&l.offKeyValue(i,o,v),c):(r=u,y((n=e)[f])&&l.onValue(n,v),a=r(n),y(n[d])&&l.offValue(n,v),a)}}}),define("can-assign",["require","exports","module","can-namespace"],function(e,t,n){var r=e("can-namespace");n.exports=r.assign=function(e,t){for(var n in t){var r=Object.getOwnPropertyDescriptor(e,n);r&&!1===r.writable||(e[n]=t[n])}return e}}),define("can-debug/src/graph/graph",["require","exports","module","can-assign"],function(e,t,n){"use strict";var o=e("can-assign");function i(){this.nodes=[],this.arrows=new Map,this.arrowsMeta=new Map}function r(e,t,n,r){var a=e.arrowsMeta.get(t);if(a){var i=a.get(n);i||(i={}),a.set(n,o(i,r))}else(a=new Map).set(n,r),e.arrowsMeta.set(t,a)}i.prototype.addNode=function(e){this.nodes.push(e),this.arrows.set(e,new Set)},i.prototype.addArrow=function(e,t,n){this.arrows.get(e).add(t),n&&r(this,e,t,n)},i.prototype.hasArrow=function(e,t){return this.getNeighbors(e).has(t)},i.prototype.getArrowMeta=function(e,t){return this.arrowsMeta.get(e)&&this.arrowsMeta.get(e).get(t)},i.prototype.setArrowMeta=function(e,t,n){r(this,e,t,n)},i.prototype.getNeighbors=function(e){return this.arrows.get(e)},i.prototype.findNode=function(e){var t,n,r=null;for(t=0;t<this.nodes.length;t++)if(e(n=this.nodes[t])){r=n;break}return r},i.prototype.bfs=function(e){var t=this.nodes[0],n=[t],r=new Map;for(r.set(t,!0);n.length;)e(t=n.shift()),this.arrows.get(t).forEach(function(e){r.has(e)||(n.push(e),r.set(e,!0))})},i.prototype.dfs=function(e){for(var t=this.nodes[0],n=[t],r=new Map;n.length;)e(t=n.pop()),r.has(t)||(r.set(t,!0),this.arrows.get(t).forEach(function(e){n.push(e)}))},i.prototype.reverse=function(){var r=this,a=new i;return r.nodes.forEach(a.addNode.bind(a)),r.nodes.forEach(function(n){r.getNeighbors(n).forEach(function(e){var t=r.getArrowMeta(n,e);a.addArrow(e,n,t)})}),a},n.exports=i}),define("can-debug/src/get-graph/make-node",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var a=e("can-reflect");n.exports=function(e,t){var n=2===arguments.length,r={obj:e,name:a.getName(e),value:n?a.getKeyValue(e,t):a.getValue(e)};return n&&(r.key=t),r}}),define("can-reflect-dependencies/src/add-mutated-by",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var c=e("can-reflect"),u=function(){return{keyDependencies:new Map,valueDependencies:new Set}};n.exports=function(s){return function(e,t,n){var r=3===arguments.length;if(2===arguments.length&&(n=t,t=void 0),!n.keyDependencies&&!n.valueDependencies){var a=new Set;a.add(n),n={valueDependencies:a}}var i=s.get(e);i||(i={mutateDependenciesForKey:new Map,mutateDependenciesForValue:u()},s.set(e,i)),r&&!i.mutateDependenciesForKey.get(t)&&i.mutateDependenciesForKey.set(t,u());var o=r?i.mutateDependenciesForKey.get(t):i.mutateDependenciesForValue;n.valueDependencies&&c.addValues(o.valueDependencies,n.valueDependencies),n.keyDependencies&&c.each(n.keyDependencies,function(e,t){var n=o.keyDependencies.get(t);n||(n=new Set,o.keyDependencies.set(t,n)),c.addValues(n,e)})}}}),define("can-reflect-dependencies/src/delete-mutated-by",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var c=e("can-reflect");n.exports=function(s){return function(e,t,n){var r=3===arguments.length,a=s.get(e);if(2===arguments.length&&(n=t,t=void 0),!n.keyDependencies&&!n.valueDependencies){var i=new Set;i.add(n),n={valueDependencies:i}}var o=r?a.mutateDependenciesForKey.get(t):a.mutateDependenciesForValue;n.valueDependencies&&c.removeValues(o.valueDependencies,n.valueDependencies),n.keyDependencies&&c.each(n.keyDependencies,function(e,t){var n=o.keyDependencies.get(t);n&&(c.removeValues(n,e),n.size||o.keyDependencies.delete(t))})}}}),define("can-reflect-dependencies/src/is-function",function(e,t,n){"use strict";n.exports=function(e){return"function"==typeof e}}),define("can-reflect-dependencies/src/get-dependency-data-of",["require","exports","module","can-symbol","can-reflect","can-reflect-dependencies/src/is-function","can-assign"],function(e,t,n){"use strict";var r=e("can-symbol"),l=e("can-reflect"),f=e("can-reflect-dependencies/src/is-function"),d=e("can-assign"),a=r.for("can.getWhatIChange"),p=r.for("can.getKeyDependencies"),h=r.for("can.getValueDependencies"),o=function(e,t){if(f(e[a]))return 2===arguments.length?l.getWhatIChange(e,t):l.getWhatIChange(e)},v=function(e){return null==e||!Object.keys(e).length||e.keyDependencies&&!e.keyDependencies.size&&e.valueDependencies&&!e.valueDependencies.size},s=function(e,t,n){var r,a,i,o,s=3===arguments.length,c=s?(r=t,a=n,(o=e.get(r))&&o.mutateDependenciesForKey.has(a)&&(i=o.mutateDependenciesForKey.get(a)),i):function(e,t){var n,r=e.get(t);if(r){var a=r.mutateDependenciesForValue;a.keyDependencies.size&&((n=n||{}).keyDependencies=a.keyDependencies),a.valueDependencies.size&&((n=n||{}).valueDependencies=a.valueDependencies)}return n}(e,t),u=s?function(e,t){if(f(e[p]))return l.getKeyDependencies(e,t)}(t,n):function(e){if(f(e[h]))return l.getValueDependencies(e)}(t);if(!v(c)||!v(u))return d(d({},c?{mutate:c}:null),u?{derive:u}:null)};n.exports=function(i){return function(e,t){var n=2===arguments.length,r=n?s(i,e,t):s(i,e),a=n?o(e,t):o(e);if(r||a)return d(d({},a?{whatIChange:a}:null),r?{whatChangesMe:r}:null)}}}),define("can-reflect-dependencies",["require","exports","module","can-reflect-dependencies/src/add-mutated-by","can-reflect-dependencies/src/delete-mutated-by","can-reflect-dependencies/src/get-dependency-data-of"],function(e,t,n){"use strict";var r=e("can-reflect-dependencies/src/add-mutated-by"),a=e("can-reflect-dependencies/src/delete-mutated-by"),i=e("can-reflect-dependencies/src/get-dependency-data-of"),o=new WeakMap;n.exports={addMutatedBy:r(o),deleteMutatedBy:a(o),getDependencyDataOf:i(o)}}),define("can-debug/src/get-graph/get-graph",["require","exports","module","can-debug/src/graph/graph","can-debug/src/get-graph/make-node","can-reflect","can-reflect-dependencies"],function(e,t,n){"use strict";var a=e("can-debug/src/graph/graph"),p=e("can-debug/src/get-graph/make-node"),h=e("can-reflect"),v=e("can-reflect-dependencies");n.exports=function(e,t){var c=0,u=new a,n=2===arguments.length,l=function(e,t,n,r){switch(e){case"whatIChange":u.addArrow(t,n,r);break;case"whatChangesMe":u.addArrow(n,t,r);break;default:throw new Error("Unknown direction value: ",r.direction)}},f=function(e,n,r){h.eachKey(e.keyDependencies||{},function(e,t){h.each(e,function(e){r(t,n,e)})})},d=function(e,t,n){h.eachIndex(e.valueDependencies||[],function(e){n(e,t)})},r=function n(t,e,r){var a,i=3===arguments.length,o=u.findNode(function(e){return i?e.obj===t&&e.key===r:e.obj===t});if(o)return e.parent&&l(e.direction,e.parent,o,{kind:e.kind,direction:e.direction}),u;c+=1,(o=i?p(t,r):p(t)).order=c,u.addNode(o),e.parent&&l(e.direction,e.parent,o,{kind:e.kind,direction:e.direction});var s=i?v.getDependencyDataOf(t,r):v.getDependencyDataOf(t);return s&&s.whatIChange&&(a={direction:"whatIChange",parent:o},h.eachKey(s.whatIChange,function(e,t){a.kind=t,f(e,a,n),d(e,a,n)})),s&&s.whatChangesMe&&(a={direction:"whatChangesMe",parent:o},h.eachKey(s.whatChangesMe,function(e,t){a.kind=t,f(e,a,n),d(e,a,n)})),u};return n?r(e,{},t):r(e,{})}}),define("can-debug/src/format-graph/format-graph",["require","exports","module","can-reflect","can-assign"],function(e,t,n){"use strict";var r=e("can-reflect"),u=e("can-assign");n.exports=function(o){var s=new Map;o.nodes.forEach(function(e,t){s.set(e,t+1)});var e=o.nodes.map(function(e){return{shape:"box",id:s.get(e),label:r.getName(e.obj)+(e.key?"."+e.key:"")}}),t=new Map,c=[];return o.nodes.forEach(function(e){var i=function(r){if(!t.has(r)){t.set(r,!0);var e=o.arrows.get(r),a=s.get(r);e.forEach(function(e){var t=s.get(e),n=o.arrowsMeta.get(r).get(e);c.push(u({from:a,to:t},{derive:{arrows:"to"},mutate:{arrows:"to",dashes:!0}}[n.kind])),i(e)})}};i(e)}),{nodes:e,edges:c}}}),define("can-debug/src/log-data/log-data",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var i=e("can-reflect");n.exports=function e(t){var n,r=t.node,a=[r.name,"key"in r?"."+r.key:""];console.group(a.join("")),console.log("value ","string"==typeof(n=r.value)?JSON.stringify(n):n),console.log("object ",r.obj),t.derive.length&&(console.group("DERIVED FROM"),i.eachIndex(t.derive,e),console.groupEnd()),t.mutations.length&&(console.group("MUTATED BY"),i.eachIndex(t.mutations,e),console.groupEnd()),t.twoWay.length&&(console.group("TWO WAY"),i.eachIndex(t.twoWay,e),console.groupEnd()),console.groupEnd()}}),define("can-debug/src/label-cycles/label-cycles",["require","exports","module","can-debug/src/graph/graph"],function(e,t,n){"use strict";var o=e("can-debug/src/graph/graph");n.exports=function(r){var a=new Map,i=new o;r.nodes.forEach(function(e){i.addNode(e)});return function t(n){a.set(n,!0),r.getNeighbors(n).forEach(function(e){a.has(e)?r.hasArrow(n,e)&&i.addArrow(e,n,{kind:"twoWay"}):(i.addArrow(n,e,r.getArrowMeta(n,e)),t(e))})}(r.nodes[0]),i}}),define("can-debug/src/get-data/get-data",["require","exports","module","can-debug/src/label-cycles/label-cycles"],function(e,t,n){"use strict";var a=e("can-debug/src/label-cycles/label-cycles");n.exports=function(e,t){var n,i=new Map,o=a("whatChangesMe"===t?e.reverse():e),r=function n(r){var a={node:r,derive:[],mutations:[],twoWay:[]};return i.set(r,!0),o.getNeighbors(r).forEach(function(e){var t=o.getArrowMeta(r,e);if(!i.has(e))switch(t.kind){case"twoWay":a.twoWay.push(n(e));break;case"derive":a.derive.push(n(e));break;case"mutate":a.mutations.push(n(e));break;default:throw new Error("Unknow meta.kind value: ",t.kind)}}),a}(o.nodes[0]);return(n=r).derive.length||n.mutations.length||n.twoWay.length?r:null}}),define("can-debug/src/what-i-change/what-i-change",["require","exports","module","can-debug/src/log-data/log-data","can-debug/src/get-data/get-data","can-debug/src/get-graph/get-graph"],function(e,t,n){"use strict";var a=e("can-debug/src/log-data/log-data"),i=e("can-debug/src/get-data/get-data"),o=e("can-debug/src/get-graph/get-graph");n.exports=function(e,t){var n=2===arguments.length,r=i(n?o(e,t):o(e),"whatIChange");r&&a(r)}}),define("can-debug/src/what-changes-me/what-changes-me",["require","exports","module","can-debug/src/log-data/log-data","can-debug/src/get-data/get-data","can-debug/src/get-graph/get-graph"],function(e,t,n){"use strict";var a=e("can-debug/src/log-data/log-data"),i=e("can-debug/src/get-data/get-data"),o=e("can-debug/src/get-graph/get-graph");n.exports=function(e,t){var n=2===arguments.length,r=i(n?o(e,t):o(e),"whatChangesMe");r&&a(r)}}),define("can-debug/src/get-what-i-change/get-what-i-change",["require","exports","module","can-debug/src/get-data/get-data","can-debug/src/get-graph/get-graph"],function(e,t,n){"use strict";var r=e("can-debug/src/get-data/get-data"),a=e("can-debug/src/get-graph/get-graph");n.exports=function(e,t){var n=2===arguments.length;return r(n?a(e,t):a(e),"whatIChange")}}),define("can-debug/src/get-what-changes-me/get-what-changes-me",["require","exports","module","can-debug/src/get-data/get-data","can-debug/src/get-graph/get-graph"],function(e,t,n){"use strict";var r=e("can-debug/src/get-data/get-data"),a=e("can-debug/src/get-graph/get-graph");n.exports=function(e,t){var n=2===arguments.length;return r(n?a(e,t):a(e),"whatChangesMe")}}),define("can-log",function(e,t,n){"use strict";t.warnTimeout=5e3,t.logLevel=0,t.warn=function(){this.logLevel<2&&("undefined"!=typeof console&&console.warn?this._logger("warn",Array.prototype.slice.call(arguments)):"undefined"!=typeof console&&console.log&&this._logger("log",Array.prototype.slice.call(arguments)))},t.log=function(){this.logLevel<1&&"undefined"!=typeof console&&console.log&&this._logger("log",Array.prototype.slice.call(arguments))},t.error=function(){this.logLevel<1&&"undefined"!=typeof console&&console.error&&this._logger("error",Array.prototype.slice.call(arguments))},t._logger=function(t,n){try{console[t].apply(console,n)}catch(e){console[t](n)}}}),define("can-log/dev/dev",["require","exports","module","can-log"],function(e,t,n){"use strict";var r=e("can-log");n.exports={warnTimeout:5e3,logLevel:0,stringify:function(e){return JSON.stringify(e,function(e,t){return void 0===t?"/* void(undefined) */":t}," ").replace(/"\/\* void\(undefined\) \*\/"/g,"undefined")},warn:function(){},log:function(){},error:function(){},_logger:r._logger}}),define("can-queues/queue-state",function(e,t,n){"use strict";n.exports={lastTask:null}}),define("can-queues/queue",["require","exports","module","can-queues/queue-state","can-log/dev/dev","can-assign"],function(e,t,n){"use strict";var r=e("can-queues/queue-state"),a=(e("can-log/dev/dev"),e("can-assign"));function i(){}var o=function(e,t){this.callbacks=a({onFirstTask:i,onComplete:function(){r.lastTask=null}},t||{}),this.name=e,this.index=0,this.tasks=[],this._log=!1};(o.prototype.constructor=o).noop=i,o.prototype.enqueue=function(e,t,n,r){1===this.tasks.push({fn:e,context:t,args:n,meta:r||{}})&&this.callbacks.onFirstTask(this)},o.prototype.flush=function(){for(;this.index<this.tasks.length;){var e=this.tasks[this.index++];e.fn.apply(e.context,e.args)}this.index=0,this.tasks=[],this.callbacks.onComplete(this)},o.prototype.log=function(){this._log=!arguments.length||arguments[0]},n.exports=o}),define("can-queues/priority-queue",["require","exports","module","can-queues/queue"],function(e,t,n){"use strict";var r=e("can-queues/queue"),a=function(){r.apply(this,arguments),this.taskMap=new Map,this.taskContainersByPriority=[],this.curPriorityIndex=1/0,this.curPriorityMax=0,this.isFlushing=!1,this.tasksRemaining=0};((a.prototype=Object.create(r.prototype)).constructor=a).prototype.enqueue=function(e,t,n,r){if(!this.taskMap.has(e)){this.tasksRemaining++;var a=0===this.taskContainersByPriority.length,i={fn:e,context:t,args:n,meta:r||{}};this.getTaskContainerAndUpdateRange(i).tasks.push(i),this.taskMap.set(e,i),a&&this.callbacks.onFirstTask(this)}},a.prototype.getTaskContainerAndUpdateRange=function(e){var t=e.meta.priority||0;t<this.curPriorityIndex&&(this.curPriorityIndex=t),t>this.curPriorityMax&&(this.curPriorityMax=t);var n=this.taskContainersByPriority,r=n[t];return r||(r=n[t]={tasks:[],index:0}),r},a.prototype.flush=function(){if(!this.isFlushing)for(this.isFlushing=!0;;){if(!(this.curPriorityIndex<=this.curPriorityMax))return this.taskMap=new Map,this.curPriorityIndex=1/0,this.curPriorityMax=0,this.taskContainersByPriority=[],this.isFlushing=!1,void this.callbacks.onComplete(this);var e=this.taskContainersByPriority[this.curPriorityIndex];if(e&&e.tasks.length>e.index){var t=e.tasks[e.index++];this.tasksRemaining--,this.taskMap.delete(t.fn),t.fn.apply(t.context,t.args)}else this.curPriorityIndex++}},a.prototype.isEnqueued=function(e){return this.taskMap.has(e)},a.prototype.flushQueuedTask=function(e){var t=this.dequeue(e);t&&t.fn.apply(t.context,t.args)},a.prototype.dequeue=function(e){var t=this.taskMap.get(e);if(t){var n=t.meta.priority||0,r=this.taskContainersByPriority[n],a=r.tasks.indexOf(t,r.index);if(0<=a)return r.tasks.splice(a,1),this.tasksRemaining--,this.taskMap.delete(t.fn),t;console.warn("Task",e,"has already run")}},a.prototype.tasksRemainingCount=function(){return this.tasksRemaining},n.exports=a}),define("can-queues/completion-queue",["require","exports","module","can-queues/queue"],function(e,t,n){"use strict";var r=e("can-queues/queue"),a=function(){r.apply(this,arguments),this.flushCount=0};((a.prototype=Object.create(r.prototype)).constructor=a).prototype.flush=function(){if(0===this.flushCount){for(this.flushCount++;this.index<this.tasks.length;){var e=this.tasks[this.index++];e.fn.apply(e.context,e.args)}this.index=0,this.tasks=[],this.flushCount--,this.callbacks.onComplete(this)}},n.exports=a}),define("can-queues",["require","exports","module","can-log/dev/dev","can-queues/queue","can-queues/priority-queue","can-queues/queue-state","can-queues/completion-queue","can-namespace"],function(e,t,n){"use strict";var r,a,i,o,s,c=e("can-log/dev/dev"),u=e("can-queues/queue"),l=e("can-queues/priority-queue"),f=e("can-queues/queue-state"),d=e("can-queues/completion-queue"),p=e("can-namespace"),h=0,v=!1,y=0,g=["notify","derive","domUI","mutate"];a=new u("NOTIFY",{onComplete:function(){i.flush()},onFirstTask:function(){h?v=!0:a.flush()}}),i=new l("DERIVE",{onComplete:function(){o.flush()},onFirstTask:function(){v=!0}}),o=new d("DOM_UI",{onComplete:function(){s.flush()},onFirstTask:function(){v=!0}}),s=new u("MUTATE",{onComplete:function(){f.lastTask=null,!1},onFirstTask:function(){v=!0}});var m={Queue:u,PriorityQueue:l,CompletionQueue:d,notifyQueue:a,deriveQueue:i,domUIQueue:o,mutateQueue:s,batch:{start:function(){1===++h&&(r={number:++y})},stop:function(){0===--h&&v&&(!(v=!1),a.flush())},isCollecting:function(){return 0<h},number:function(){return y},data:function(){return r}},runAsTask:function(e,t){return e},enqueueByQueue:function(r,a,i,o,s){r&&(m.batch.start(),g.forEach(function(e){var n=m[e+"Queue"],t=r[e];void 0!==t&&t.forEach(function(e){var t=null!=o?o(e,a,i):{};t.reasonLog=s,n.enqueue(e,a,i,t)})}),m.batch.stop())},lastTask:function(){return f.lastTask},stack:function(e){for(var t=e||f.lastTask,n=[];t;)n.unshift(t),t=t.meta.parentTask;return n},logStack:function(e){this.stack(e).forEach(function(e,t){var n=e.meta;0===t&&n&&n.reasonLog&&c.log.apply(c,n.reasonLog);var r=n&&n.log?n.log:[e.fn.name,e];c.log.apply(c,[e.meta.stack.name+" ran task:"].concat(r))})},taskCount:function(){return a.tasks.length+i.tasks.length+o.tasks.length+s.tasks.length},flush:function(){a.flush()},log:function(){a.log.apply(a,arguments),i.log.apply(i,arguments),o.log.apply(o,arguments),s.log.apply(s,arguments)}};if(p.queues)throw new Error("You can't have two versions of can-queues, check your dependencies");n.exports=p.queues=m}),define("can-diff/list/list",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var d=e("can-reflect"),p=[].slice;function h(e,t){return e===t}function v(n){return n.identity&&n.identity.length?function(e,t){return d.getIdentity(e,n)===d.getIdentity(t,n)}:h}function y(e,t,n,r,a){for(var i=n.length-1,o=r.length-1;e<i&&t<o;){if(!a(n[i],r[o],i))return[{type:"splice",index:t,deleteCount:i-e+1,insert:p.call(r,t,o+1)}];i--,o--}return[{type:"splice",index:t,deleteCount:i-e+1,insert:p.call(r,t,o+1)}]}n.exports=function(e,t,n){var r,a,i=0,o=0,s=d.size(e),c=d.size(t),u=[];for(r="function"===typeof n?n:null!=n?"map"===n.type?v(n):null!=(a=n).values?v(d.getSchema(a.values)):h:function(e,t){var n,r=d.getSchema(e);if(null!=r){if(null==r.values)return h;n=d.getSchema(r.values)}return null==n&&0<t&&(n=d.getSchema(d.getKeyValue(e,0))),n?v(n):h}(e,s);i<s&&o<c;){var l=e[i],f=t[o];if(r(l,f,i))i++,o++;else if(o+1<c&&r(l,t[o+1],i))u.push({index:o,deleteCount:0,insert:[t[o]],type:"splice"}),i++,o+=2;else{if(!(i+1<s&&r(e[i+1],f,i+1)))return u.push.apply(u,y(i,o,e,t,r)),u;u.push({index:o,deleteCount:1,insert:[],type:"splice"}),i+=2,o++}}return o===c&&i===s||u.push({type:"splice",index:o,deleteCount:s-i,insert:p.call(t,o)}),u}}),define("can-diff/merge-deep/merge-deep",["require","exports","module","can-reflect","can-diff/list/list"],function(e,t,n){"use strict";var u=e("can-reflect"),c=e("can-diff/list/list");function r(e,t){return t=u.serialize(t),u.isMoreListLikeThanMapLike(e)?f(e,t):l(e,t),e}function l(s,c){u.eachKey(s,function(e,t){if(u.hasKey(c,t)){var n=u.getKeyValue(c,t);if(u.deleteKeyValue(c,t),u.isPrimitive(e))u.setKeyValue(s,t,n);else{var r=Array.isArray(n),a=u.isMoreListLikeThanMapLike(e);if(a&&r)f(e,n);else if(!r&&!a&&u.isMapLike(e)&&u.isPlainObject(n)){var i=u.getSchema(e);if(i&&i.identity&&i.identity.length){var o=u.getIdentity(e,i);if(null!=o&&o===u.getIdentity(n,i))return void l(e,n)}u.setKeyValue(s,t,u.new(e.constructor,n))}else u.setKeyValue(s,t,n)}}else u.deleteKeyValue(s,t)}),u.eachKey(c,function(e,t){u.setKeyValue(s,t,e)})}function f(t,e){var n,r,a,i=u.getSchema(t);i&&(n=i.values),n&&(r=u.getSchema(n)),!r&&0<u.size(t)&&(r=u.getSchema(u.getKeyValue(t,0))),a=r&&r.identity&&r.identity.length?function(e,t){var n=u.getIdentity(e,r)===u.getIdentity(t,r);return n&&l(e,t),n}:function(e,t){var n=e===t;return n&&(u.isPrimitive(e)||l(e,t)),n};var o=c(t,e,a),s=n?u.new.bind(u,n):function(e){return e};if(!o.length)return t;o.forEach(function(e){d(t,e,s)})}function d(e,t,n){var r=n&&t.insert.map(function(e){return n(e)})||t.insert,a=[t.index,t.deleteCount].concat(r);return e.splice.apply(e,a),e}r.applyPatch=d,n.exports=r}),define("can-debug",["require","exports","module","can-namespace","can-globals","can-debug/src/proxy-namespace","can-debug/src/temporarily-bind","can-debug/src/get-graph/get-graph","can-debug/src/format-graph/format-graph","can-debug/src/what-i-change/what-i-change","can-debug/src/what-changes-me/what-changes-me","can-debug/src/get-what-i-change/get-what-i-change","can-debug/src/get-what-changes-me/get-what-changes-me","can-symbol","can-reflect","can-queues","can-diff/merge-deep/merge-deep"],function(e,t,n){!function(r,e,t,n){"use strict";var a=e("can-namespace"),i=e("can-globals"),o=e("can-debug/src/proxy-namespace"),s=e("can-debug/src/temporarily-bind"),c=e("can-debug/src/get-graph/get-graph"),u=e("can-debug/src/format-graph/format-graph"),l=e("can-debug/src/what-i-change/what-i-change"),f=e("can-debug/src/what-changes-me/what-changes-me"),d=e("can-debug/src/get-what-i-change/get-what-i-change"),p=e("can-debug/src/get-what-changes-me/get-what-changes-me"),h=e("can-symbol"),v=e("can-reflect"),y=e("can-queues"),g=e("can-diff/merge-deep/merge-deep"),m=(r=i.getKeyValue("global"),!1);n.exports=function(){return a.debug={getGraph:s(c),formatGraph:s(u),getWhatIChange:s(d),getWhatChangesMe:s(p),logWhatIChange:s(l),logWhatChangesMe:s(f)},function(){if(!m){var t="__CANJS_DEVTOOLS__",n={Symbol:h,Reflect:v,queues:y,getGraph:a.debug.getGraph,formatGraph:a.debug.formatGraph,mergeDeep:g};r[t]?r[t].register(n):Object.defineProperty(r,t,{set:function(e){Object.defineProperty(r,t,{value:e}),e.register(n)},configurable:!0}),m=!0}}(),r.can="undefined"!=typeof Proxy?o(a):a,a.debug}}(function(){return this}(),e,0,n)}),define("can/es/can-debug",["exports","can-debug"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/enable-can-debug",["can/es/can-debug"],function(e){"use strict";var t;(t=e)&&t.__esModule}),define("can-observation-recorder",["require","exports","module","can-namespace","can-symbol"],function(e,t,n){"use strict";var r=e("can-namespace"),a=e("can-symbol"),i=[],o=a.for("can.addParent"),s=a.for("can.getValue"),c={stack:i,start:function(e){var t={keyDependencies:new Map,valueDependencies:new Set,childDependencies:new Set,traps:null,ignore:0,name:e};return i.push(t),t},stop:function(){return i.pop()},add:function(e,t){var n=i[i.length-1];if(n&&0===n.ignore)if(n.traps)n.traps.push([e,t]);else if(void 0===t)n.valueDependencies.add(e);else{var r=n.keyDependencies.get(e);r||(r=new Set,n.keyDependencies.set(e,r)),r.add(t)}},addMany:function(e){var t=i[i.length-1];if(t)if(t.traps)t.traps.push.apply(t.traps,e);else for(var n=0,r=e.length;n<r;n++)this.add(e[n][0],e[n][1])},created:function(e){var t=i[i.length-1];t&&(t.childDependencies.add(e),e[o]&&e[o](t))},ignore:function(n){return function(){if(i.length){var e=i[i.length-1];e.ignore++;var t=n.apply(this,arguments);return e.ignore--,t}return n.apply(this,arguments)}},peekValue:function(e){if(!e||!e[s])return e;if(i.length){var t=i[i.length-1];t.ignore++;var n=e[s]();return t.ignore--,n}return e[s]()},isRecording:function(){var e=i.length,t=e&&i[e-1];return t&&0===t.ignore&&t},makeDependenciesRecord:function(e){return{traps:null,keyDependencies:new Map,valueDependencies:new Set,ignore:0,name:e}},makeDependenciesRecorder:function(){return c.makeDependenciesRecord()},trap:function(){if(i.length){var e=i[i.length-1],t=e.traps,n=e.traps=[];return function(){return e.traps=t,n}}return function(){return[]}},trapsCount:function(){return i.length?i[i.length-1].traps.length:0}};if(r.ObservationRecorder)throw new Error("You can't have two versions of can-observation-recorder, check your dependencies");n.exports=r.ObservationRecorder=c}),define("can-key-tree",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var u=e("can-reflect");function s(e){if(e===Object.prototype)return!0;var t=Object.prototype.toString.call(e),n="[object Object]"!==t,r=-1!==t.indexOf("[object ");return n&&r}function l(n,r,a,i){if(a===r.length){if(!u.isMoreListLikeThanMapLike(n))throw new Error("can-key-tree: Map-type leaf containers are not supported yet.");var e=u.toArray(n);i&&e.forEach(function(e){i.apply(null,r.concat(e))}),u.removeValues(n,e)}else u.each(n,function(e,t){l(e,r.concat(t),a,i),u.deleteKeyValue(n,t)})}var r=function(e,t){var n=e[0];u.isConstructorLike(n)?this.root=new n:this.root=n,this.callbacks=t||{},this.treeStructure=e,this.empty=!0};u.assign(r.prototype,{add:function(e){if(e.length>this.treeStructure.length)throw new Error("can-key-tree: Can not add path deeper than tree.");for(var t=this.root,n=!0===this.empty,r=0;r<e.length-1;r++){var a=e[r],i=u.getKeyValue(t,a);if(!i){var o=this.treeStructure[r+1];i=s(o.prototype)?new o:new o(a),u.setKeyValue(t,a,i)}t=i}if(!u.isMoreListLikeThanMapLike(t))throw new Error("can-key-tree: Map types are not supported yet.");return u.addValues(t,[e[e.length-1]]),n&&(this.empty=!1,this.callbacks.onFirst&&this.callbacks.onFirst.call(this)),this},getNode:function(e){for(var t=this.root,n=0;n<e.length;n++){var r=e[n];if(!(t=u.getKeyValue(t,r)))return}return t},get:function(e){var t=this.getNode(e);if(this.treeStructure.length===e.length)return t;var n=new this.treeStructure[this.treeStructure.length-1];return function t(e,n,r,a){if(e)if(a===r){if(!u.isMoreListLikeThanMapLike(e))throw new Error("can-key-tree: Map-type leaf containers are not supported yet.");u.addValues(n,u.toArray(e))}else u.each(e,function(e){t(e,n,r+1,a)})}(t,n,e.length,this.treeStructure.length-1),n},delete:function(e,t){for(var n=this.root,r=[this.root],a=e[e.length-1],i=0;i<e.length-1;i++){var o=e[i],s=u.getKeyValue(n,o);if(void 0===s)return!1;r.push(s),n=s}if(e.length)if(e.length===this.treeStructure.length){if(!u.isMoreListLikeThanMapLike(n))throw new Error("can-key-tree: Map types are not supported yet.");t&&t.apply(null,e.concat(a)),u.removeValues(n,[a])}else{var c=u.getKeyValue(n,a);if(void 0===c)return!1;l(c,e,this.treeStructure.length-1,t),u.deleteKeyValue(n,a)}else l(n,[],this.treeStructure.length-1,t);for(i=r.length-2;0<=i&&0===u.size(n);i--)n=r[i],u.deleteKeyValue(n,e[i]);return 0===u.size(this.root)&&(this.empty=!0,this.callbacks.onEmpty&&this.callbacks.onEmpty.call(this)),!0},size:function(){return function t(e,n){if(0===n)return u.size(e);if(0===u.size(e))return 0;var r=0;return u.each(e,function(e){r+=t(e,n-1)}),r}(this.root,this.treeStructure.length-1)},isEmpty:function(){return this.empty}}),n.exports=r}),define("can-define-lazy-value",function(e,t,n){"use strict";n.exports=function(t,n,r,a){Object.defineProperty(t,n,{configurable:!0,get:function(){Object.defineProperty(this,n,{value:void 0,writable:!0});var e=r.call(this,t,n);return Object.defineProperty(this,n,{value:e,writable:!!a}),e},set:function(e){return Object.defineProperty(this,n,{value:e,writable:!!a}),e}})}}),define("can-event-queue/dependency-record/merge",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var a=e("can-reflect");n.exports=function(e,t){return function(e,t){var n=t.keyDependencies;if(n){var r=e.keyDependencies;r||(r=new Map,e.keyDependencies=r),a.eachKey(n,function(e,t){var n=r.get(t);n||(n=new Set,r.set(t,n)),a.eachIndex(e,function(e){n.add(e)})})}}(e,t),function(e,t){var n=t.valueDependencies;if(n){var r=e.valueDependencies;r||(r=new Set,e.valueDependencies=r),a.eachIndex(n,function(e){r.add(e)})}}(e,t),e}}),define("can-event-queue/value/value",["require","exports","module","can-queues","can-key-tree","can-reflect","can-define-lazy-value","can-event-queue/dependency-record/merge"],function(e,t,n){"use strict";var r=e("can-queues"),a=e("can-key-tree"),i=e("can-reflect"),o=e("can-define-lazy-value"),s=(e("can-event-queue/dependency-record/merge"),{on:function(e,t){this.handlers.add([t||"mutate",e])},off:function(e,t){void 0===e?void 0===t?this.handlers.delete([]):this.handlers.delete([t]):this.handlers.delete([t||"mutate",e])}}),c={"can.onValue":s.on,"can.offValue":s.off,"can.dispatch":function(e,t){var n;n=[this.handlers.getNode([]),this,[e,t]],r.enqueueByQueue.apply(r,n)},"can.getWhatIChange":function(){},"can.isBound":function(){return!this.handlers.isEmpty()}};function u(){return new a([Object,Array],{onFirst:void 0!==this.onBound&&this.onBound.bind(this),onEmpty:void 0!==this.onUnbound&&this.onUnbound.bind(this)})}var l=function(e){return i.assign(e,s),i.assignSymbols(e,c),o(e,"handlers",u,!0),e};l.addHandlers=function(e,t){return console.warn("can-event-queue/value: Avoid using addHandlers. Add onBound and onUnbound methods instead."),e.handlers=new a([Object,Array],t),e},n.exports=l}),define("can-observation/recorder-dependency-helpers",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var r=e("can-reflect");function a(e){void 0!==this.oldEventSet&&!1!==this.oldEventSet.delete(e)||r.onKeyValue(this.observable,e,this.onDependencyChange,"notify")}function i(e,t){e.forEach(a,{onDependencyChange:this.onDependencyChange,observable:t,oldEventSet:this.oldDependencies.keyDependencies.get(t)})}function o(e){r.offKeyValue(this.observable,e,this.onDependencyChange,"notify")}function s(e,t){e.forEach(o,{onDependencyChange:this.onDependencyChange,observable:t})}function c(e){!1===this.oldDependencies.valueDependencies.delete(e)&&r.onValue(e,this.onDependencyChange,"notify")}function u(e){r.offValue(e,this.onDependencyChange,"notify")}n.exports={updateObservations:function(e){e.newDependencies.keyDependencies.forEach(i,e),e.oldDependencies.keyDependencies.forEach(s,e),e.newDependencies.valueDependencies.forEach(c,e),e.oldDependencies.valueDependencies.forEach(u,e)},stopObserving:function(e,t){e.keyDependencies.forEach(s,{onDependencyChange:t}),e.valueDependencies.forEach(u,{onDependencyChange:t})}}}),define("can-observation/temporarily-bind",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var r,a=e("can-reflect"),i=function(){},o=function(){for(var e=0,t=r.length;e<t;e++)a.offValue(r[e],i);r=null};n.exports=function(e){var t=e.computeInstance||e;a.onValue(t,i),r||(r=[],setTimeout(o,10)),r.push(t)}}),define("can-observation",["require","exports","module","can-namespace","can-reflect","can-queues","can-observation-recorder","can-symbol","can-log/dev/dev","can-event-queue/value/value","can-observation/recorder-dependency-helpers","can-observation/temporarily-bind"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-namespace"),i=t("can-reflect"),o=t("can-queues"),s=t("can-observation-recorder"),c=t("can-symbol"),u=(t("can-log/dev/dev"),t("can-event-queue/value/value")),l=t("can-observation/recorder-dependency-helpers"),f=t("can-observation/temporarily-bind"),d=c.for("can.dispatch"),p=(c.for("can.getChangesDependencyRecord"),c.for("can.getValueDependencies"));function h(e,t,n){this.func=e,this.context=t,this.options=n||{priority:0,isObservable:!0},this.bound=!1,this._value=void 0,this.newDependencies=s.makeDependenciesRecord(),this.oldDependencies=null;var r=this;this.onDependencyChange=function(e){r.dependencyChange(this,e)},this.update=this.update.bind(this)}u(h.prototype),i.assign(h.prototype,{onBound:function(){this.bound=!0,this.oldDependencies=this.newDependencies,s.start(this._name),this._value=this.func.call(this.context),this.newDependencies=s.stop(),l.updateObservations(this)},dependencyChange:function(e,t){if(!0===this.bound){var n;n=[this.update,this,[],{priority:this.options.priority}],o.deriveQueue.enqueue.apply(o.deriveQueue,n)}},update:function(){if(!0===this.bound){var e=this._value;this.oldValue=null,this.onBound(),e!==this._value&&this[d](this._value,e)}},onUnbound:function(){this.bound=!1,l.stopObserving(this.newDependencies,this.onDependencyChange),this.newDependencies=s.makeDependenciesRecord()},get:function(){return this.options.isObservable&&s.isRecording()&&(s.add(this),!1===this.bound&&h.temporarilyBind(this)),!0===this.bound?(0<o.deriveQueue.tasksRemainingCount()&&h.updateChildrenAndSelf(this),this._value):this.func.call(this.context)},hasDependencies:function(){var e=this.newDependencies;return this.bound?0<e.valueDependencies.size+e.keyDependencies.size:void 0},log:function(){}}),Object.defineProperty(h.prototype,"value",{get:function(){return this.get()}});var v={"can.getValue":h.prototype.get,"can.isValueLike":!0,"can.isMapLike":!1,"can.isListLike":!1,"can.valueHasDependencies":h.prototype.hasDependencies,"can.getValueDependencies":function(){if(!0===this.bound){var e=this.newDependencies,t={};return e.keyDependencies.size&&(t.keyDependencies=e.keyDependencies),e.valueDependencies.size&&(t.valueDependencies=e.valueDependencies),t}},"can.getPriority":function(){return this.options.priority},"can.setPriority":function(e){this.options.priority=e}};i.assignSymbols(h.prototype,v),h.updateChildrenAndSelf=function(e){if(void 0!==e.update&&!0===o.deriveQueue.isEnqueued(e.update))return o.deriveQueue.flushQueuedTask(e.update),!0;if(e[p]){var t=!1;return(e[p]().valueDependencies||[]).forEach(function(e){!0===h.updateChildrenAndSelf(e)&&(t=!0)}),t}return!1};var y={addAll:"addMany"};["add","addAll","ignore","trap","trapsCount","isRecording"].forEach(function(t){h[t]=function(){var e=y[t]?y[t]:t;return console.warn("can-observation: Call "+e+"() on can-observation-recorder."),s[e].apply(this,arguments)}}),h.prototype.start=function(){return console.warn("can-observation: Use .on and .off to bind."),this.onBound()},h.prototype.stop=function(){return console.warn("can-observation: Use .on and .off to bind."),this.onUnbound()},h.temporarilyBind=f,r.exports=a.Observation=h}(0,e,0,n)}),define("can-simple-observable/log",["require","exports","module","can-log/dev/dev","can-reflect"],function(e,t,n){"use strict";e("can-log/dev/dev"),e("can-reflect");n.exports=function(){}}),define("can-simple-observable",["require","exports","module","can-simple-observable/log","can-namespace","can-symbol","can-reflect","can-observation-recorder","can-event-queue/value/value"],function(e,t,n){"use strict";var r=e("can-simple-observable/log"),a=e("can-namespace"),i=e("can-symbol"),o=e("can-reflect"),s=e("can-observation-recorder"),c=e("can-event-queue/value/value"),u=i.for("can.dispatch");function l(e){this._value=e}c(l.prototype),o.assignMap(l.prototype,{log:r,get:function(){return s.add(this),this._value},set:function(e){var t=this._value;this._value=e,this[u](e,t)}}),Object.defineProperty(l.prototype,"value",{set:function(e){return this.set(e)},get:function(){return this.get()}});var f={"can.getValue":l.prototype.get,"can.setValue":l.prototype.set,"can.isMapLike":!1,"can.valueHasDependencies":function(){return!0}};o.assignSymbols(l.prototype,f),n.exports=a.SimpleObservable=l}),define("can-simple-observable/settable/settable",["require","exports","module","can-reflect","can-observation-recorder","can-simple-observable","can-observation","can-queues","can-simple-observable/log","can-event-queue/value/value"],function(e,t,n){"use strict";var r=e("can-reflect"),a=e("can-observation-recorder"),i=e("can-simple-observable"),o=e("can-observation"),s=e("can-queues"),c=e("can-simple-observable/log"),u=e("can-event-queue/value/value"),l=a.ignore(r.getValue.bind(r));function f(e,t,n){this.lastSetValue=new i(n),this.handler=this.handler.bind(this),this.observation=new o(function(){return e.call(t,this.lastSetValue.get())},this)}u(f.prototype),r.assignMap(f.prototype,{log:c,constructor:f,handler:function(e){var t=this._value;this._value=e,s.enqueueByQueue(this.handlers.getNode([]),this,[e,t],null,void 0)},onBound:function(){this.bound||(this.bound=!0,this.activate())},activate:function(){r.onValue(this.observation,this.handler,"notify"),this._value=l(this.observation)},onUnbound:function(){this.bound=!1,r.offValue(this.observation,this.handler,"notify")},set:function(e){var t=this.lastSetValue.get();r.isObservableLike(t)&&r.isValueLike(t)&&!r.isObservableLike(e)?r.setValue(t,e):e!==t&&this.lastSetValue.set(e)},get:function(){return a.isRecording()&&(a.add(this),this.bound||this.onBound()),!0===this.bound?this._value:this.observation.get()},hasDependencies:function(){return r.valueHasDependencies(this.observation)},getValueDependencies:function(){return r.getValueDependencies(this.observation)}}),Object.defineProperty(f.prototype,"value",{set:function(e){return this.set(e)},get:function(){return this.get()}}),r.assignSymbols(f.prototype,{"can.getValue":f.prototype.get,"can.setValue":f.prototype.set,"can.isMapLike":!1,"can.getPriority":function(){return r.getPriority(this.observation)},"can.setPriority":function(e){r.setPriority(this.observation,e)},"can.valueHasDependencies":f.prototype.hasDependencies,"can.getValueDependencies":f.prototype.getValueDependencies}),n.exports=f}),define("can-simple-observable/async/async",["require","exports","module","can-simple-observable","can-observation","can-queues","can-simple-observable/settable/settable","can-reflect","can-observation-recorder","can-event-queue/value/value"],function(e,t,n){"use strict";var r=e("can-simple-observable"),a=e("can-observation"),i=e("can-queues"),o=e("can-simple-observable/settable/settable"),s=e("can-reflect"),c=e("can-observation-recorder");e("can-event-queue/value/value");function u(t,n,e){this.resolve=this.resolve.bind(this),this.lastSetValue=new r(e),this.handler=this.handler.bind(this),this.observation=new a(function(){this.resolveCalled=!1,this.inGetter=!0;var e=t.call(n,this.lastSetValue.get(),!0===this.bound?this.resolve:void 0);if(this.inGetter=!1,void 0!==e?this.resolve(e):this.resolveCalled&&this.resolve(this._value),!0!==this.bound)return e},this)}((u.prototype=Object.create(o.prototype)).constructor=u).prototype.handler=function(e){void 0!==e&&o.prototype.handler.apply(this,arguments)};var l=c.ignore(s.getValue.bind(s));u.prototype.activate=function(){s.onValue(this.observation,this.handler,"notify"),this.resolveCalled||(this._value=l(this.observation))},u.prototype.resolve=function(e){this.resolveCalled=!0;var t=this._value;if(this._value=e,!this.inGetter){var n=[this.handlers.getNode([]),this,[e,t],null];i.enqueueByQueue.apply(i,n)}},n.exports=u}),define("can-dom-events/helpers/util",["require","exports","module","can-globals/document/document","can-globals/is-browser-window/is-browser-window"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-globals/document/document"),i=t("can-globals/is-browser-window/is-browser-window");function s(e){return e.ownerDocument||a()}function o(e){if(!e||!e.nodeName)return e===window;var t=e.nodeType;return 1===t||9===t||11===t}var c=!1;!function(){if(i()){var t="fix_synthetic_events_on_disabled_test",n=document.createElement("input");n.disabled=!0;var r=setTimeout(function(){c=!0},50),a=function e(){clearTimeout(r),n.removeEventListener(t,e)};n.addEventListener(t,a);try{var e=document.create("HTMLEvents");e.initEvent(t,!1),n.dispatchEvent(e)}catch(e){a(),c=!0}}}(),r.exports={createEvent:function(e,t,n,r){var a,i=s(e).createEvent("HTMLEvents");if("string"==typeof t)a=t;else for(var o in a=t.type,t)void 0===i[o]&&(i[o]=t[o]);return void 0===n&&(n=!0),i.initEvent(a,n,r),i},addDomContext:function(e,t){return o(e)&&(t=Array.prototype.slice.call(t,0)).unshift(e),t},removeDomContext:function(e,t){return o(e)||(e=(t=Array.prototype.slice.call(t,0)).shift()),{context:e,args:t}},isDomEventTarget:o,getTargetDocument:s,forceEnabledForDispatch:function(e,t){return c&&(n=e,r=t.type,a="inserted"===r||"removed"===r,i=!!n.disabled,a&&i);var n,r,a,i}}}(0,e,0,n)}),define("can-dom-events/helpers/make-event-registry",function(e,t,n){"use strict";function r(){this._registry={}}n.exports=function(){return new r},r.prototype.has=function(e){return!!this._registry[e]},r.prototype.get=function(e){return this._registry[e]},r.prototype.add=function(e,t){if(!e)throw new Error("An EventDefinition must be provided");if("function"!=typeof e.addEventListener)throw new TypeError("EventDefinition addEventListener must be a function");if("function"!=typeof e.removeEventListener)throw new TypeError("EventDefinition removeEventListener must be a function");if("string"!=typeof(t=t||e.defaultEventType))throw new TypeError("Event type must be a string, not "+t);if(this.has(t))throw new Error('Event "'+t+'" is already registered');this._registry[t]=e;var n=this;return function(){n._registry[t]=void 0}}}),define("can-dom-events/helpers/-make-delegate-event-tree",["require","exports","module","can-key-tree","can-reflect"],function(e,t,n){"use strict";var a=e("can-key-tree"),o=e("can-reflect"),i=function(e){return"focus"===e||"blur"===e};n.exports=function(e){var r,t,n=(r=e,t=function(e){this.element=e,this.events={},this.delegated={}},o.assignSymbols(t.prototype,{"can.setKeyValue":function(e,t){var n=this.delegated[e]=function(i){o.each(t,function(e,t){var n=i.target;do{var r=n===document?document.documentElement:n,a=r.matches||r.msMatchesSelector;a&&a.call(r,t)&&e.forEach(function(e){e.call(r,i)}),n=n.parentNode}while(n&&n!==i.currentTarget)})};this.events[e]=t,r.addEventListener(this.element,e,n,i(e))},"can.getKeyValue":function(e){return this.events[e]},"can.deleteKeyValue":function(e){r.removeEventListener(this.element,e,this.delegated[e],i(e)),delete this.delegated[e],delete this.events[e]},"can.getOwnEnumerableKeys":function(){return Object.keys(this.events)}}),t);return new a([Map,n,Object,Array])}}),define("can-dom-events",["require","exports","module","can-namespace","can-dom-events/helpers/util","can-dom-events/helpers/make-event-registry","can-dom-events/helpers/-make-delegate-event-tree"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-namespace"),s=t("can-dom-events/helpers/util"),i=t("can-dom-events/helpers/make-event-registry"),o=t("can-dom-events/helpers/-make-delegate-event-tree"),c={_eventRegistry:i(),addEvent:function(e,t){return this._eventRegistry.add(e,t)},addEventListener:function(e,t){if(c._eventRegistry.has(t))return c._eventRegistry.get(t).addEventListener.apply(c,arguments);var n=Array.prototype.slice.call(arguments,1);return e.addEventListener.apply(e,n)},removeEventListener:function(e,t){if(c._eventRegistry.has(t))return c._eventRegistry.get(t).removeEventListener.apply(c,arguments);var n=Array.prototype.slice.call(arguments,1);return e.removeEventListener.apply(e,n)},addDelegateListener:function(e,t,n,r){c._eventTree.add([e,t,n,r])},removeDelegateListener:function(e,t,n,r){c._eventTree.delete([e,t,n,r])},dispatch:function(e,t,n,r){var a=s.createEvent(e,t,n,r),i=s.forceEnabledForDispatch(e,a);i&&(e.disabled=!1);var o=e.dispatchEvent(a);return i&&(e.disabled=!0),o}};c._eventTree=o(c),r.exports=a.domEvents=c}(0,e,0,n)}),define("can-event-queue/map/map",["require","exports","module","can-log/dev/dev","can-queues","can-reflect","can-symbol","can-key-tree","can-dom-events","can-dom-events/helpers/util","can-event-queue/dependency-record/merge"],function(e,t,n){"use strict";e("can-log/dev/dev");var a,u=e("can-queues"),i=e("can-reflect"),r=e("can-symbol"),o=e("can-key-tree"),s=e("can-dom-events"),c=e("can-dom-events/helpers/util").isDomEventTarget,l=(e("can-event-queue/dependency-record/merge"),r.for("can.meta")),f=r.for("can.dispatchInstanceBoundChange"),d=r.for("can.dispatchInstanceOnPatches"),p=r.for("can.onKeyValue"),h=r.for("can.offKeyValue"),v=r.for("can.onEvent"),y=r.for("can.offEvent"),g=r.for("can.onValue"),m=r.for("can.offValue");function b(t,e){e.handlers||(e.handlers=new o([Object,Object,Object,Array],{onFirst:function(){void 0!==t._eventSetup&&t._eventSetup();var e=t.constructor;void 0!==e[f]&&t instanceof e&&e[f](t,!0)},onEmpty:function(){void 0!==t._eventTeardown&&t._eventTeardown();var e=t.constructor;void 0!==e[f]&&t instanceof e&&e[f](t,!1)}})),e.listenHandlers||(e.listenHandlers=new o([Map,Map,Object,Array]))}var w=function(e){var t=e[l];return t||(t={},i.setKeyValue(e,l,t)),b(e,t),t};function x(e,t,n,r){arguments.length&&i.isPrimitive(e)&&(r=n,n=t,t=e,e=this.context),"function"==typeof t&&(r=n,n=t,t=void 0),"string"==typeof n&&(r=n,n=void 0);var a=[];return e&&(a.push(e),(t||n||r)&&(a.push(t),(r||n)&&(a.push(r||this.defaultQueue),n&&a.push(n)))),a}var _={dispatch:function(e,t){if(!this.__inSetup){"string"==typeof e&&(e={type:e});var n=w(this).handlers,r=void 0!==e.type&&n.getNode([e.type]),a=e.patches&&this.constructor[d],i=void 0!==e.patches&&n.getNode(["can.patches","onKeyValue"]),o=void 0!==e.keyChanged&&n.getNode(["can.keys","onKeyValue"]),s=a||r||i||o;if(s&&u.batch.start(),r&&(r.onKeyValue&&u.enqueueByQueue(r.onKeyValue,this,t,e.makeMeta,e.reasonLog),r.event)){e.batchNum=u.batch.number();var c=[e].concat(t);u.enqueueByQueue(r.event,this,c,e.makeMeta,e.reasonLog)}o&&u.enqueueByQueue(o,this,[e.keyChanged],e.makeMeta,e.reasonLog),i&&u.enqueueByQueue(i,this,[e.patches],e.makeMeta,e.reasonLog),a&&this.constructor[d](this,e.patches),s&&u.batch.stop()}return e},addEventListener:function(e,t,n){return w(this).handlers.add([e,"event",n||"mutate",t]),this},removeEventListener:function(e,t,n){if(void 0===e){var r=w(this).handlers,a=r.getNode([]);Object.keys(a).forEach(function(e){r.delete([e,"event"])})}else t||n?t?w(this).handlers.delete([e,"event",n||"mutate",t]):w(this).handlers.delete([e,"event",n||"mutate"]):w(this).handlers.delete([e,"event"]);return this},one:function(e,t){var n=function(){return a.off.call(this,e,n),t.apply(this,arguments)};return a.on.call(this,e,n),this},listenTo:function(e,t,n,r){return i.isPrimitive(e)&&(r=n,n=t,t=e,e=this),"function"==typeof t&&(r=n,n=t,t=void 0),w(this).listenHandlers.add([e,t,r||"mutate",n]),a.on.call(e,t,n,r||"mutate"),this},stopListening:function(){var e=x.apply({context:this,defaultQueue:"mutate"},arguments);return w(this).listenHandlers.delete(e,function(e,t,n,r){a.off.call(e,t,r,n)}),this},on:function(e,t,n){if(c(this))"string"==typeof t?s.addDelegateListener(this,e,t,n):s.addEventListener(this,e,t,n);else if(this[v])this[v](e,t,n);else if("addEventListener"in this)this.addEventListener(e,t,n);else if(this[p])i.onKeyValue(this,e,t,n);else{if(e||!this[g])throw new Error("can-event-queue: Unable to bind "+e);i.onValue(this,t,n)}return this},off:function(e,t,n){if(c(this))"string"==typeof t?s.removeDelegateListener(this,e,t,n):s.removeEventListener(this,e,t,n);else if(this[y])this[y](e,t,n);else if("removeEventListener"in this)this.removeEventListener(e,t,n);else if(this[h])i.offKeyValue(this,e,t,n);else{if(e||!this[m])throw new Error("can-event-queue: Unable to unbind "+e);i.offValue(this,t,n)}return this}},k={"can.onKeyValue":function(e,t,n){w(this).handlers.add([e,"onKeyValue",n||"mutate",t])},"can.offKeyValue":function(e,t,n){w(this).handlers.delete([e,"onKeyValue",n||"mutate",t])},"can.isBound":function(){return!w(this).handlers.isEmpty()},"can.getWhatIChange":function(e){},"can.onPatches":function(e,t){w(this).handlers.add(["can.patches","onKeyValue",t||"notify",e])},"can.offPatches":function(e,t){w(this).handlers.delete(["can.patches","onKeyValue",t||"notify",e])}};function O(e,t,n){Object.defineProperty(e,t,{enumerable:!1,value:n})}O(a=function(e){return i.assignMap(e,_),i.assignSymbols(e,k)},"addHandlers",b),O(a,"stopListeningArgumentsToKeys",x),_.bind=_.addEventListener,_.unbind=_.removeEventListener,i.assignMap(a,_),i.assignSymbols(a,k),O(a,"start",function(){console.warn("use can-queues.batch.start()"),u.batch.start()}),O(a,"stop",function(){console.warn("use can-queues.batch.stop()"),u.batch.stop()}),O(a,"flush",function(){console.warn("use can-queues.flush()"),u.flush()}),O(a,"afterPreviousEvents",function(e){console.warn("don't use afterPreviousEvents"),u.mutateQueue.enqueue(function(){u.mutateQueue.enqueue(e)}),u.flush()}),O(a,"after",function(e){console.warn("don't use after"),u.mutateQueue.enqueue(e),u.flush()}),n.exports=a}),define("can-simple-observable/resolver/resolver",["require","exports","module","can-reflect","can-symbol","can-observation-recorder","can-observation","can-queues","can-event-queue/map/map","can-simple-observable/settable/settable","can-simple-observable"],function(e,t,n){"use strict";var o=e("can-reflect"),r=e("can-symbol"),a=e("can-observation-recorder"),i=(e("can-observation"),e("can-queues")),s=e("can-event-queue/map/map"),c=e("can-simple-observable/settable/settable"),u=e("can-simple-observable"),l=r.for("can.getChangesDependencyRecord");function f(e,t,n){this.resolver=a.ignore(e),this.context=t,this._valueOptions={resolve:this.resolve.bind(this),listenTo:this.listenTo.bind(this),stopListening:this.stopListening.bind(this),lastSet:new u(n)},this.update=this.update.bind(this),this.contextHandlers=new WeakMap,this.teardown=null,this.binder={}}function d(e,t,n,r){s.off.call(e,t,r,n)}f.prototype=Object.create(c.prototype),o.assignMap(f.prototype,{constructor:f,listenTo:function(e,t,n,r){o.isPrimitive(e)&&(n=t,t=e,e=this.context),"function"==typeof t&&(n=t,t=void 0);var a=this,i=n.bind(this.context);i[l]=function(){var e=new Set;return e.add(a),{valueDependencies:e}},this.contextHandlers.set(n,i),s.listenTo.call(this.binder,e,t,i,r||"notify")},stopListening:function(){var e=this.binder[r.for("can.meta")],t=e&&e.listenHandlers;if(t){var n=s.stopListeningArgumentsToKeys.call({context:this.context,defaultQueue:"notify"});t.delete(n,d)}return this},resolve:function(e){if(this._value=e,this.isBinding)return this.lastValue=this._value,e;if(this._value!==this.lastValue){i.batch.start(),i.deriveQueue.enqueue(this.update,this,[],{}),i.batch.stop()}return e},update:function(){if(this.lastValue!==this._value){var e=this.lastValue;this.lastValue=this._value,i.enqueueByQueue(this.handlers.getNode([]),this,[this._value,e])}},activate:function(){this.isBinding=!0,this.teardown=this.resolver.call(this.context,this._valueOptions),this.isBinding=!1},onUnbound:function(){this.bound=!1,s.stopListening.call(this.binder),null!=this.teardown&&(this.teardown(),this.teardown=null)},set:function(e){this._valueOptions.lastSet.set(e)},get:function(){if(a.isRecording()&&(a.add(this),this.bound||this.onBound()),!0===this.bound)return this._value;var e=function(){};this.on(e);var t=this._value;return this.off(e),t},hasDependencies:function(){var e=!1;if(this.bound){var t=this.binder[r.for("can.meta")];e=!!(t&&t.listenHandlers).size()}return e},getValueDependencies:function(){if(this.bound){var e=this.binder[r.for("can.meta")],t=e&&e.listenHandlers,a=new Map,i=new Set;if(t&&(o.each(t.root,function(e,r){o.each(e,function(e,t){if(void 0===t)i.add(r);else{var n=a.get(r);n||(n=new Set,a.set(r,n)),n.add(t)}})}),i.size||a.size)){var n={};return a.size&&(n.keyDependencies=a),i.size&&(n.valueDependencies=i),n}}}}),o.assignSymbols(f.prototype,{"can.getValue":f.prototype.get,"can.setValue":f.prototype.set,"can.isMapLike":!1,"can.getPriority":function(){return this.priority||0},"can.setPriority":function(e){this.priority=e},"can.valueHasDependencies":f.prototype.hasDependencies,"can.getValueDependencies":f.prototype.getValueDependencies}),n.exports=f}),define("can-event-queue/type/type",["require","exports","module","can-reflect","can-symbol","can-key-tree","can-queues"],function(e,t,n){"use strict";var r=e("can-reflect"),a=e("can-symbol"),i=e("can-key-tree"),o=e("can-queues"),s=a.for("can.meta");function c(e,t){t.lifecycleHandlers||(t.lifecycleHandlers=new i([Object,Array])),t.instancePatchesHandlers||(t.instancePatchesHandlers=new i([Object,Array]))}function u(e){var t=e[s];return t||(t={},r.setKeyValue(e,s,t)),c(0,t),t}var l={};function f(e,t,n){l["can.on"+e]=function(e,t){u(this)[n].add([t||"mutate",e])},l["can.off"+e]=function(e,t){u(this)[n].delete([t||"mutate",e])},l["can."+t]=function(e,t){o.enqueueByQueue(u(this)[n].getNode([]),this,[e,t])}}function d(e){return r.assignSymbols(e,l)}f("InstancePatches","dispatchInstanceOnPatches","instancePatchesHandlers"),f("InstanceBoundChange","dispatchInstanceBoundChange","lifecycleHandlers"),Object.defineProperty(d,"addHandlers",{enumerable:!1,value:c}),n.exports=d}),define("can-string-to-any",function(e,t,n){"use strict";n.exports=function(e){switch(e){case"NaN":case"Infinity":return+e;case"null":return null;case"undefined":return;case"true":case"false":return"true"===e;default:var t=+e;return isNaN(t)?e:t}}}),define("can-data-types/maybe-boolean/maybe-boolean",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var r=e("can-reflect");function a(e){return null==e?e:!("false"===e||"0"===e||!e)}n.exports=r.assignSymbols(a,{"can.new":a,"can.getSchema":function(){return{type:"Or",values:[!0,!1,void 0,null]}},"can.getName":function(){return"MaybeBoolean"},"can.isMember":function(e){return null==e||"boolean"==typeof e}})}),define("can-data-types/maybe-date/maybe-date",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var r=e("can-reflect");function a(e){var t=typeof e;return"string"===t?(e=Date.parse(e),isNaN(e)?null:new Date(e)):"number"===t?new Date(e):e}function i(e){var t=a(this.setValue=e);this.value=null==t?t:t.getTime()}i.prototype.valueOf=function(){return this.value},r.assignSymbols(i.prototype,{"can.serialize":function(){return this.setValue}}),n.exports=r.assignSymbols(a,{"can.new":a,"can.getSchema":function(){return{type:"Or",values:[Date,void 0,null]}},"can.ComparisonSetType":i,"can.getName":function(){return"MaybeDate"},"can.isMember":function(e){return null==e||e instanceof Date}})}),define("can-data-types/maybe-number/maybe-number",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var r=e("can-reflect");function a(e){return null==e?e:+e}n.exports=r.assignSymbols(a,{"can.new":a,"can.getSchema":function(){return{type:"Or",values:[Number,void 0,null]}},"can.getName":function(){return"MaybeNumber"},"can.isMember":function(e){return null==e||"number"==typeof e}})}),define("can-data-types/maybe-string/maybe-string",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var r=e("can-reflect");function a(e){return null==e?e:""+e}n.exports=r.assignSymbols(a,{"can.new":a,"can.getSchema":function(){return{type:"Or",values:[String,void 0,null]}},"can.getName":function(){return"MaybeString"},"can.isMember":function(e){return null==e||"string"==typeof e}})}),define("can-define",["require","exports","module","can-namespace","can-symbol","can-reflect","can-observation","can-observation-recorder","can-simple-observable/async/async","can-simple-observable/settable/settable","can-simple-observable/resolver/resolver","can-event-queue/map/map","can-event-queue/type/type","can-queues","can-assign","can-log/dev/dev","can-string-to-any","can-define-lazy-value","can-data-types/maybe-boolean/maybe-boolean","can-data-types/maybe-date/maybe-date","can-data-types/maybe-number/maybe-number","can-data-types/maybe-string/maybe-string"],function(e,t,n){"use strict";var f,v,y,g,d,c,r=e("can-namespace"),p=e("can-symbol"),h=e("can-reflect"),i=e("can-observation"),m=e("can-observation-recorder"),o=e("can-simple-observable/async/async"),s=e("can-simple-observable/settable/settable"),a=e("can-simple-observable/resolver/resolver"),u=e("can-event-queue/map/map"),l=e("can-event-queue/type/type"),b=e("can-queues"),w=e("can-assign"),x=(e("can-log/dev/dev"),e("can-string-to-any")),_=e("can-define-lazy-value"),k=e("can-data-types/maybe-boolean/maybe-boolean"),O=e("can-data-types/maybe-date/maybe-date"),E=e("can-data-types/maybe-number/maybe-number"),L=e("can-data-types/maybe-string/maybe-string"),q=p.for("can.new"),S=p.for("can.serialize");function M(e){return e&&(!0===e.canDefineType||e[q])}var P=m.ignore(h.getValue.bind(h)),C=Object.defineProperty;function V(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:!0,value:n})}function j(e,t,n,r){void 0===t.value||"function"==typeof t.value&&0!==t.value.length||(t.default=t.value,delete t.value),void 0!==t.Value&&(t.Default=t.Value,delete t.Value)}function D(e){return"function"==typeof e.value&&e.value.length}n.exports=v=r.define=function(n,e,t){var r,a,i,o,s=Object.create(t?t.dataInitializers:null),c=Object.create(t?t.computedInitializers:null),u=d(e,t,n);if(u.dataInitializers=s,u.computedInitializers=c,h.eachKey(u.definitions,function(e,t){v.property(n,t,e,s,c,u.defaultDefinition)}),n.hasOwnProperty("_data"))for(r in s)_(n._data,r,s[r].bind(n),!0);else _(n,"_data",function(){var e={};for(var t in s)_(e,t,s[t].bind(this),!0);return e});if(n.hasOwnProperty("_computed"))for(r in c)_(n._computed,r,c[r].bind(n));else _(n,"_computed",function(){var e=Object.create(null);for(var t in c)_(e,t,c[t].bind(this));return e});(a=f,i=Object.getOwnPropertyNames(a),o="getOwnPropertySymbols"in Object?Object.getOwnPropertySymbols(a):[],i.concat(o)).forEach(function(e){Object.defineProperty(n,e,{enumerable:!1,value:f[e],configurable:!0,writable:!0})}),Object.defineProperty(n,"_define",{enumerable:!1,value:u,configurable:!0,writable:!0});var l=p.iterator||p.for("iterator");return n[l]||V(n,l,function(){return new v.Iterator(this)}),u};v.extensions=function(){},v.property=function(e,t,n,r,a,i){var o=v.extensions.apply(this,arguments);o&&(n=g(t,o,i||{},e));var s=n.type;if(s&&function(e){for(var t in e)if("type"!==t)return!1;return!0}(n)&&s===v.types["*"])C(e,t,{get:y.get.data(t),set:y.set.events(t,y.get.data(t),y.set.data(t),y.eventType.data(t)),enumerable:!0,configurable:!0});else{n.type=s;var c,u=n.get||D(n)?"computed":"data",l=y.read[u](t),f=y.get[u](t),d=y.set[u](t),p=function(e){return e};n.Type&&(p=y.set.Type(t,n.Type,p)),s&&(p=y.set.type(t,s,p));var h=y.set.events(t,l,d,y.eventType[u](t));D(n)?a[t]=y.valueResolver(t,n,p):void 0===n.default&&void 0===n.Default||(c=m.ignore(y.get.defaultValue(t,n,p,h))),n.get?a[t]=y.compute(t,n.get,c):c&&(r[t]=c),n.get&&n.set?d=y.set.setter(t,n.set,y.read.lastSet(t),d,!0):n.set?d=y.set.setter(t,n.set,l,h,!1):"data"===u?d=h:n.get&&n.get.length<1&&(d=function(){}),s&&(d=y.set.type(t,s,d)),n.Type&&(d=y.set.Type(t,n.Type,d)),C(e,t,{get:f,set:d,enumerable:"serialize"in n?!!n.serialize:!n.get,configurable:!0})}},v.makeDefineInstanceKey=function(a){a[p.for("can.defineInstanceKey")]=function(e,t){var n=this.prototype._define;"object"==typeof t&&j(0,t);var r=c(e,t,n.defaultDefinition,this);r&&"object"==typeof r?(v.property(a.prototype,e,r,n.dataInitializers,n.computedInitializers,n.defaultDefinition),n.definitions[e]=r):n.methods[e]=r,this.prototype.dispatch({type:"can.keys",target:this.prototype})}},v.Constructor=function(e,t){var n=function(e){Object.defineProperty(this,"__inSetup",{configurable:!0,enumerable:!1,value:!0,writable:!0}),v.setup.call(this,e,t),this.__inSetup=!1},r=v(n.prototype,e);return l(n),v.makeDefineInstanceKey(n,r),n},y={computeObj:function(n,r,e){var a={oldValue:void 0,compute:e,count:0,handler:function(e){var t=a.oldValue;a.oldValue=e,n.dispatch({type:r,target:n},[e,t])}};return a},valueResolver:function(t,n,e){var r=y.get.defaultValue(t,n,e);return function(){var e=r.call(this);return y.computeObj(this,t,new a(n.value,this,e))}},compute:function(n,r,a){return function(){var e,t=a&&a.call(this);return e=0===r.length?new i(r,this):1===r.length?new s(r,this,t):new o(r,this,t),y.computeObj(this,n,e)}},set:{data:function(t){return function(e){this._data[t]=e}},computed:function(t){return function(e){h.setValue(this._computed[t].compute,e)}},events:function(r,a,i,e){return function(e){if(this.__inSetup)i.call(this,e);else{var t,n=a.call(this);if(e!==n)i.call(this,e),t={patches:[{type:"set",key:r,value:e}],type:r,target:this},this.dispatch(t,[e,n])}}},setter:function(e,i,o,s,c){return function(e){var t=this;b.batch.start();var n=!1,r=o.call(this),a=i.call(this,e,function(e){s.call(t,e),n=!0},r);if(n)b.batch.stop();else if(c)if(void 0!==a)r!==a&&s.call(this,a),b.batch.stop();else{if(0===i.length)return s.call(this,e),void b.batch.stop();if(1!==i.length)return void b.batch.stop();b.batch.stop()}else if(void 0!==a)s.call(this,a),b.batch.stop();else{if(0===i.length)return s.call(this,e),void b.batch.stop();if(1!==i.length)return void b.batch.stop();s.call(this,void 0),b.batch.stop()}}},type:function(t,n,r){function e(e){return r.call(this,n.call(this,e,t))}return M(n)?n.canDefineType?e:function(e){return r.call(this,h.convert(e,n))}:"object"==typeof n?y.set.Type(t,n,r):e},Type:function(e,t,n){return Array.isArray(t)&&v.DefineList?t=v.DefineList.extend({"#":t[0]}):"object"==typeof t&&(t=v.DefineMap?v.DefineMap.extend(t):v.Constructor(t)),function(e){return e instanceof t||null==e?n.call(this,e):n.call(this,new t(e))}}},eventType:{data:function(n){return function(e,t){return void 0!==t||this._data.hasOwnProperty(n)?"set":"add"}},computed:function(){return function(){return"set"}}},read:{data:function(e){return function(){return this._data[e]}},computed:function(e){return function(){return h.getValue(this._computed[e].compute)}},lastSet:function(t){return function(){var e=this._computed[t].compute;if(e.lastSetValue)return h.getValue(e.lastSetValue)}}},get:{defaultValue:function(a,i,o,s){return function(){var e=i.default;if(void 0!==e)"function"==typeof e&&(e=e.call(this)),e=o.call(this,e);else{var t=i.Default;t&&(e=o.call(this,new t))}if(i.set){var n,r=!0;return y.set.setter(a,i.set,function(){},function(e){r?n=e:s.call(this,e)},i.get).call(this,e),r=!1,n}return e}},data:function(e){return function(){return this.__inSetup||m.add(this,e),this._data[e]}},computed:function(n){return function(e){var t=this._computed[n].compute;return m.isRecording()&&(m.add(this,n),h.isBound(t)||i.temporarilyBind(t)),P(t)}}}},v.behaviors=["get","set","value","Value","type","Type","serialize"];function I(e,t){var n=e._computed&&e._computed[t];n&&n.compute&&(n.count?n.count++:(n.count=1,h.onValue(n.compute,n.handler,"notify"),n.oldValue=P(n.compute)))}function T(e,t){var n=e._computed&&e._computed[t];n&&(1===n.count?(n.count=0,h.offValue(n.compute,n.handler,"notify")):n.count--)}g=function(e,t,n,r){var a={};if(h.eachKey(t,function(e,t){!function(e,t,n){if("enumerable"===t)e.serialize=!!n;else if("type"===t){var r=n;"string"==typeof r&&("object"!=typeof(r=v.types[r])||M(r)||(w(e,r),r=r[t])),void 0!==r&&(e[t]=r)}else e[t]=n}(a,t,e)}),h.eachKey(n,function(e,t){void 0===a[t]&&"type"!==t&&"Type"!==t&&(a[t]=e)}),t.Type){var i=t.Type,o=i[S];o&&(a.serialize=function(e){return o.call(e)}),i[q]&&(a.type=i,delete a.Type)}if("string"!=typeof t.type){if(!a.type&&!a.Type){var s=h.assignMap({},n);a=h.assignMap(s,a)}0===h.size(a)&&(a.type=v.types["*"])}return j(0,a),a},c=function(e,t,n,r){var a;return"string"==typeof t?a={type:t}:t&&(t[S]||t[q])?a={Type:t}:"function"==typeof t?h.isConstructorLike(t)&&(a={Type:t}):Array.isArray(t)?a={Type:t}:h.isPlainObject(t)&&(a=t),a?g(e,a,n,r):t},d=function(e,t,a){var i,o=Object.create(t?t.definitions:null),s={},n=e["*"];return i=n?(delete e["*"],c("*",n,{})):Object.create(null),function(e,t){for(var n in e)e.hasOwnProperty(n)&&t.call(e,n,Object.getOwnPropertyDescriptor(e,n))}(e,function(e,t){var n;if(n=t.get||t.set?{get:t.get,set:t.set}:t.value,"constructor"!==e){var r=c(e,n,i,a);r&&"object"==typeof r&&0<h.size(r)?o[e]=r:"function"==typeof r&&(s[e]=r)}else s[e]=n}),n&&V(e,"*",n),{definitions:o,methods:s,defaultDefinition:i}},f=u({});var A=p.for("can.meta");w(f,{_eventSetup:function(){},_eventTeardown:function(){},addEventListener:function(e,t,n){return I(this,e),u.addEventListener.apply(this,arguments)},removeEventListener:function(e,t){return T(this,e),u.removeEventListener.apply(this,arguments)}}),f.on=f.bind=f.addEventListener,f.off=f.unbind=f.removeEventListener;var N=p.for("can.onKeyValue"),K=p.for("can.offKeyValue");h.assignSymbols(f,{"can.onKeyValue":function(e){return I(this,e),u[N].apply(this,arguments)},"can.offKeyValue":function(e){return T(this,e),u[K].apply(this,arguments)}}),delete f.one,v.setup=function(e,t){Object.defineProperty(this,"constructor",{value:this.constructor,enumerable:!1,writable:!1}),Object.defineProperty(this,A,{value:Object.create(null),enumerable:!1,writable:!1});var n=this._define.definitions,r=Object.create(null),a=this;h.eachKey(e,function(e,t){void 0!==n[t]?a[t]=e:v.expando(a,t,e)}),0<h.size(r)&&V(this,"_instanceDefinitions",r)};var R=function(e){return e};v.expando=function(e,t,n){if(v._specialKeys[t])return!0;var r=e._define.definitions;if(!r||!r[t]){var a=e._instanceDefinitions;if(!a){if(Object.isSealed(e))return;Object.defineProperty(e,"_instanceDefinitions",{configurable:!0,enumerable:!1,writable:!0,value:{}}),a=e._instanceDefinitions}if(!a[t]){var i=e._define.defaultDefinition||{type:v.types.observable};return v.property(e,t,i,{},{}),i.type?e._data[t]=v.make.set.type(t,i.type,R).call(e,n):e._data[t]=v.types.observable(n),a[t]=i,e.__inSetup||(b.batch.start(),e.dispatch({type:"can.keys",target:e}),void 0!==e._data[t]&&e.dispatch({type:t,target:e,patches:[{type:"add",key:t,value:e._data[t]}]},[e._data[t],void 0]),b.batch.stop()),!0}}},v.replaceWith=_,v.eventsProto=f,v.defineConfigurableAndNotEnumerable=V,v.make=y,v.getDefinitionOrMethod=c,v._specialKeys={_data:!0,_computed:!0};var B={};function H(e){return h.isValueLike(e)&&h.isObservableLike(e)}v.makeSimpleGetterSetter=function(e){if(void 0===B[e]){var t=y.set.events(e,y.get.data(e),y.set.data(e),y.eventType.data(e));B[e]={get:y.get.data(e),set:function(e){return t.call(this,v.types.observable(e))},enumerable:!0,configurable:!0}}return B[e]},v.Iterator=function(e){this.obj=e,this.definitions=Object.keys(e._define.definitions),this.instanceDefinitions=e._instanceDefinitions?Object.keys(e._instanceDefinitions):Object.keys(e),this.hasGet="function"==typeof e.get},v.Iterator.prototype.next=function(){var e;if(this.definitions.length){if(e=this.definitions.shift(),this.obj._define.definitions[e].get)return this.next()}else{if(!this.instanceDefinitions.length)return{value:void 0,done:!0};e=this.instanceDefinitions.shift()}return{value:[e,this.hasGet?this.obj.get(e):this.obj[e]],done:!1}},v.types={date:O,number:E,boolean:k,observable:function(e){return Array.isArray(e)&&v.DefineList?e=new v.DefineList(e):h.isPlainObject(e)&&v.DefineMap&&(e=new v.DefineMap(e)),e},stringOrObservable:function(e){return Array.isArray(e)?new v.DefaultList(e):h.isPlainObject(e)?new v.DefaultMap(e):h.convert(e,v.types.string)},htmlbool:function(e){return""===e||!!x(e)},"*":function(e){return e},any:function(e){return e},string:L,compute:{set:function(e,t,n,r){return H(e)?e:H(r)?(h.setValue(r,e),r):e},get:function(e){return H(e)?h.getValue(e):e}}},v.updateSchemaKeys=function(e,t){for(var n in t){var r=t[n];!1!==r.serialize&&(r.Type?e.keys[n]=r.Type:r.type?e.keys[n]=r.type:e.keys[n]=function(e){return e},!0===t[n].identity&&e.identity.push(n))}return e}}),define("can-string",function(e,t,n){"use strict";var r=/\=\=/,a=/([A-Z]+)([A-Z][a-z])/g,i=/([a-z\d])([A-Z])/g,o=/([a-z\d])([A-Z])/g,s=/"/g,c=/'/g,u=/-+(.)?/g,l=/[a-z][A-Z]/g,f=function(e){return""+(null==e||isNaN(e)&&""+e=="NaN"?"":e)},d={esc:function(e){return f(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(s,"&#34;").replace(c,"&#39;")},capitalize:function(e){return e.charAt(0).toUpperCase()+e.slice(1)},camelize:function(e){return f(e).replace(u,function(e,t){return t?t.toUpperCase():""})},hyphenate:function(e){return f(e).replace(l,function(e){return e.charAt(0)+"-"+e.charAt(1).toLowerCase()})},underscore:function(e){return e.replace(r,"/").replace(a,"$1_$2").replace(i,"$1_$2").replace(o,"_").toLowerCase()},undHash:/_|-/};n.exports=d}),define("can-construct",["require","exports","module","can-reflect","can-log/dev/dev","can-namespace"],function(e,t,n){"use strict";var r,v=e("can-reflect"),a=(e("can-log/dev/dev"),e("can-namespace")),y=0,g=function(){if(arguments.length)return g.extend.apply(g,arguments)};try{Object.getOwnPropertyDescriptor({}),r=!0}catch(e){r=!1}var m=function(e,t,n){Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:!1,value:n})};v.assignMap(g,{constructorExtends:!0,newInstance:function(){var e,t=this.instance();if(t.setup){if(Object.defineProperty(t,"__inSetup",{configurable:!0,enumerable:!1,value:!0,writable:!0}),(e=t.setup.apply(t,arguments))instanceof g.ReturnValue)return e.value;t.__inSetup=!1}return t.init&&t.init.apply(t,e||arguments),t},_inherit:r?function(e,t,n){var r,a,i,o;for(var s in n=n||e,e)a=e,i=s,(r=(o=Object.getOwnPropertyDescriptor(a,i))&&(o.get||o.set)?o:null)?this._defineProperty(n,t,s,r):g._overwrite(n,t,s,e[s])}:function(e,t,n){for(var r in n=n||e,e)g._overwrite(n,t,r,e[r])},_defineProperty:function(e,t,n,r){Object.defineProperty(e,n,r)},_overwrite:function(e,t,n,r){Object.defineProperty(e,n,{value:r,configurable:!0,enumerable:!0,writable:!0})},setup:function(e){var t=v.assignDeepMap({},e.defaults);this.defaults=v.assignDeepMap(t,this.defaults)},instance:function(){y=1;var e=new this;return y=0,e},extend:function(e,t,n){var r=e,a=t,i=n;"string"!=typeof r&&(i=a,a=r,r=null),i||(i=a,a=null),i=i||{};var o,s,c=this,u=this.prototype;function l(){if(!y)return this&&this.constructor===o||!arguments.length||!o.constructorExtends?o.newInstance.apply(o,arguments):o.extend.apply(o,arguments)}for(var f in s=this.instance(),g._inherit(i,u,s),r||(a&&a.shortName?r=a.shortName:this.shortName&&(r=this.shortName)),o="function"==typeof namedCtor?namedCtor(constructorName,l):function(){return l.apply(this,arguments)},c)c.hasOwnProperty(f)&&(o[f]=c[f]);if(g._inherit(a,c,o),v.assignMap(o,{constructor:o,prototype:s}),void 0!==r){if(Object.getOwnPropertyDescriptor){var d=Object.getOwnPropertyDescriptor(o,"name");d&&!d.configurable||Object.defineProperty(o,"name",{writable:!0,value:r,configurable:!0})}o.shortName=r}m(o.prototype,"constructor",o);var p=[c].concat(Array.prototype.slice.call(arguments)),h=o.setup.apply(o,p);return o.init&&o.init.apply(o,h||p),o},ReturnValue:function(e){this.value=e}}),m(g.prototype,"setup",function(){}),m(g.prototype,"init",function(){}),n.exports=a.Construct=g}),define("can-define/ensure-meta",["require","exports","module","can-symbol","can-reflect"],function(e,t,n){"use strict";var r=e("can-symbol"),a=e("can-reflect");n.exports=function(e){var t=r.for("can.meta"),n=e[t];return n||(n={},a.setKeyValue(e,t,n)),n}}),define("can-define/define-helpers/define-helpers",["require","exports","module","can-define","can-reflect","can-queues","can-log/dev/dev","can-define/ensure-meta"],function(e,t,n){"use strict";var r=e("can-define"),s=e("can-reflect"),a=e("can-queues"),c=e("can-log/dev/dev"),u=e("can-define/ensure-meta"),i={defineExpando:r.expando,reflectSerialize:function(r){var a=this._define.definitions,i=this._define.defaultDefinition;return this.forEach(function(e,t){var n=a[t];void 0!==(e=n&&"function"==typeof n.serialize?n.serialize.call(this,e,t):i&&"function"==typeof i.serialize?i.serialize.call(this,e,t):s.serialize(e))&&(r[t]=e)},this),r},reflectUnwrap:function(n){return this.forEach(function(e,t){void 0!==e&&(n[t]=s.unwrap(e))}),n},log:function(r){var a=this,i=function(e){return"string"==typeof e?JSON.stringify(e):e},e=u(a),o=e.allowedLogKeysSet||new Set;e.allowedLogKeysSet=o,r&&o.add(r),e._log=function(e,t){var n=e.type;"can.onPatches"===n||r&&!o.has(n)||"can.keys"===n||r&&!o.has(n)||("add"===n||"remove"===n?c.log(s.getName(a),"\n how ",i(n),"\n what ",i(t[0]),"\n index ",i(t[1])):c.log(s.getName(a),"\n key ",i(n),"\n is ",i(t[0]),"\n was ",i(t[1])))}},deleteKey:function(e){var t=this._instanceDefinitions;if(t&&Object.prototype.hasOwnProperty.call(t,e)&&!Object.isSealed(this)){delete t[e],a.batch.start(),this.dispatch({type:"can.keys",target:this});var n=this._data[e];void 0!==n&&(delete this._data[e],this.dispatch({type:e,target:this,patches:[{type:"delete",key:e}]},[void 0,n])),a.batch.stop()}else this.set(e,void 0);return this}};n.exports=i}),define("can-define/map/map",["require","exports","module","can-construct","can-define","can-define/define-helpers/define-helpers","can-observation-recorder","can-namespace","can-log","can-log/dev/dev","can-reflect","can-symbol","can-queues","can-event-queue/type/type"],function(e,t,n){"use strict";var r=e("can-construct"),i=e("can-define"),a=e("can-define/define-helpers/define-helpers"),o=e("can-observation-recorder"),s=e("can-namespace"),c=e("can-log"),u=(e("can-log/dev/dev"),e("can-reflect")),l=e("can-symbol"),f=e("can-queues"),d=e("can-event-queue/type/type"),p=function(e){var t=[];for(var n in e){var r=e[n];"object"==typeof r&&("serialize"in r?!r.serialize:r.get)||t.push(n)}return t};function h(e){f.batch.start(),u.assignDeepMap(this,e||{}),f.batch.stop()}function v(e){f.batch.start(),u.updateDeepMap(this,e||{}),f.batch.stop()}function y(e,t){a.defineExpando(this,e,t)||(this[e]=t)}function g(e){var t=this[e];return void 0!==t||e in this||Object.isSealed(this)?t:(o.add(this,e),this[e])}var m=l.for("can.getSchema");function b(){var e=this.prototype._define,t=e?e.definitions:{};return i.updateSchemaKeys({type:"map",identity:[],keys:{}},t)}var w,x,_,k=function(e){i.setup.call(this,e||{},this.constructor.seal)},O=r.extend("DefineMap",{setup:function(e){var t,n=this.prototype;if(O){var r=i(n,n,e.prototype._define);for(t in i.makeDefineInstanceKey(this,r),d(this),O.prototype)i.defineConfigurableAndNotEnumerable(n,t,n[t]);n.setup===O.prototype.setup&&i.defineConfigurableAndNotEnumerable(n,"setup",k);var a=Object.getOwnPropertyDescriptor(n,"_computed").get;Object.defineProperty(n,"_computed",{configurable:!0,enumerable:!1,get:function(){if(this!==n)return a.call(this,arguments)}})}else for(t in n)i.defineConfigurableAndNotEnumerable(n,t,n[t]);i.defineConfigurableAndNotEnumerable(n,"constructor",this),this[m]=b}},{setup:function(e,t){this._define||(Object.defineProperty(this,"_define",{enumerable:!1,value:{definitions:{}}}),Object.defineProperty(this,"_data",{enumerable:!1,value:{}})),i.setup.call(this,e||{},!0===t)},get:function(e){return e?g.call(this,e):u.unwrap(this,Map)},set:function(e,t){return"object"==typeof e?!0===t?v.call(this,e):h.call(this,e):y.call(this,e,t),this},assignDeep:function(e){return h.call(this,e),this},updateDeep:function(e){return v.call(this,e),this},assign:function(e){return function(e){f.batch.start(),u.assignMap(this,e||{}),f.batch.stop()}.call(this,e),this},update:function(e){return function(e){f.batch.start(),u.updateMap(this,e||{}),f.batch.stop()}.call(this,e),this},serialize:function(){return u.serialize(this,Map)},deleteKey:a.deleteKey,forEach:(w=function(e,t,n){return u.eachKey(e,t,n)},x=o.ignore(w),function(e,t,n){return!1===n?x(this,e,t):w(this,e,t)}),"*":{type:i.types.observable}}),E={"can.isMapLike":!0,"can.isListLike":!1,"can.isValueLike":!1,"can.getKeyValue":g,"can.setKeyValue":y,"can.deleteKeyValue":a.deleteKey,"can.getOwnKeys":function(){var e=u.getOwnEnumerableKeys(this);if(this._computed)for(var t,n=u.getOwnKeys(this._computed),r=0;r<n.length;r++)t=n[r],e.indexOf(t)<0&&e.push(t);return e},"can.getOwnEnumerableKeys":function(){return o.add(this,"can.keys"),o.add(Object.getPrototypeOf(this),"can.keys"),p(this._define.definitions).concat(p(this._instanceDefinitions))},"can.hasOwnKey":function(e){return Object.hasOwnProperty.call(this._define.definitions,e)||void 0!==this._instanceDefinitions&&Object.hasOwnProperty.call(this._instanceDefinitions,e)},"can.hasKey":function(e){return e in this._define.definitions||void 0!==this._instanceDefinitions&&e in this._instanceDefinitions},"can.assignDeep":h,"can.updateDeep":v,"can.unwrap":a.reflectUnwrap,"can.serialize":a.reflectSerialize,"can.keyHasDependencies":function(e){return!!(this._computed&&this._computed[e]&&this._computed[e].compute)},"can.getKeyDependencies":function(e){var t;return this._computed&&this._computed[e]&&this._computed[e].compute&&((t={}).valueDependencies=new Set,t.valueDependencies.add(this._computed[e].compute)),t}};for(var L in u.assignSymbols(O.prototype,E),u.setKeyValue(O.prototype,l.iterator,function(){return new i.Iterator(this)}),i.eventsProto)O[L]=i.eventsProto[L],Object.defineProperty(O.prototype,L,{enumerable:!1,value:i.eventsProto[L],writable:!0});("getOwnPropertySymbols"in Object?Object.getOwnPropertySymbols(i.eventsProto):(_=i.eventsProto,Object.getOwnPropertyNames(_).filter(function(e){return 0===e.indexOf("@@symbol")}))).forEach(function(e){Object.defineProperty(O.prototype,e,{configurable:!0,enumerable:!1,value:i.eventsProto[e],writable:!0})}),i.DefineMap=O,Object.defineProperty(O.prototype,"toObject",{enumerable:!1,writable:!0,value:function(){return c.warn("Use DefineMap::get instead of DefineMap::toObject"),this.get()}}),n.exports=s.DefineMap=O}),define("can-cid",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace"),a=0,i="can"+new Date,o=function(e,t){var n=e.nodeName?i:"_cid";return e[n]||(a++,e[n]=(t||"")+a),e[n]};if(o.domExpando=i,o.get=function(e){var t=typeof e;return null!==t&&("object"===t||"function"===t)?o(e):t+":"+e},r.cid)throw new Error("You can't have two versions of can-cid, check your dependencies");n.exports=r.cid=o}),define("can-single-reference",["require","exports","module","can-cid"],function(s,e,t){!function(e,t,n,r){"use strict";var a,i=s("can-cid");function o(e,t){return(t?i(e)+":"+t:i(e))||e}a={set:function(e,t,n,r){e[o(t,r)]=n},getAndDelete:function(e,t,n){var r=o(t,n),a=e[r];return delete e[r],a}},r.exports=a}(0,0,0,t)}),define("can-define/list/list",["require","exports","module","can-construct","can-define","can-queues","can-event-queue/type/type","can-observation-recorder","can-log","can-log/dev/dev","can-define/define-helpers/define-helpers","can-assign","can-diff/list/list","can-namespace","can-reflect","can-symbol","can-single-reference"],function(e,t,n){"use strict";var r=e("can-construct"),a=e("can-define"),i=a.make,l=e("can-queues"),o=e("can-event-queue/type/type"),s=e("can-observation-recorder"),c=e("can-log"),u=(e("can-log/dev/dev"),e("can-define/define-helpers/define-helpers")),f=e("can-assign"),d=e("can-diff/list/list"),p=e("can-namespace"),h=e("can-reflect"),v=e("can-symbol"),y=e("can-single-reference"),g=[].splice,m=!1,b=function(e){return e},w="can.patches",x=a.eventsProto[v.for("can.onKeyValue")],_=a.eventsProto[v.for("can.offKeyValue")],k=v.for("can.getSchema");function O(){var e=this.prototype._define.definitions,t={type:"list",keys:{}};return(t=a.updateSchemaKeys(t,e)).keys["#"]&&(t.values=e["#"].Type,delete t.keys["#"]),t}var E=r.extend("DefineList",{setup:function(e){if(E){o(this);var t=this.prototype,n=a(t,t,e.prototype._define);a.makeDefineInstanceKey(this,n);var r=n.definitions["#"]||n.defaultDefinition;r&&(r.Type?this.prototype.__type=i.set.Type("*",r.Type,b):r.type&&(this.prototype.__type=i.set.type("*",r.type,b))),this[k]=O}}},{setup:function(e){this._define||(Object.defineProperty(this,"_define",{enumerable:!1,value:{definitions:{length:{type:"number"},_length:{type:"number"}}}}),Object.defineProperty(this,"_data",{enumerable:!1,value:{}})),a.setup.call(this,{},!1),Object.defineProperty(this,"_length",{enumerable:!1,configurable:!0,writable:!0,value:0}),e&&this.splice.apply(this,[0,0].concat(h.toArray(e)))},__type:a.types.observable,_triggerChange:function(e,t,n,r){var a=+e;if(isNaN(a))this.dispatch({type:""+e,target:this},[n,r]);else{var i,o=this._define.definitions["#"];"add"===t?(o&&"function"==typeof o.added&&s.ignore(o.added).call(this,n,a),i={type:t,patches:[{type:"splice",insert:n,index:a,deleteCount:0}]},this.dispatch(i,[n,a])):"remove"===t?(o&&"function"==typeof o.removed&&s.ignore(o.removed).call(this,r,a),i={type:t,patches:[{type:"splice",index:a,deleteCount:r.length}]},this.dispatch(i,[r,a])):this.dispatch(t,[n,a])}},get:function(e){return arguments.length?(isNaN(e)?s.add(this,e):s.add(this,"length"),this[e]):h.unwrap(this,Map)},set:function(e,t){if("object"!=typeof e)if("number"==typeof(e=isNaN(+e)||e%1?e:+e)){if("number"==typeof e&&e>this._length-1){var n=new Array(e+1-this._length);return n[n.length-1]=t,this.push.apply(this,n),n}this.splice(e,1,t)}else{u.defineExpando(this,e,t)||(this[e]=t)}else h.isListLike(e)?t?this.replace(e):h.assignList(this,e):h.assignMap(this,e);return this},assign:function(e){return h.isListLike(e)?h.assignList(this,e):h.assignMap(this,e),this},update:function(e){return h.isListLike(e)?h.updateList(this,e):h.updateMap(this,e),this},assignDeep:function(e){return h.isListLike(e)?h.assignDeepList(this,e):h.assignDeepMap(this,e),this},updateDeep:function(e){return h.isListLike(e)?h.updateDeepList(this,e):h.updateDeepMap(this,e),this},_items:function(){var t=[];return this._each(function(e){t.push(e)}),t},_each:function(e){for(var t=0,n=this._length;t<n;t++)e(this[t],t)},splice:function(e,t){var n,r,a,i=h.toArray(arguments),o=[],s=2<i.length,c=this._length;for(e=e||0,n=0,r=i.length-2;n<r;n++)i[a=n+2]=this.__type(i[a],a),o.push(i[a]),this[n+e]!==i[a]&&(s=!1);if(s&&this._length<=o.length)return o;void 0===t&&(t=i[1]=this._length-e),m=!0;var u=g.apply(this,i);return m=!1,l.batch.start(),0<t&&this._triggerChange(""+e,"remove",void 0,u),2<i.length&&this._triggerChange(""+e,"add",o,u),this.dispatch("length",[this._length,c]),l.batch.stop(),u},serialize:function(){return h.serialize(this,Map)}});for(var L in a.eventsProto)Object.defineProperty(E.prototype,L,{enumerable:!1,value:a.eventsProto[L],writable:!0});("getOwnPropertySymbols"in Object?Object.getOwnPropertySymbols(a.eventsProto):[v.for("can.onKeyValue"),v.for("can.offKeyValue")]).forEach(function(e){Object.defineProperty(E.prototype,e,{configurable:!0,enumerable:!1,value:a.eventsProto[e],writable:!0})});for(var L in h.eachKey({push:"length",unshift:0},function(i,e){var o=[][e];E.prototype[e]=function(){for(var e,t,n=[],r=i?this._length:0,a=arguments.length;a--;)t=arguments[a],n[a]=this.__type(t,a);return m=!0,e=o.apply(this,n),m=!1,this.comparator&&!n.length||(l.batch.start(),this._triggerChange(""+r,"add",n,void 0),this.dispatch("length",[this._length,r]),l.batch.stop()),e}}),h.eachKey({pop:"length",shift:0},function(i,e){var o=[][e];E.prototype[e]=function(){if(this._length){var e,t,n=(t=arguments)[0]&&Array.isArray(t[0])?t[0]:h.toArray(t),r=i&&this._length?this._length-1:0,a=this._length?this._length:0;return m=!0,e=o.apply(this,n),m=!1,l.batch.start(),this._triggerChange(""+r,"remove",void 0,[e]),this.dispatch("length",[this._length,a]),l.batch.stop(),e}}}),h.eachKey({map:3,filter:3,reduce:4,reduceRight:4,every:3,some:3},function(o,s){E.prototype[s]=function(){var n,t=this,e=[].slice.call(arguments,0),r=e[0],a=e[o-1]||t;"object"==typeof r&&(n=r,r=function(e){for(var t in n)if(e[t]!==n[t])return!1;return!0}),e[0]=function(){var e=[].slice.call(arguments,0);return e[o-3]=t.get(e[o-2]),r.apply(a,e)};var i=Array.prototype[s].apply(this,e);return"map"===s?new E(i):"filter"===s?new t.constructor(i):i}}),f(E.prototype,{indexOf:function(e,t){for(var n=t||0,r=this.length;n<r;n++)if(this.get(n)===e)return n;return-1},lastIndexOf:function(e,t){for(var n=t=void 0===t?this.length-1:t;0<=n;n--)if(this.get(n)===e)return n;return-1},join:function(){return s.add(this,"length"),[].join.apply(this,arguments)},reverse:function(){var e=[].reverse.call(this._items());return this.replace(e)},slice:function(){s.add(this,"length");var e=Array.prototype.slice.apply(this,arguments);return new this.constructor(e)},concat:function(){var t=[];return h.eachIndex(arguments,function(e){h.isListLike(e)?(Array.isArray(e)?e:h.toArray(e)).forEach(function(e){t.push(this.__type(e))},this):t.push(this.__type(e))},this),new this.constructor(Array.prototype.concat.apply(h.toArray(this),t))},forEach:function(e,t){for(var n,r=0,a=this.length;r<a&&(n=this.get(r),!1!==e.call(t||n,n,r,this));r++);return this},replace:function(e){var t=d(this,e);l.batch.start();for(var n=0,r=t.length;n<r;n++)this.splice.apply(this,[t[n].index,t[n].deleteCount].concat(t[n].insert));return l.batch.stop(),this},sort:function(e){var t=Array.prototype.slice.call(this);return Array.prototype.sort.call(t,e),this.splice.apply(this,[0,t.length].concat(t)),this}}),a.eventsProto)E[L]=a.eventsProto[L],Object.defineProperty(E.prototype,L,{enumerable:!1,value:a.eventsProto[L],writable:!0});Object.defineProperty(E.prototype,"length",{get:function(){return this.__inSetup||s.add(this,"length"),this._length},set:function(e){if(m)this._length=e;else if(null!=e&&!isNaN(+e)&&e!==this._length)if(e>this._length-1){var t=new Array(e-this._length);this.push.apply(this,t)}else this.splice(e)},enumerable:!0}),E.prototype.attr=function(e,t){return c.warn("DefineMap::attr shouldn't be called"),0===arguments.length?this.get():e&&"object"==typeof e?this.set.apply(this,arguments):1===arguments.length?this.get(e):this.set(e,t)},E.prototype.item=function(e,t){return 1===arguments.length?this.get(e):this.set(e,t)};var q={"can.isMoreListLikeThanMapLike":!0,"can.isMapLike":!0,"can.isListLike":!0,"can.isValueLike":!(E.prototype.items=function(){return c.warn("DefineList::get should should be used instead of DefineList::items"),this.get()}),"can.getKeyValue":E.prototype.get,"can.setKeyValue":E.prototype.set,"can.onKeyValue":function(e,t,n){var r;return isNaN(e)?x.apply(this,arguments):(r=function(){t(this[e])},y.set(t,this,r,e),x.call(this,"length",r,n))},"can.offKeyValue":function(e,t,n){var r;return isNaN(e)?_.apply(this,arguments):(r=y.getAndDelete(t,this,e),_.call(this,"length",r,n))},"can.deleteKeyValue":function(e){if("number"==typeof(e=isNaN(+e)||e%1?e:+e))this.splice(e,1);else{if("length"===e||"_length"===e)return;this.set(e,void 0)}return this},"can.assignDeep":function(e){l.batch.start(),h.assignList(this,e),l.batch.stop()},"can.updateDeep":function(e){l.batch.start(),this.replace(e),l.batch.stop()},"can.keyHasDependencies":function(e){return!!(this._computed&&this._computed[e]&&this._computed[e].compute)},"can.getKeyDependencies":function(e){var t;return this._computed&&this._computed[e]&&this._computed[e].compute&&((t={}).valueDependencies=new Set,t.valueDependencies.add(this._computed[e].compute)),t},"can.splice":function(e,t,n){this.splice.apply(this,[e,t].concat(n))},"can.onPatches":function(e,t){this[v.for("can.onKeyValue")](w,e,t)},"can.offPatches":function(e,t){this[v.for("can.offKeyValue")](w,e,t)}};h.assignSymbols(E.prototype,q),h.setKeyValue(E.prototype,v.iterator,function(){var e=-1;return"number"!=typeof this.length&&(this.length=0),{next:function(){return{value:this[++e],done:e>=this.length}}.bind(this)}}),a.DefineList=E,n.exports=p.DefineList=E}),define("can/es/can-define",["exports","can-define","can-define/map/map","can-define/list/list"],function(e,t,n,r){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"define",{enumerable:!0,get:function(){return a(t).default}}),Object.defineProperty(e,"DefineMap",{enumerable:!0,get:function(){return a(n).default}}),Object.defineProperty(e,"DefineList",{enumerable:!0,get:function(){return a(r).default}})}),define("can-key/utils",function(e,t,n){"use strict";var r={isContainer:function(e){var t=typeof e;return e&&("object"===t||"function"===t)},strReplacer:/\{([^\}]+)\}/g,parts:function(e){return Array.isArray(e)?e:void 0!==e?(e+"").replace(/\[/g,".").replace(/]/g,"").split("."):[]}};n.exports=r}),define("can-key/delete/delete",["require","exports","module","can-reflect","can-key/utils"],function(e,t,n){"use strict";var i=e("can-reflect"),o=e("can-key/utils");n.exports=function(e,t){for(var n=o.parts(t),r=e,a=0;a<n.length-1;a++)r&&(r=i.getKeyValue(r,n[a]));r&&i.deleteKeyValue(r,n[n.length-1])}}),define("can-key/get/get",["require","exports","module","can-reflect","can-key/utils"],function(e,t,n){"use strict";var s=e("can-reflect"),c=e("can-key/utils");n.exports=function(e,t){var n,r,a,i=c.parts(t),o=i.length;if(!o)return e;for(n=e,r=0;r<o&&c.isContainer(n)&&null!==n;r++)a=n,n=s.getKeyValue(a,i[r]);return n}}),define("can-key/replace-with/replace-with",["require","exports","module","can-key/utils","can-key/get/get","can-key/delete/delete"],function(e,t,n){"use strict";var o=e("can-key/utils"),s=e("can-key/get/get"),c=e("can-key/delete/delete");n.exports=function(e,r,a,i){return e.replace(o.strReplacer,function(e,t){var n=s(r,t);return i&&c(r,t),a?a(t,n):n})}}),define("can-key/set/set",["require","exports","module","can-reflect","can-symbol","can-key/utils"],function(e,t,n){"use strict";var s=e("can-reflect"),r=e("can-symbol"),c=e("can-key/utils");r.for("can.setValue");n.exports=function(e,t,n){for(var r=c.parts(t),a=e,i=r.length,o=0;o<i-1&&c.isContainer(a);o++)a=s.getKeyValue(a,r[o]);if(!a)throw new TypeError("Cannot set value at key path '"+t+"'");return s.setKeyValue(a,r[o],n),e}}),define("can-key/walk/walk",["require","exports","module","can-reflect","can-key/utils"],function(e,t,n){"use strict";var l=e("can-reflect"),f=e("can-key/utils");n.exports=function(e,t,n){var r,a,i,o,s=f.parts(t),c=s.length;if(c)for(r=e,a=0;a<c;a++){var u=n({parent:i=r,key:o=s[a],value:r=f.isContainer(i)&&l.getKeyValue(i,o)},a);void 0!==u&&(r=u)}}}),define("can-key/transform/transform",["require","exports","module","can-key/walk/walk","can-key/utils","can-reflect"],function(e,t,n){"use strict";var s=e("can-key/walk/walk"),c=e("can-key/utils"),u=e("can-reflect");n.exports=function(e,t){var o=u.serialize(e);return u.eachKey(t,function(e,t){var n=c.parts(t),r=c.parts(e),a=[];s(o,n,function(e){a.push(e)});var i=a[a.length-1].value;void 0!==i&&(s(o,r,function(e,t){if(t<r.length-1&&!e.value)return e.parent[e.key]={};t===r.length-1&&(e.parent[e.key]=i)}),function(e){for(var t=e.length-1;0<=t;t--){var n=e[t];if(delete n.parent[n.key],0!==u.size(n.parent))return}}(a))}),o}}),define("can-key",["require","exports","module","can-key/delete/delete","can-key/get/get","can-key/replace-with/replace-with","can-key/set/set","can-key/transform/transform","can-key/walk/walk","can-namespace"],function(e,t,n){"use strict";var r=e("can-key/delete/delete"),a=e("can-key/get/get"),i=e("can-key/replace-with/replace-with"),o=e("can-key/set/set"),s=e("can-key/transform/transform"),c=e("can-key/walk/walk"),u=e("can-namespace");n.exports=u.key={deleteKey:r,get:a,replaceWith:i,set:o,transform:s,walk:c}}),define("can-simple-observable/key/key",["require","exports","module","can-key","can-key/utils","can-reflect","can-observation"],function(e,t,n){var s=e("can-key"),c=e("can-key/utils"),u=e("can-reflect"),l=e("can-observation");n.exports=function(t,e){var r=c.parts(e),a=r.length-1,n=new l(function(){var n;return s.walk(t,r,function(e,t){t===a&&(n=e.value)}),n}),i=function(e){s.set(t,r,e)};Object.defineProperty(n,"value",{get:n.get,set:i});var o={"can.setValue":i};return u.assignSymbols(n,o)}}),define("can-value",["require","exports","module","can-key","can-reflect","can-simple-observable/key/key","can-namespace","can-observation","can-simple-observable","can-simple-observable/settable/settable"],function(e,t,n){"use strict";var r=e("can-key"),a=e("can-reflect"),i=e("can-simple-observable/key/key"),o=e("can-namespace"),s=e("can-observation"),c=e("can-simple-observable"),u=e("can-simple-observable/settable/settable");n.exports=o.value={bind:function(e,t){return i(e,t)},from:function(e,t){return new s(function(){return r.get(e,t)})},returnedBy:function(e,t,n){return 1===e.length?new u(e,t,n):new s(e,t)},to:function(e,t){var n=i(e,t);return a.assignSymbols(n,{"can.getValue":null})},with:function(e){return new c(e)}}}),define("can/es/can-value",["exports","can-value"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-observation",["exports","can-observation"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-observation-recorder",["exports","can-observation-recorder"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-simple-map",["require","exports","module","can-construct","can-event-queue/map/map","can-queues","can-observation-recorder","can-reflect","can-log/dev/dev","can-symbol"],function(e,t,n){"use strict";var r=e("can-construct"),a=e("can-event-queue/map/map"),s=e("can-queues"),c=e("can-observation-recorder"),u=e("can-reflect"),i=(e("can-log/dev/dev"),e("can-symbol"),r.extend("SimpleMap",{setup:function(e){this._data={},e&&"object"==typeof e&&this.attr(e)},attr:function(e,t){var n=this;if(0===arguments.length){c.add(this,"can.keys");var r={};return u.eachKey(this._data,function(e,t){c.add(this,t),r[t]=e},this),r}if(1<arguments.length){var a=this._data.hasOwnProperty(e),i=this._data[e];if(i!==(this._data[e]=t)){var o={keyChanged:a?void 0:e,type:e};this.dispatch(o,[t,i])}}else{if("object"!=typeof e)return"constructor"!==e?(c.add(this,e),this._data[e]):this.constructor;s.batch.start(),u.eachKey(e,function(e,t){n.attr(t,e)}),s.batch.stop()}},serialize:function(){return u.serialize(this,Map)},get:function(){return this.attr.apply(this,arguments)},set:function(){return this.attr.apply(this,arguments)},log:function(e){}}));a(i.prototype);var o={"can.isMapLike":!0,"can.isListLike":!1,"can.isValueLike":!1,"can.getKeyValue":i.prototype.get,"can.setKeyValue":i.prototype.set,"can.deleteKeyValue":function(e){var t;if(this._data.hasOwnProperty(e)){var n=this._data[e];delete this._data[e],t={keyChanged:e,type:e},this.dispatch(t,[void 0,n])}},"can.getOwnEnumerableKeys":function(){return c.add(this,"can.keys"),Object.keys(this._data)},"can.assignDeep":function(e){s.batch.start(),u.assignMap(this,e),s.batch.stop()},"can.updateDeep":function(e){s.batch.start(),u.updateMap(this,e),s.batch.stop()},"can.keyHasDependencies":function(e){return!1},"can.getKeyDependencies":function(e){},"can.hasOwnKey":function(e){return this._data.hasOwnProperty(e)}};u.assignSymbols(i.prototype,o),n.exports=i}),define("can/es/can-simple-map",["exports","can-simple-map"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-bind",["require","exports","module","can-reflect","can-symbol","can-namespace","can-queues","can-assign"],function(e,t,n){"use strict";var c=e("can-reflect"),r=e("can-symbol"),a=e("can-namespace"),i=e("can-queues"),o=e("can-assign"),u=(r.for("can.getChangesDependencyRecord"),r.for("can.getValue")),s=r.for("can.onValue"),l=r.for("can.onEmit"),f=r.for("can.offEmit"),d=r.for("can.setValue");function p(e,t){c.setValue(t,e)}function h(e,t,n){return e[l](t,n)}function v(e,t,n){return e[f](t,n)}function y(e,t,n,r){var a;e[s]?a=c.offValue:e[l]&&(a=v),a&&a(e,n,r)}function g(e,t,n,r){var a;e[s]?a=c.onValue:e[l]&&(a=h),a&&a(e,n,r)}function m(e,t){this.value=0,this._binding=e,this._type=t}function b(t){void 0===(this._options=t).queue&&(t.queue="domUI"),0<t.cycles==!1&&(t.cycles=0),t.onInitDoNotUpdateChild="boolean"==typeof t.onInitDoNotUpdateChild&&t.onInitDoNotUpdateChild,t.onInitDoNotUpdateParent="boolean"==typeof t.onInitDoNotUpdateParent&&t.onInitDoNotUpdateParent,t.onInitSetUndefinedParentIfChildIsDefined="boolean"!=typeof t.onInitSetUndefinedParentIfChildIsDefined||t.onInitSetUndefinedParentIfChildIsDefined;var n=new m(this,"child"),r=new m(this,"parent"),e=!0;"boolean"==typeof t.childToParent?e=t.childToParent:null==t.child[u]?e=!1:void 0===t.setParent&&null==t.parent[d]&&(e=!1);var a=!0;if("boolean"==typeof t.parentToChild?a=t.parentToChild:null==t.parent[u]?a=!1:void 0===t.setChild&&null==t.child[d]&&(a=!1),!1===e&&!1===a)throw new Error("Neither the child nor parent will be updated; this is a no-way binding");this._childToParent=e,this._parentToChild=a,void 0===t.setChild&&(t.setChild=p),void 0===t.setParent&&(t.setParent=p),void 0!==t.priority&&(c.setPriority(t.child,t.priority),c.setPriority(t.parent,t.priority));var i=2*t.cycles,o=i+("childSticksToParent"===t.sticky?1:0),s=i+("parentSticksToChild"===t.sticky?1:0);this._bindingState={child:!1,parent:!1},this._updateChild=function(e){w.call(this,{bindingState:this._bindingState,newValue:e,debugObservableName:"child",debugPartnerName:"parent",observable:t.child,setValue:t.setChild,semaphore:n,allowedUpdates:o,sticky:"parentSticksToChild"===t.sticky,partner:t.parent,setPartner:t.setParent,partnerSemaphore:r})}.bind(this),this._updateParent=function(e){w.call(this,{bindingState:this._bindingState,newValue:e,debugObservableName:"parent",debugPartnerName:"child",observable:t.parent,setValue:t.setParent,semaphore:r,allowedUpdates:s,sticky:"childSticksToParent"===t.sticky,partner:t.child,setPartner:t.setChild,partnerSemaphore:n})}.bind(this)}function w(e){var t=e.bindingState;if(!1!==t.child||!1!==t.parent){var n=e.semaphore;if(n.value+e.partnerSemaphore.value<=e.allowedUpdates&&(i.batch.start(),n.increment(e),e.setValue(e.newValue,e.observable),i.mutateQueue.enqueue(n.decrement,n,[]),i.batch.stop(),e.sticky)){var r=c.getValue(e.observable);r!==c.getValue(e.partner)&&e.setPartner(r,e.partner)}}}o(m.prototype,{decrement:function(){this.value-=1},increment:function(e){this._incremented=!0,this.value+=1}}),Object.defineProperty(b.prototype,"parentValue",{get:function(){return c.getValue(this._options.parent)}}),o(b.prototype,{start:function(){var e,t,n=this._options;this.startParent(),this.startChild(),!0===this._childToParent&&!0===this._parentToChild?void 0===(t=c.getValue(n.parent))?void 0===(e=c.getValue(n.child))?!1===n.onInitDoNotUpdateChild&&this._updateChild(t):!1===n.onInitDoNotUpdateParent&&!0===n.onInitSetUndefinedParentIfChildIsDefined&&this._updateParent(e):!1===n.onInitDoNotUpdateChild&&this._updateChild(t):!0===this._childToParent?!1===n.onInitDoNotUpdateParent&&(e=c.getValue(n.child),this._updateParent(e)):!0===this._parentToChild&&!1===n.onInitDoNotUpdateChild&&(t=c.getValue(n.parent),this._updateChild(t))},startChild:function(){if(!1===this._bindingState.child&&!0===this._childToParent){var e=this._options;this._bindingState.child=!0,g(e.child,e.parent,this._updateParent,e.queue)}},startParent:function(){if(!1===this._bindingState.parent&&!0===this._parentToChild){var e=this._options;this._bindingState.parent=!0,g(e.parent,e.child,this._updateChild,e.queue)}},stop:function(){var e=this._bindingState,t=this._options;!0===e.parent&&!0===this._parentToChild&&(e.parent=!1,y(t.parent,t.child,this._updateChild,t.queue)),!0===e.child&&!0===this._childToParent&&(e.child=!1,y(t.child,t.parent,this._updateParent,t.queue))}}),n.exports=a.Bind=b}),define("can/es/can-bind",["exports","can-bind"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-event-queue",["exports","can-event-queue/map/map","can-event-queue/value/value"],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"mapEventBindings",{enumerable:!0,get:function(){return r(t).default}}),Object.defineProperty(e,"valueEventBindings",{enumerable:!0,get:function(){return r(n).default}})}),define("can/es/can-simple-observable",["exports","can-simple-observable"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-reflect-promise",["require","exports","module","can-reflect","can-symbol","can-observation-recorder","can-queues","can-key-tree","can-log/dev/dev"],function(e,t,n){"use strict";var a=e("can-reflect"),r=e("can-symbol"),i=e("can-observation-recorder"),o=e("can-queues"),s=e("can-key-tree"),c=(e("can-log/dev/dev"),r.for("can.getKeyValue")),u=r.for("can.meta"),l={isPending:!0,state:"pending",isResolved:!1,isRejected:!1,value:void 0,reason:void 0};function f(e,t,n){var r=e[u],a=r[t];r[t]=n,o.enqueueByQueue(r.handlers.getNode([t]),e,[n,a],function(){return{}},["Promise",e,"resolved with value",n,"and changed virtual property: "+t])}function d(t){var e=t[u];e||(Object.defineProperty(t,u,{enumerable:!1,configurable:!1,writable:!1,value:Object.create(l)}),(e=t[u]).handlers=new s([Object,Object,Array])),t.then(function(e){o.batch.start(),f(t,"isPending",!1),f(t,"isResolved",!0),f(t,"value",e),f(t,"state","resolved"),o.batch.stop()},function(e){o.batch.start(),f(t,"isPending",!1),f(t,"isRejected",!0),f(t,"reason",e),f(t,"state","rejected"),o.batch.stop()})}n.exports=function t(e){var n,r="getPrototypeOf"in Object?Object.getPrototypeOf(e):e.__proto__;e[c]&&e[u]||(null!==r&&r!==Object.prototype||"function"==typeof(r=e).promise&&(n=r.promise,r.promise=function(){var e=n.call(r);return t(e),e}),a.assignSymbols(r,{"can.getKeyValue":function(e){switch(this[u]||d(this),i.add(this,e),e){case"state":case"isPending":case"isResolved":case"isRejected":case"value":case"reason":return this[u][e];default:return this[e]}},"can.getValue":function(){return this[c]("value")},"can.isValueLike":!1,"can.onKeyValue":function(e,t,n){this[u]||d(this),this[u].handlers.add([e,n||"mutate",t])},"can.offKeyValue":function(e,t,n){this[u]||d(this),this[u].handlers.delete([e,n||"mutate",t])},"can.hasOwnKey":function(e){return this[u]||d(this),e in this[u]}}))}}),define("can-stache-key",["require","exports","module","can-observation-recorder","can-log/dev/dev","can-symbol","can-reflect","can-reflect-promise"],function(e,t,n){"use strict";var p,h=e("can-observation-recorder"),o=e("can-log/dev/dev"),r=e("can-symbol"),s=e("can-reflect"),a=e("can-reflect-promise"),c=r.for("can.getValue"),i=r.for("can.setValue"),u=r.for("can.isValueLike"),l=h.ignore(s.getKeyValue.bind(s)),f=Function.prototype.bind,v=function(e,t,n,r,a,i){for(var o=0,s=p.valueReaders.length;o<s;o++)p.valueReaders[o].test(e,t,n,r)&&(e=p.valueReaders[o].read(e,t,n,r,a,i));return e},y=function(e,t,n,r,a){e.foundObservable&&!t.foundObservable&&h.trapsCount()&&(h.addMany(n()),e.foundObservable(r,a),t.foundObservable=!0)},g=function(e,t,n){return!!(t&&t.length&&s.hasKey(e,t[n].key))};(p={read:function(e,t,n){var r,a={foundObservable:!1};(n=n||{}).foundObservable&&(r=h.trap());var i,o,s=v(e,0,t,n,a),c=t.length,u=0;for(y(n,a,r,e,0);u<c;){i=s;for(var l=0,f=p.propertyReaders.length;l<f;l++){var d=p.propertyReaders[l];if(d.test(s)){s=d.read(s,t[u],u,n,a);break}}if(y(n,a,r,i,u),s=v(s,u+=1,t,n,a,i),y(n,a,r,i,u-1),typeof s,u<t.length&&null==s)return o=g(i,t,u-1),n.earlyExit&&!o&&n.earlyExit(i,u-1,s),{value:void 0,parent:i,parentHasKey:o,foundLastParent:!1}}return o=g(i,t,t.length-1),void 0!==s||o||n.earlyExit&&n.earlyExit(i,u-1),{value:s,parent:i,parentHasKey:o,foundLastParent:!0}},get:function(e,t,n){return p.read(e,p.reads(t),n||{}).value},valueReadersMap:{},valueReaders:[{name:"function",test:function(e){return e&&s.isFunctionLike(e)&&!s.isConstructorLike(e)},read:function(e,t,n,r,a,i){return r.callMethodsOnObservables&&s.isObservableLike(i)&&s.isMapLike(i)?(o.warn("can-stache-key: read() called with `callMethodsOnObservables: true`."),e.apply(i,r.args||[])):!1!==r.proxyMethods?f.call(e,i):e}},{name:"isValueLike",test:function(e,t,n,r){return e&&e[c]&&!1!==e[u]&&(r.foundAt||!((a=n[t-1])&&a.at));var a},read:function(e,t,n,r){return!1===r.readCompute&&t===n.length?e:s.getValue(e)},write:function(e,t){e[i]?e[i](t):e.set?e.set(t):e(t)}}],propertyReadersMap:{},propertyReaders:[{name:"map",test:function(e){return(s.isPromise(e)||"object"==typeof e&&e&&"function"==typeof e.then)&&a(e),s.isObservableLike(e)&&s.isMapLike(e)},read:function(e,t){var n=s.getKeyValue(e,t.key);return void 0!==n?n:e[t.key]},write:s.setKeyValue},{name:"object",test:function(){return!0},read:function(e,t,n,r){if(null!=e)return"object"!=typeof e?e[t.key]:t.key in e?e[t.key]:void 0},write:function(e,t,n){var r=e[t];null!=n&&"object"==typeof n&&s.isMapLike(r)?(o.warn('can-stache-key: Merging data into "'+t+'" because its parent is non-observable'),s.update(r,n)):null!=r&&void 0!==r[i]?s.setValue(r,n):e[t]=n}}],reads:function(e){var t=""+e,n=[],r=0,a=!1;"@"===t.charAt(0)&&(r=1,a=!0);for(var i="",o=r;o<t.length;o++){var s=t.charAt(o);"."===s||"@"===s?i="\\"!==t.charAt(o-1)?(n.push({key:i,at:a}),a="@"===s,""):i.substr(0,i.length-1)+".":i+=s}return n.push({key:i,at:a}),n},write:function(e,t,n,r){var a,i="string"==typeof t?p.reads(t):t;if(r=r||{},1<i.length?(a=i.pop(),e=p.read(e,i,r).value,i.push(a)):a=i[0],e){var o=l(e,a.key);p.valueReadersMap.isValueLike.test(o,i.length-1,i,r)?p.valueReadersMap.isValueLike.write(o,n,r):(p.valueReadersMap.isValueLike.test(e,i.length-1,i,r)&&(e=e[c]()),p.propertyReadersMap.map.test(e)?p.propertyReadersMap.map.write(e,a.key,n,r):p.propertyReadersMap.object.test(e)&&(p.propertyReadersMap.object.write(e,a.key,n,r),r.observation&&r.observation.update()))}}}).propertyReaders.forEach(function(e){p.propertyReadersMap[e.name]=e}),p.valueReaders.forEach(function(e){p.valueReadersMap[e.name]=e}),p.set=p.write,n.exports=p}),define("can-dom-mutate/-util",["require","exports","module","can-globals/document/document"],function(u,e,t){!function(e,t,n,r){"use strict";var i=u("can-globals/document/document");function o(e){return!(!e||11!==e.nodeType)}function a(e){for(var t=[],n=e.firstChild;n;)t.push(n),n=n.nextSibling;return t}function s(){return NodeFilter.FILTER_ACCEPT}var c=s;c.acceptNode=s,r.exports={eliminate:function(e,t){var n=e.indexOf(t);0<=n&&e.splice(n,1)},isInDocument:function(e){var t=i();return t===e||function e(t,n){return t.contains?t.contains(n):t.nodeType===Node.DOCUMENT_NODE&&t.documentElement?e(t.documentElement,n):(n=n.parentNode)===t}(t,e)},getDocument:i,isDocumentElement:function(e){return i().documentElement===e},isFragment:o,getParents:function(e){return o(e)?a(e):[e]},getAllNodes:function(e){return void 0!==i().createTreeWalker?function(e){for(var t,n,r=o(e)?[]:[e],a=!(!(t=e)||1!==t.nodeType)&&i().createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,c,!1);n=a&&a.nextNode();)r.push(n);return r}(e):function(e){var t,n,r=0,a=o(e)?[]:[e];if(null==e.firstChild)return a;for(;!t&&(n=e.firstChild)?(r++,a.push(n)):(n=e.nextSibling)?(t=!1,a.push(n)):(n=e.parentNode,r--,t=!0),e=n,0<r;);return a}(e)},getChildren:a,subscription:function(r){return function(){var t=r.apply(this,arguments),n=!1;return function(){if(n){var e=r.name||r.displayName||"an anonymous function";throw new Error("Disposal function returned by "+e+" called more than once.")}t.apply(this,arguments),n=!0}}},addToSet:function(e,t){for(var n=0,r=e.length;n<r;n++)t.add(e[n])}}}(0,0,0,t)}),define("can-dom-mutate",["require","exports","module","can-globals","can-globals/global/global","can-globals/mutation-observer/mutation-observer","can-namespace","can-globals/document/document","can-reflect","can-dom-mutate/-util"],function(e,t,n){!function(e,t,n,r){"use strict";var s,l,f,c=t("can-globals"),u=t("can-globals/global/global"),d=t("can-globals/mutation-observer/mutation-observer"),a=t("can-namespace"),p=t("can-globals/document/document"),h=t("can-reflect"),v=t("can-dom-mutate/-util"),y=v.eliminate,g=v.subscription,m=v.isDocumentElement,b=v.getAllNodes,i=Array.prototype.slice,o=new WeakMap;function w(e,t){var n=o.get(e);if(n)return n[t]}function x(e,t,n){var r=o.get(e);r||(r={},o.set(e,r)),r[t]=n}function _(e,t){return delete o.get(e)[t]}function k(e){for(var t=[],n=0;n<e.length;n++)t.push({target:e[n]});return t}function O(n){return function(e,t){n(e),t&&t()}}function E(e,t){var n=w(p(),t);if(n)return n.listeners}function L(e,t){var n=w(p(),t);if(n)return n.get(e)}function q(e,t){for(var n=i.call(e,0),r=n.length,a=0;a<r;a++)n[a](t)}function S(o,s){return function(e){for(var t=0;t<e.length;t++){var n=e[t],r=n.target,a=L(r,o);if(a&&q(a,n),s){var i=E(0,s);i&&q(i,n)}}}}var M=0;function P(r,t,a,i){var o=w(r,t);o||x(r,t,o={observingCount:0});var n=function(){o.observer&&(o.observer.disconnect(),o.observer=null);var e=d();if(e){var t=u().Node;if(!!(t&&r instanceof t)){var n=new e(i);n.id=M++,n.observe(r,a),o.observer=n}}};return 0===o.observingCount&&(c.onKeyValue("MutationObserver",n),n()),o.observingCount++,function(){var e=w(r,t);e&&(e.observingCount--,e.observingCount<=0&&(e.observer&&e.observer.disconnect(),_(r,t),c.offKeyValue("MutationObserver",n)))}}function C(e){if("undefined"!=typeof Set){for(var t=e.length,n=new Set,r=new Set,a=0;a<t;a++){for(var i=e[a],o=i.addedNodes.length,s=0;s<o;s++)v.addToSet(b(i.addedNodes[s]),n);for(var c=i.removedNodes.length,u=0;u<c;u++)v.addToSet(b(i.removedNodes[u]),r)}f(k(h.toArray(r))),l(k(h.toArray(n)))}}function V(e){for(var t=e.length,n=0;n<t;n++){var r=e[n];if("attributes"===r.type){var a=r.target,i=r.attributeName,o=r.oldValue;s.dispatchNodeAttributeChange(a,i,o)}}}var j={subtree:!0,childList:!0},D={attributes:!0,attributeOldValue:!0};function I(r,a,i){return g(function(e,t){return 11===e.nodeType?Function.prototype:(n=i?P(e,a,D,V):P(p(),a,j,C),function(e,t,n){var r=p(),a=w(r,t);a||x(r,t,a=new Map);var i=a.get(e);i||(i=[],a.set(e,i)),i.push(n)}(e,r,t),function(){n(),function(e,t,n){var r=p(),a=w(r,t);if(a){var i=a.get(e);i&&(y(i,n),0===i.length&&(a.delete(e),0===a.size&&_(r,t)))}}(e,r,t)});var n})}function T(i,o){return g(function(e,n){if(!m(e))throw new Error("Global mutation listeners must pass a documentElement");var r=p(),t=w(r,i);t||x(r,i,t={listeners:[]});var a=t.listeners;return 0===a.length&&(t.removeListener=o(r,function(){})),a.push(n),function(){var e=w(r,i);if(e){var t=e.listeners;y(t,n),0===t.length&&(e.removeListener(),_(r,i))}}})}var A="domMutation",N=A+"InsertionData",K=A+"RemovalData",R=A+"AttributeChangeData",B=A+"DocumentInsertionData",H=A+"DocumentRemovalData",F=A+"DocumentAttributeChangeData",z=A+"TreeData";l=O(S(N,B)),f=O(S(K,H));var U=O(S(R,F)),G=I(N,z),W=I(K,z),Y=I(R,"domMutationAttributeData",!0),$=T(B,G),Q=T(H,W),J=T(F,Y);s={dispatchNodeInsertion:function(e,t){var n=new Set;v.addToSet(b(e),n);var r=k(h.toArray(n));l(r,t)},dispatchNodeRemoval:function(e,t){var n=new Set;v.addToSet(b(e),n);var r=k(h.toArray(n));f(r,t)},dispatchNodeAttributeChange:function(e,t,n,r){U([{target:e,attributeName:t,oldValue:n}],r)},onNodeInsertion:G,onNodeRemoval:W,onNodeAttributeChange:Y,onRemoval:Q,onInsertion:$,onAttributeChange:J},r.exports=a.domMutate=s}(0,e,0,n)}),define("can-control",["require","exports","module","can-construct","can-namespace","can-assign","can-stache-key","can-reflect","can-observation","can-event-queue/map/map","can-log/dev/dev","can-string","can-key/get/get","can-dom-mutate","can-symbol"],function(e,t,n){"use strict";var r,o,a=e("can-construct"),i=e("can-namespace"),s=e("can-assign"),c=e("can-stache-key"),u=e("can-reflect"),l=e("can-observation"),d=e("can-event-queue/map/map"),f=(e("can-log/dev/dev"),e("can-string")),p=e("can-key/get/get"),h=e("can-dom-mutate"),v=e("can-symbol").for("can.controls"),y=[].slice,g=/\{([^\}]+)\}/g,m=function(e,t,n,r){return r?(c=e,u=r.trim(),l=t,f=n,d.on.call(c,l,u,f),function(){d.off.call(c,l,u,f)}):(a=e,i=t,o=n,d.on.call(a,i,o,s),function(){d.off.call(a,i,o,s)});var a,i,o,s,c,u,l,f},b=a.extend("Control",{setup:function(){if(a.setup.apply(this,arguments),b){var e,t=this;for(e in t.actions={},t.prototype)t._isAction(e)&&(t.actions[e]=t._action(e))}},_shifter:function(t,n){var r="string"==typeof n?t[n]:n;"function"!=typeof r&&(r=t[r]);var a=this;return function(){var e=a.wrapElement(this);return t.called=n,r.apply(t,[e].concat(y.call(arguments,0)))}},_isAction:function(e){var t=this.prototype[e],n=typeof t;return"constructor"!==e&&("function"===n||"string"===n&&"function"==typeof this.prototype[t])&&!!(b.isSpecial(e)||r[e]||/[^\w]/.test(e))},_action:function(r,i,t){var e;if(g.lastIndex=0,i||!g.test(r)){if(e=new l(function(){var a,e=r.replace(g,function(e,t){var n,r;return this._isDelegate(i,t)?(a=this._getDelegate(i,t),""):(t=this._removeDelegateFromKey(t),r=this._lookup(i)[0],void 0===(n=c.read(r,c.reads(t),{readCompute:!1}).value)&&"undefined"!=typeof window&&(n=p(window,t)),r&&(u.isObservableLike(r)&&u.isMapLike(r)||n)?"string"==typeof n?n:(a=n,""):(!0,null))}.bind(this)),t=(e=e.trim()).split(/\s+/g),n=t.pop();return{processor:this.processors[n]||o,parts:[e,t.join(" "),n],delegate:a||void 0}},this),t){var n=function(e){t._bindings.control[r](t.element),t._bindings.control[r]=e.processor(e.delegate||t.element,e.parts[2],e.parts[1],r,t)};u.onValue(e,n,"mutate"),t._bindings.readyComputes[r]={compute:e,handler:n}}return e.get()}},_lookup:function(e){return[e,window]},_removeDelegateFromKey:function(e){return e},_isDelegate:function(e,t){return"element"===t},_getDelegate:function(e,t){},processors:{},defaults:{},convertElement:function(e){return e="string"==typeof e?document.querySelector(e):e,this.wrapElement(e)},wrapElement:function(e){return e},unwrapElement:function(e){return e},isSpecial:function(e){return"inserted"===e||"removed"===e}},{setup:function(e,t){var n,r=this.constructor,a=r.pluginName||r.shortName;if(!e)throw new Error("Creating an instance of a named control without passing an element");if(this.element=r.convertElement(e),a&&"Control"!==a&&this.element.classList&&this.element.classList.add(a),(n=this.element[v])||(n=[],this.element[v]=n),n.push(this),u.isObservableLike(t)&&u.isMapLike(t)){for(var i in r.defaults)t.hasOwnProperty(i)||c.set(t,i,r.defaults[i]);this.options=t}else this.options=s(s({},r.defaults),t);return this.on(),[this.element,this.options]},on:function(e,t,n,r){if(e)return"string"==typeof e&&(r=n,n=t,t=e,e=this.element),void 0===r&&(r=n,n=t,t=null),"string"==typeof r&&(r=b._shifter(this,r)),this._bindings.user.push(m(e,n,r,t)),this._bindings.user.length;this.off();var a,i,o=this.constructor,s=this._bindings,c=o.actions,u=this.constructor.unwrapElement(this.element),l=b._shifter(this,"destroy");for(a in c)c.hasOwnProperty(a)&&(i=c[a]||o._action(a,this.options,this))&&(s.control[a]=i.processor(i.delegate||u,i.parts[2],i.parts[1],a,this));var f=h.onNodeRemoval(u,function(){var e=u.ownerDocument,t=e.contains?e:e.documentElement;t&&!1!==t.contains(u)||l()});return s.user.push(function(){f&&(f(),f=void 0)}),s.user.length},off:function(){var t=this.constructor.unwrapElement(this.element),e=this._bindings;e&&((e.user||[]).forEach(function(e){e(t)}),u.eachKey(e.control||{},function(e){e(t)}),u.eachKey(e.readyComputes||{},function(e){u.offValue(e.compute,e.handler,"mutate")})),this._bindings={user:[],control:{},readyComputes:{}}},destroy:function(){if(null!==this.element){var e,t=this.constructor,n=t.pluginName||t.shortName&&f.underscore(t.shortName);this.off(),n&&"can_control"!==n&&this.element.classList&&this.element.classList.remove(n),(e=this.element[v])&&e.splice(e.indexOf(this),1),this.element=null}}});r=b.processors,o=function(e,t,n,r,a){return m(e,t,b._shifter(a,r),n)},["beforeremove","change","click","contextmenu","dblclick","keydown","keyup","keypress","mousedown","mousemove","mouseout","mouseover","mouseup","reset","resize","scroll","select","submit","focusin","focusout","mouseenter","mouseleave","touchstart","touchmove","touchcancel","touchend","touchleave","inserted","removed","dragstart","dragenter","dragover","dragleave","drag","drop","dragend"].forEach(function(e){r[e]=o}),n.exports=i.Control=b}),define("can-component/control/control",["require","exports","module","can-control","can-reflect"],function(e,t,n){"use strict";var a=e("can-control"),r=e("can-reflect"),i=/\{([^\}]+)\}/g,o=a.extend({_lookup:function(e){return[e.scope,e,window]},_removeDelegateFromKey:function(e){return e.replace(/^(scope|^viewModel)\./,"")},_isDelegate:function(e,t){return"scope"===t||"viewModel"===t},_getDelegate:function(e,t){return e[t]},_action:function(e,t,n){var r;return i.lastIndex=0,r=i.test(e),!n&&r?void 0:a._action.apply(this,arguments)}},{setup:function(e,t){return this.scope=t.scope,this.viewModel=t.viewModel,a.prototype.setup.call(this,e,t)},off:function(){this._bindings&&r.eachKey(this._bindings.readyComputes||{},function(e){r.offValue(e.compute,e.handler)}),a.prototype.off.apply(this,arguments),this._bindings.readyComputes={}},destroy:function(){a.prototype.destroy.apply(this,arguments),"function"==typeof this.options.destroy&&this.options.destroy.apply(this,arguments)}});n.exports=o}),define("can-attribute-encoder",["require","exports","module","can-namespace","can-log/dev/dev"],function(e,t,n){"use strict";var r=e("can-namespace");e("can-log/dev/dev");var a,i=(a={},function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)}("allowReorder,attributeName,attributeType,autoReverse,baseFrequency,baseProfile,calcMode,clipPathUnits,contentScriptType,contentStyleType,diffuseConstant,edgeMode,externalResourcesRequired,filterRes,filterUnits,glyphRef,gradientTransform,gradientUnits,kernelMatrix,kernelUnitLength,keyPoints,keySplines,keyTimes,lengthAdjust,limitingConeAngle,markerHeight,markerUnits,markerWidth,maskContentUnits,maskUnits,patternContentUnits,patternTransform,patternUnits,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,repeatCount,repeatDur,requiredExtensions,requiredFeatures,specularConstant,specularExponent,spreadMethod,startOffset,stdDeviation,stitchTiles,surfaceScale,systemLanguage,tableValues,textLength,viewBox,viewTarget,xChannelSelector,yChannelSelector".split(","),function(e){a[e]=!0}),a);function o(e,t,n){return t+"-"+n.toLowerCase()}function s(e,t){return 0===e.indexOf(t)}function c(e,t){return e.length-e.lastIndexOf(t)===t.length}var u={leftParens:/\(/g,rightParens:/\)/g,leftBrace:/\{/g,rightBrace:/\}/g,camelCase:/([a-z]|[0-9]|^)([A-Z])/g,forwardSlash:/\//g,space:/\s/g,uppercase:/[A-Z]/g,uppercaseDelimiterThenChar:/:u:([a-z])/g,caret:/\^/g,dollar:/\$/g,at:/@/g},l=":u:",f=":s:",d=":f:",p=":lp:",h=":rp:",v=":lb:",y=":rb:",g=":c:",m=":d:",b=":at:",w={encode:function(e){var t=e;return!i[t]&&t.match(u.camelCase)&&(s(t,"on:")||c(t,":to")||c(t,":from")||c(t,":bind")||c(t,":raw")?t=t.replace(u.uppercase,function(e){return l+e.toLowerCase()}):(s(t,"(")||s(t,"{"))&&(t=t.replace(u.camelCase,o))),t=t.replace(u.space,f).replace(u.forwardSlash,d).replace(u.leftParens,p).replace(u.rightParens,h).replace(u.leftBrace,v).replace(u.rightBrace,y).replace(u.caret,g).replace(u.dollar,m).replace(u.at,b)},decode:function(e){var t=e;return!i[t]&&u.uppercaseDelimiterThenChar.test(t)&&(s(t,"on:")||c(t,":to")||c(t,":from")||c(t,":bind")||c(t,":raw"))&&(t=t.replace(u.uppercaseDelimiterThenChar,function(e,t){return t.toUpperCase()})),t=t.replace(p,"(").replace(h,")").replace(v,"{").replace(y,"}").replace(d,"/").replace(f," ").replace(g,"^").replace(m,"$").replace(b,"@")}};if(r.encoder)throw new Error("You can't have two versions of can-attribute-encoder, check your dependencies");n.exports=r.encoder=w}),define("can-view-parser",["require","exports","module","can-namespace","can-log/dev/dev","can-attribute-encoder"],function(e,t,n){"use strict";var r=e("can-namespace"),s=(e("can-log/dev/dev"),e("can-attribute-encoder"));function m(e,t){for(var n=0;n<e.length;n++)t(e[n],n)}function a(e){var t={};return m(e.split(","),function(e){t[e]=!0}),t}var i="A-Za-z0-9",o="-:_"+i,b="{{",w=new RegExp("^<\\/(["+o+"]+)[^>]*>"),x=new RegExp("\\{\\{(![\\s\\S]*?!|[\\s\\S]*?)\\}\\}\\}?","g"),f=/\s/,d=new RegExp("["+i+"]"),p=new RegExp("["+o+"]+s*=s*(\"[^\"]*\"|'[^']*')"),_=a("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed"),k=a("altGlyph,altGlyphDef,altGlyphItem,animateColor,animateMotion,animateTransform,clipPath,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,foreignObject,glyphRef,linearGradient,radialGradient,textPath"),O=a("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"),E=a("script"),L="start,end,close,attrStart,attrEnd,attrValue,chars,comment,special,done".split(","),l={"{":"}","(":")"},q=function(){},S=function(e,a,t){if("object"==typeof e)return function(e,t){for(var n=0,r=e.length;n<r;n++){var a=e[n];t[a.tokenType].apply(t,a.args)}return e}(e,a);var r=[];function n(e,t,n,r){t=k[t]?t:t.toLowerCase(),O[t]&&p.last()===t&&i("",t),r=_[t]||!!r,a.start(t,r,f),r||p.push(t),S.parseAttrs(n,a,f),a.end(t,r,f),"html"===t&&(u=!0)}function i(e,t){var n;if(t)for(t=k[t]?t:t.toLowerCase(),n=p.length-1;0<=n&&p[n]!==t;n--);else n=0;if(0<=n){for(var r=p.length-1;n<=r;r--)a.close&&a.close(p[r],f);p.length=n,"body"===t&&(u=!0)}}function o(e,t){a.special&&a.special(t,f)}a=a||{},t&&m(L,function(t){var n=a[t]||q;a[t]=function(){if(!1!==n.apply(this,arguments)){var e=arguments.length;void 0===arguments[e-1]&&(e=arguments.length-1),r.push({tokenType:t,args:[].slice.call(arguments,0,e)})}}});var s,c,u,l,f,d=function(){v&&!u&&a.chars&&a.chars(v,f),u=!1,v=""},p=[],h=e,v="";for(p.last=function(){return this[this.length-1]};e;){if(c=!0,p.last()&&E[p.last()])e=e.replace(new RegExp("([\\s\\S]*?)</"+p.last()+"[^>]*>"),function(e,t){return t=t.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g,"$1$2"),a.chars&&a.chars(t,f),""}),i(0,p.last());else{if(0===e.indexOf("\x3c!--"))0<=(s=e.indexOf("--\x3e"))&&(d(),a.comment&&a.comment(e.substring(4,s),f),e=e.substring(s+3),c=!1);else if(0===e.indexOf("</"))(l=e.match(w))&&(d(),l[0].replace(w,i),e=e.substring(l[0].length),c=!1);else if(0===e.indexOf("<")){var y=S.searchStartTag(e);y&&(d(),n.apply(null,y.match),e=y.html,c=!1)}else 0===e.indexOf(b)&&(l=e.match(x))&&(d(),l[0].replace(x,o),e=e.substring(l[0].length));if(c){0===(s=M(e,b))&&e===h&&(v+=e.charAt(0),e=e.substr(1),s=M(e,b));var g=s<0?e:e.substring(0,s);e=s<0?"":e.substring(s),g&&(v+=g)}}if(e===h)throw new Error("Parse Error: "+e);h=e}return d(),i(),a.done(f),r},h=function(e,t,n,r,a){var i=r.substring("number"==typeof e.nameStart?e.nameStart:t,t),o=s.encode(i);e.attrStart=o,n.attrStart(e.attrStart,a),e.inName=!1},v=function(e,t,n,r,a){if(void 0!==e.valueStart&&e.valueStart<t){var i=r.substring(e.valueStart,t);n.attrValue(i,a)}n.attrEnd(e.attrStart,a),e.attrStart=void 0,e.valueStart=void 0,e.inValue=!1,e.inName=!1,e.lookingForEq=!1,e.inQuote=!1,e.lookingForName=!0},M=function(e,t){for(var n=t.length,r=0,a=e.length;r<a;r++)if("<"===e[r]||e.substr(r,n)===t)return r;return-1};S.parseAttrs=function(e,t,n){if(e){for(var r,a=0,i={inName:!1,nameStart:void 0,inValue:!1,valueStart:void 0,inQuote:!1,attrStart:void 0,lookingForName:!0,lookingForValue:!1,lookingForEq:!1};a<e.length;){r=a;var o=e.charAt(a);if(a++,b===e.substr(r,b.length)){i.inValue&&r>i.valueStart?t.attrValue(e.substring(i.valueStart,r),n):i.inName&&i.nameStart<r?(h(i,r,t,e,n),v(i,r,t,e,n)):i.lookingForValue?i.inValue=!0:i.lookingForEq&&i.attrStart&&v(i,r,t,e,n),x.lastIndex=r;var s=x.exec(e);s&&(t.special(s[1],n),a=r+s[0].length,i.inValue&&(i.valueStart=r+s[0].length))}else if(i.inValue)i.inQuote?o===i.inQuote&&v(i,r,t,e,n):f.test(o)&&v(i,r,t,e,n);else if("="===o&&(i.lookingForEq||i.lookingForName||i.inName))i.attrStart||h(i,r,t,e,n),i.lookingForValue=!0,i.lookingForEq=!1,i.lookingForName=!1;else if(i.inName){var c,u=e[i.nameStart];l[u]===o?(c=l["{"===u?"(":"{"],e[r+1]===c?(h(i,r+2,t,e,n),a++):h(i,r+1,t,e,n),i.lookingForEq=!0):f.test(o)&&"{"!==u&&"("!==u&&(h(i,r,t,e,n),i.lookingForEq=!0)}else i.lookingForName?f.test(o)||(i.attrStart&&v(i,r,t,e,n),i.nameStart=r,i.inName=!0):i.lookingForValue&&(f.test(o)?a===e.length&&v(i,r,t,e,n):(i.lookingForValue=!1,i.inValue=!0,i.valueStart="'"===o||'"'===o?(i.inQuote=o,r+1):r))}i.inName?(h(i,r+1,t,e,n),v(i,r+1,t,e,n)):(i.lookingForEq||i.lookingForValue||i.inValue)&&v(i,r+1,t,e,n),x.lastIndex=0}},S.searchStartTag=function(e){for(var t=e.indexOf(">"),n=p.exec(e.substring(1)),r=1;n&&t>=r+n.index;){for(r+=n.index+n[0].length;t<r;)t+=e.substring(t+1).indexOf(">")+1;n=p.exec(e.substring(r))}if(-1===t||!d.test(e[1]))return null;var a,i,o="",s="",c=e.substring(0,t+1),u="/"===c[c.length-2],l=c.search(f);return i=u?(s="/",c.substring(1,c.length-2).trim()):c.substring(1,c.length-1).trim(),-1===l?a=i:(l--,a=i.substring(0,l),o=i.substring(l)),{match:[c,a,o,s],html:e.substring(c.length)}},n.exports=r.HTMLParser=S}),define("can-dom-mutate/node/node",["require","exports","module","can-globals","can-namespace","can-dom-mutate","can-dom-mutate/-util"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-globals"),i=t("can-namespace"),o=t("can-dom-mutate"),s=t("can-dom-mutate/-util"),c=s.isInDocument,u=s.getParents,l={dispatchNodeInsertion:function(e,t){c(t)&&o.dispatchNodeInsertion(t)},dispatchNodeRemoval:function(e,t){c(e)&&!c(t)&&o.dispatchNodeRemoval(t)}},f={replaceChild:function(e,t){var n=u(e),r=this.replaceChild(e,t);l.dispatchNodeRemoval(this,t);for(var a=0;a<n.length;a++)l.dispatchNodeInsertion(this,n[a]);return r},setAttribute:function(e,t){var n=this.getAttribute(e),r=this.setAttribute(e,t);return n!==this.getAttribute(e)&&o.dispatchNodeAttributeChange(this,e,n),r},removeAttribute:function(e){var t=this.getAttribute(e),n=this.removeAttribute(e);return t&&o.dispatchNodeAttributeChange(this,e,t),n}};[["appendChild","Insertion"],["insertBefore","Insertion"],["removeChild","Removal"]].forEach(function(e){var a=e[0],i="dispatchNode"+e[1];f[a]=function(e){for(var t=u(e),n=this[a].apply(this,arguments),r=0;r<t.length;r++)l[i](this,t[r]);return n}});var d={};["appendChild","insertBefore","removeChild","replaceChild","setAttribute","removeAttribute"].forEach(function(e){d[e]=function(){return this[e].apply(this,arguments)}});var p={};function h(e){var t=e?d:f;for(var n in t)p[n]=t[n]}var v="MutationObserver";h(a.getKeyValue(v)),a.onKeyValue(v,h),r.exports=i.domMutateNode=o.node=p}(0,e,0,n)}),define("can-dom-mutate/node",["require","exports","module","can-namespace","can-dom-mutate/node/node"],function(e,t,n){"use strict";var r=e("can-namespace"),a=e("can-dom-mutate/node/node");n.exports=r.node=a}),define("can-view-nodelist",["require","exports","module","can-namespace","can-dom-mutate/node"],function(e,t,n){"use strict";var r=e("can-namespace"),a=e("can-dom-mutate/node"),o=new Map,s=[].splice,c=[].push,u=function(e){for(var t=0,n=0,r=e.length;n<r;n++){var a=e[n];a.nodeType?t++:t+=u(a)}return t},l={update:function(e,t,n){n||(n=l.unregisterChildren(e));for(var r=[],a=0,i=r.length=t.length;a<i;a++)r[a]=t[a];t=r;var o=e.length;return s.apply(e,[0,o].concat(t)),e.replacements?(l.nestReplacements(e),e.deepChildren=e.newDeepChildren,e.newDeepChildren=[]):l.nestList(e),n},nestReplacements:function(e){for(var t,n=0,r=function(e){for(var t=new Map,n=0,r=e.length;n<r;n++){var a=l.first(e[n]);t.set(a,e[n])}return t}(e.replacements),a=e.replacements.length;n<e.length&&a;){var i=e[n],o=r.get(i);o&&(r.delete(i),e.splice(n,u(o),o),a--),n++}a&&(t=e,r.forEach(function(e){t.newDeepChildren.push(e)})),e.replacements=[]},nestList:function(e){for(var t=0;t<e.length;){var n=e[t],r=o.get(n);r?r!==e&&e.splice(t,u(r),r):o.set(n,e),t++}},last:function(e){var t=e[e.length-1];return t.nodeType?t:l.last(t)},first:function(e){var t=e[0];return t.nodeType?t:l.first(t)},flatten:function(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];r.nodeType?t.push(r):t.push.apply(t,l.flatten(r))}return t},register:function(e,t,n,r){return e.unregistered=t,e.parentList=n,e.nesting=n&&void 0!==n.nesting?n.nesting+1:0,n?(e.deepChildren=[],e.newDeepChildren=[],e.replacements=[],!0!==n&&(r?n.replacements.push(e):n.newDeepChildren.push(e))):l.nestList(e),e},unregisterChildren:function(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];r.nodeType?(e.replacements||o.delete(r),t.push(r)):c.apply(t,l.unregister(r,!0))}var a=e.deepChildren;if(a)for(var i=0;i<a.length;i++)l.unregister(a[i],!0);return t},unregister:function(e,t){var n=l.unregisterChildren(e,!0);if(e.isUnregistered=!0,e.unregistered){var r=e.unregistered;if(e.replacements=e.unregistered=null,!t){var a=e.parentList&&e.parentList.deepChildren;if(a){var i=a.indexOf(e);-1!==i&&a.splice(i,1)}}r()}return n},after:function(e,t){var n=e[e.length-1];n.nextSibling?a.insertBefore.call(n.parentNode,t,n.nextSibling):a.appendChild.call(n.parentNode,t)},replace:function(e,t){var n,r=e[0].parentNode;"SELECT"===r.nodeName.toUpperCase()&&0<=r.selectedIndex&&(n=r.value),1===e.length?a.replaceChild.call(r,t,e[0]):(l.after(e,t),l.remove(e)),void 0!==n&&(r.value=n)},remove:function(e){for(var t=e[0]&&e[0].parentNode,n=0;n<e.length;n++)a.removeChild.call(t,e[n])},nodeMap:o};n.exports=r.nodeLists=l}),define("can-child-nodes",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace");n.exports=r.childNodes=function(e){var t=e.childNodes;if("length"in t)return t;for(var n=e.firstChild,r=[];n;)r.push(n),n=n.nextSibling;return r}}),define("can-fragment",["require","exports","module","can-globals/document/document","can-namespace","can-reflect","can-child-nodes","can-symbol"],function(e,t,n){!function(e,t,n,r){"use strict";var o=t("can-globals/document/document"),a=t("can-namespace"),i=t("can-reflect"),s=t("can-child-nodes"),c=t("can-symbol"),u=/^\s*<(\w+)[^>]*>/,l={}.toString,f=c.for("can.toDOM");function d(e,t){if(e&&11===e.nodeType)return e;t?t.length&&(t=t[0]):t=o();for(var n=function(e,t,n){void 0===t&&(t=u.test(e)&&RegExp.$1),e&&"[object Function]"===l.call(e.replace)&&(e=e.replace(/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,"<$1></$2>"));var r=n.createElement("div"),a=n.createElement("div");return"tbody"===t||"tfoot"===t||"thead"===t||"colgroup"===t?(a.innerHTML="<table>"+e+"</table>",r=3===a.firstChild.nodeType?a.lastChild:a.firstChild):"col"===t?(a.innerHTML="<table><colgroup>"+e+"</colgroup></table>",r=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild):"tr"===t?(a.innerHTML="<table><tbody>"+e+"</tbody></table>",r=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild):"td"===t||"th"===t?(a.innerHTML="<table><tbody><tr>"+e+"</tr></tbody></table>",r=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild.firstChild):"option"===t?(a.innerHTML="<select>"+e+"</select>",r=3===a.firstChild.nodeType?a.lastChild:a.firstChild):r.innerHTML=""+e,[].slice.call(s(r))}(e,void 0,t),r=(t||document).createDocumentFragment(),a=0,i=n.length;a<i;a++)r.appendChild(n[a]);return r}var p=function(e,t){var n,r=t||o();if(e&&"string"!=typeof e){if("function"==typeof e[f])return p(e[f]());if(11===e.nodeType)return e;if("number"==typeof e.nodeType)return(n=r.createDocumentFragment()).appendChild(e),n;i.isListLike(e)?(n=r.createDocumentFragment(),i.eachIndex(e,function(e){n.appendChild(p(e))})):n=d(""+e,r)}else n=d(null==e?"":""+e,r);return s(n).length||n.appendChild(r.createTextNode("")),n};r.exports=a.fragment=a.frag=p}(0,e,0,n)}),define("can-view-callbacks",["require","exports","module","can-observation-recorder","can-log/dev/dev","can-globals/global/global","can-globals/document/document","can-dom-mutate/node","can-namespace","can-view-nodelist","can-fragment","can-globals","can-symbol","can-reflect"],function(e,t,n){!function(e,t,n,r){"use strict";var u,l=t("can-observation-recorder"),f=(t("can-log/dev/dev"),t("can-globals/global/global")),d=t("can-globals/document/document"),p=t("can-dom-mutate/node"),a=t("can-namespace"),h=t("can-view-nodelist"),v=t("can-fragment"),y=t("can-globals"),i=t("can-symbol"),o=t("can-reflect"),s=i.for("can.callbackMap"),g={},m=new WeakMap,b=function(e){var t=e.tagName&&e.tagName.toLowerCase();g[t]&&q.tagHandler(e,t,{})},w=function(e){var t;if(b(e),e.getElementsByTagName){t=e.getElementsByTagName("*");for(var n,r=0;void 0!==(n=t[r]);r++)w(n)}},x=!1,c=function(e,t){if(!t){var n=_[e];if(!n)for(var r=0,a=k.length;r<a;r++){var i=k[r];if(i.match.test(e))return i.handler}return n}"string"==typeof e?_[e]=t:k.push({match:e,handler:t})},_={},k=[],O=new WeakMap,E=/[-\:]/,L=function(){},q={_tags:g,_attributes:_,_regExpAttributes:k,defaultCallback:L,tag:function(e,t){var n;if(!t)return null===t?delete g[e.toLowerCase()]:n=g[e.toLowerCase()],!n&&E.test(e)&&(n=L),n;var r,a,i=f(),o=E.test(e);g[e.toLowerCase()];if(i.html5&&(i.html5.elements+=" "+e,i.html5.shivDocument()),g[e.toLowerCase()]=t,null!=(a=y.getKeyValue("document"))&&null!=a.documentElement&&"false"!==a.documentElement.getAttribute("data-can-automount")){var s=y.getKeyValue("customElements");if(s){if(r=s.get(e.toLowerCase()),o&&!r){var c=function(){return Reflect.construct(HTMLElement,[],c)};c.prototype=Object.create(HTMLElement.prototype),c.prototype.connectedCallback=function(){q.tagHandler(this,e.toLowerCase(),{})},s.define(e,c)}}else!function(){if(!x){var e=y.getKeyValue("MutationObserver");e&&((u=new e(function(e){for(var t,n,r=0;void 0!==(n=e[r]);r++)if("childList"===n.type){t=n.addedNodes;for(var a,i=0;void 0!==(a=t[i]);i++)w(a)}})).observe(d().documentElement,{childList:!0,subtree:!0}),x=!0)}}(),function(e){for(var t,n=d().getElementsByTagName(e),r=0;void 0!==(t=n[r]);r++)b(t)}(e)}else x&&u.disconnect()},attr:c,attrs:function(e){var t=o.getKeyValue(e,s)||e;O.has(t)||(O.set(t,!0),o.eachKey(t,function(e,t){c(t,e)}))},tagHandler:function(e,t,n){if(!m.has(e)){var r,a=n.scope,i=a&&a.templateContext.tags.get(t)||g[t];if(i?(r=l.ignore(i)(e,n),m.set(e,!0)):r=a,r&&n.subtemplate){a!==r&&(a=a.add(r));var o=h.register([],void 0,n.parentNodeList||!0,!1);o.expression="<"+e.tagName+">";var s=n.subtemplate(a,n.options,o),c="string"==typeof s?v(s):s;p.appendChild.call(e,c)}}}};if(a.view=a.view||{},a.view.callbacks)throw new Error("You can't have two versions of can-view-callbacks, check your dependencies");r.exports=a.view.callbacks=q}(0,e,0,n)}),define("can-view-target",["require","exports","module","can-globals/document/document","can-dom-mutate/node","can-namespace","can-globals/mutation-observer/mutation-observer"],function(e,t,n){!function(e,t,n,r){"use strict";var a,i,s=t("can-globals/document/document"),h=t("can-dom-mutate/node"),o=t("can-namespace"),c=t("can-globals/mutation-observer/mutation-observer"),v=function(e,t,n,r){for(var a=r.createDocumentFragment(),i=0,o=e.length;i<o;i++){var s=e[i];a.appendChild(f(s,t,n.concat(i),r))}return a},y="undefined"!=typeof document&&(a=document.createDocumentFragment(),(i=document.createElement("div")).appendChild(document.createTextNode("")),i.appendChild(document.createTextNode("")),a.appendChild(i),2===a.cloneNode(!0).firstChild.childNodes.length),u="undefined"!=typeof document&&function(){var e=document.createElement("a");e.innerHTML="<xyz></xyz>";var t,n,r=e.cloneNode(!0),a="<xyz></xyz>"===r.innerHTML;return a?((e=document.createDocumentFragment()).appendChild(document.createTextNode("foo-bar")),(t=c())?((n=new t(function(){})).observe(document.documentElement,{childList:!0,subtree:!0}),r=e.cloneNode(!0),n.disconnect()):r=e.cloneNode(!0),1===r.childNodes.length):a}(),g="undefined"!=typeof document&&!!document.createElementNS,l=u?function(e){return e.cloneNode(!0)}:function(e){var t,n=e.ownerDocument;if(1===e.nodeType?t="http://www.w3.org/1999/xhtml"!==e.namespaceURI&&g&&n.createElementNS?n.createElementNS(e.namespaceURI,e.nodeName):n.createElement(e.nodeName):3===e.nodeType?t=n.createTextNode(e.nodeValue):8===e.nodeType?t=n.createComment(e.nodeValue):11===e.nodeType&&(t=n.createDocumentFragment()),e.attributes)for(var r=e.attributes,a=0;a<r.length;a++){var i=r[a];i&&i.specified&&(i.namespaceURI?t.setAttributeNS(i.namespaceURI,i.nodeName||i.name,i.nodeValue||i.value):t.setAttribute(i.nodeName||i.name,i.nodeValue||i.value))}if(e&&e.firstChild)for(var o=e.firstChild;o;)t.appendChild(l(o)),o=o.nextSibling;return t};function f(t,e,n,r){var a,i,o,s,c,u=n,l=typeof t,f=function(){return a||(a={path:n,callbacks:[]},e.push(a),u=[]),a};if("object"===l){if(t.tag){if(i=g&&t.namespace?r.createElementNS(t.namespace,t.tag):r.createElement(t.tag),t.attrs)for(var d in t.attrs){var p=t.attrs[d];"function"==typeof p?f().callbacks.push({callback:p}):null!==p&&"object"==typeof p&&p.namespaceURI?i.setAttributeNS(p.namespaceURI,d,p.value):h.setAttribute.call(i,d,p)}if(t.attributes)for(s=0,c=t.attributes.length;s<c;s++)f().callbacks.push({callback:t.attributes[s]});t.children&&t.children.length&&(o=a?a.paths=[]:e,i.appendChild(v(t.children,o,u,r)))}else if(t.comment&&(i=r.createComment(t.comment),t.callbacks))for(s=0,c=t.attributes.length;s<c;s++)f().callbacks.push({callback:t.callbacks[s]})}else"string"===l?i=r.createTextNode(t):"function"===l&&(y?(i=r.createTextNode(""),f().callbacks.push({callback:t})):(i=r.createComment("~"),f().callbacks.push({callback:function(){var e=r.createTextNode("");return h.replaceChild.call(this.parentNode,e,this),t.apply(e,arguments)}})));return i}function d(e,t,n){for(var r=t.path,a=t.callbacks,i=t.paths,o=e,s=r?r.length:0,c=i?i.length:0,u=0;u<s;u++)o=o.childNodes.item(r[u]);for(u=0;u<c;u++)d(o,i[u],n);n.push({element:o,callbacks:a})}function p(e,t){var o=[],n=v(e,o,[],t||s());return{paths:o,clone:n,hydrate:function(){for(var e=l(this.clone),t=[],n=0,r=t.length=arguments.length;n<r;n++)t[n]=arguments[n];for(var a=[],i=0;i<o.length;i++)d(e,o[i],a);return function(e,t){for(var n,r,a,i=e.length,o=0;o<i;o++){n=(a=e[o]).callbacks.length,r=a.element;for(var s=0;s<n;s++)a.callbacks[s].callback.apply(r,t)}}(a,t),e}}}p.keepsTextNodes=y,p.cloneNode=l,o.view=o.view||{},r.exports=o.view.target=p}(0,e,0,n)}),define("can-view-scope/template-context",["require","exports","module","can-simple-map"],function(e,t,n){"use strict";var r=e("can-simple-map");n.exports=function(e){e=e||{},this.vars=new r(e.vars||{}),this.helpers=new r(e.helpers||{}),this.partials=new r(e.partials||{}),this.tags=new r(e.tags||{})}}),define("can-view-scope/make-compute-like",["require","exports","module","can-single-reference","can-reflect"],function(e,t,n){"use strict";var i=e("can-single-reference"),o=e("can-reflect");n.exports=function(r){var a=function(e){return arguments.length?o.setValue(this,e):o.getValue(this)}.bind(r);return a.on=a.bind=a.addEventListener=function(e,n){var t=function(e,t){n.call(a,{type:"change"},e,t)};i.set(n,this,t),r.on(t)},a.off=a.unbind=a.removeEventListener=function(e,t){r.off(i.getAndDelete(t,this))},o.assignSymbols(a,{"can.getValue":function(){return o.getValue(r)},"can.setValue":function(e){return o.setValue(r,e)},"can.onValue":function(e,t){return o.onValue(r,e,t)},"can.offValue":function(e,t){return o.offValue(r,e,t)},"can.valueHasDependencies":function(){return o.valueHasDependencies(r)},"can.getPriority":function(){return o.getPriority(r)},"can.setPriority":function(e){o.setPriority(r,e)},"can.isValueLike":!0,"can.isFunctionLike":!1}),a.isComputed=!0,a}}),define("can-stache-helpers",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace");if(r.stacheHelpers)throw new Error("You can't have two versions of can-stache-helpers, check your dependencies");n.exports=r.stacheHelpers={}}),define("can-view-scope/scope-key-data",["require","exports","module","can-observation","can-stache-key","can-assign","can-reflect","can-symbol","can-observation-recorder","can-view-scope/make-compute-like","can-reflect-dependencies","can-event-queue/value/value","can-stache-helpers","can-simple-observable","can-log/dev/dev"],function(e,t,n){"use strict";var i=e("can-observation"),r=e("can-stache-key"),o=e("can-assign"),a=e("can-reflect"),s=e("can-symbol"),c=e("can-observation-recorder"),u=e("can-view-scope/make-compute-like"),l=(e("can-reflect-dependencies"),e("can-event-queue/value/value")),f=e("can-stache-helpers"),d=e("can-simple-observable"),p=(e("can-log/dev/dev"),s.for("can.dispatch")),h=c.ignore(function(e){if(e.reads&&1===e.reads.length){var t=e.root;return t&&t[s.for("can.getValue")]&&(t=a.getValue(t)),t&&a.isObservableLike(t)&&a.isMapLike(t)&&"function"!=typeof t[e.reads[0].key]&&t}});var v=function(t,e,n){this.startingScope=t,this.key=e,this.read=this.read.bind(this),this.dispatch=this.dispatch.bind(this),"debugger"===e&&(this.startingScope={_context:f},this.read=function(){var e={scope:t};return(0,f.debugger)(e)});var r=this.observation=new i(this.read,this);this.options=o({observation:this.observation},n),this.fastPath=void 0,this.root=void 0,this.reads=void 0,this.setRoot=void 0,this._thisArg=new d,this.parentHasKey=void 0;var a=new Set;a.add(r),this.dependencies={valueDependencies:a},this._latestValue=void 0};function y(){this._value=this.newVal}function g(){this.value=this.newVal}l(v.prototype),o(v.prototype,{constructor:v,dispatch:function(e){var t=this.value;this._latestValue=this.value=e,this[p].call(this,this.value,t)},onBound:function(){this.bound=!0,a.onValue(this.observation,this.dispatch,"notify");var e=h(this);e&&this.toFastPath(e),this._latestValue=this.value=c.peekValue(this.observation)},onUnbound:function(){this.bound=!1,a.offValue(this.observation,this.dispatch,"notify"),this.toSlowPath()},set:function(e){var t=this.root||this.setRoot;t?this.reads.length?r.write(t,this.reads,e,this.options):a.setValue(t,e):this.startingScope.set(this.key,e,this.options)},get:function(){return c.isRecording()&&(c.add(this),this.bound||i.temporarilyBind(this)),!0===this.bound&&!0===this.fastPath?this._latestValue:c.peekValue(this.observation)},toFastPath:function(r){var a=this,e=this.observation;this.fastPath=!0,e.dependencyChange=function(e,t){if((n=t)&&"number"==typeof n.batchNum&&"string"==typeof n.type)throw"no event objects!";var n;return e===r&&"function"!=typeof t?(a._latestValue=t,this.newVal=t):a.toSlowPath(),i.prototype.dependencyChange.apply(this,arguments)},e.hasOwnProperty("_value")?e.onBound=y:e.onBound=g},toSlowPath:function(){this.observation.dependencyChange=i.prototype.dependencyChange,this.observation.onBound=i.prototype.onBound,this.fastPath=!1},read:function(){var e;return this.root?(e=r.read(this.root,this.reads,this.options),this.thisArg=e.parent):(e=this.startingScope.read(this.key,this.options),this.scope=e.scope,this.reads=e.reads,this.root=e.rootObserve,this.setRoot=e.setRoot,this.thisArg=e.thisArg,this.parentHasKey=e.parentHasKey),e.value},hasDependencies:function(){return this.bound||i.temporarilyBind(this),a.valueHasDependencies(this.observation)}}),Object.defineProperty(v.prototype,"thisArg",{get:function(){return this._thisArg.get()},set:function(e){this._thisArg.set(e)}});var m={"can.getValue":v.prototype.get,"can.setValue":v.prototype.set,"can.valueHasDependencies":v.prototype.hasDependencies,"can.getValueDependencies":function(){return this.dependencies},"can.getPriority":function(){return a.getPriority(this.observation)},"can.setPriority":function(e){a.setPriority(this.observation,e)}};a.assignSymbols(v.prototype,m),Object.defineProperty(v.prototype,"compute",{get:function(){var e=u(this);return Object.defineProperty(this,"compute",{value:e,writable:!1,configurable:!1}),e},configurable:!0}),Object.defineProperty(v.prototype,"initialValue",{get:function(){return this.bound||i.temporarilyBind(this),c.peekValue(this)},set:function(){throw new Error("initialValue should not be set")},configurable:!0}),n.exports=v}),define("can-view-scope/compute_data",["require","exports","module","can-view-scope/scope-key-data"],function(e,t,n){"use strict";var r=e("can-view-scope/scope-key-data");n.exports=function(e,t,n){return new r(e,t,n||{args:[]})}}),define("can-view-scope",["require","exports","module","can-stache-key","can-observation-recorder","can-view-scope/template-context","can-view-scope/compute_data","can-assign","can-namespace","can-reflect","can-log/dev/dev","can-define-lazy-value","can-stache-helpers","can-simple-map"],function(e,t,n){!function(e,t,n,r){"use strict";var c=t("can-stache-key"),m=t("can-observation-recorder"),a=t("can-view-scope/template-context"),i=t("can-view-scope/compute_data"),b=t("can-assign"),o=t("can-namespace"),w=t("can-reflect"),s=t("can-log/dev/dev"),u=t("can-define-lazy-value"),l=t("can-stache-helpers");function f(){return!1}var d=t("can-simple-map").extend("LetContext",{});function p(e,t,n){this._context=e,this._parent=t,this._meta=n||{},this.__cache={}}var h=/(\.\.\/)|(\.\/)|(this[\.@])/g;b(p,{read:c.read,TemplateContext:a,keyInfo:function(e){"./"===e&&(e="this");var i={remainingKey:e};if(i.isScope="scope"===e,i.isScope)return i;var t=e.substr(0,6);return i.isInScope="scope."===t||"scope@"===t,i.isInScope?i.remainingKey=e.substr(6):"scope/"===t?(i.walkScope=!0,i.remainingKey=e.substr(6)):"@scope/"===e.substr(0,7)?(i.walkScope=!0,i.remainingKey=e.substr(7)):(i.parentContextWalkCount=0,i.remainingKey=e.replace(h,function(e,t,n,r,a){return i.isContextBased=!0,void 0!==t&&i.parentContextWalkCount++,""}),".."===i.remainingKey?(i.parentContextWalkCount++,i.remainingKey="this"):"."!==i.remainingKey&&""!==i.remainingKey||(i.remainingKey="this"),"this"===i.remainingKey&&(i.isContextBased=!0)),i},isTemplateContextOrCanNotHaveProperties:function(e){var t=e._context;return t instanceof a||null==t},shouldSkipIfSpecial:function(e){return!0===(!0===e._meta.special)||!!p.isTemplateContextOrCanNotHaveProperties(e)},shouldSkipEverythingButSpecial:function(e){return!1===(!0===e._meta.special)||!!p.isTemplateContextOrCanNotHaveProperties(e)},makeShouldExitOnSecondNormalContext:function(){var r=!1;return function(e){var t=!e.isSpecial(),n=t&&r;return t&&(r=!0),n}},makeShouldExitAfterFirstNormalContext:function(){var t=!1;return function(e){return!!t||(!e.isSpecial()&&(t=!0),!1)}},makeShouldSkipSpecialContexts:function(e){var t=e||0;return function(e){return!(t<0&&e._meta.notContext)&&(!!e.isSpecial()||!(--t<0))}}}),b(p.prototype,{add:function(e,t){return e!==this._context?new this.constructor(e,this,t):this},find:function(e,t){var n=c.reads(e),r={shouldExit:f,shouldSkip:p.shouldSkipIfSpecial,shouldLookForHelper:!0,read:c.read};return this._walk(n,t,r).value},readFromSpecialContext:function(e){return this._walk([{key:e,at:!1}],{special:!0},{shouldExit:f,shouldSkip:p.shouldSkipEverythingButSpecial,shouldLookForHelper:!1,read:c.read})},readFromTemplateContext:function(e,t){var n=c.reads(e);return c.read(this.templateContext,n,t)},read:function(e,t){return t=t||{},this.readKeyInfo(p.keyInfo(e),t||{})},readKeyInfo:function(e,t){var n,r,a={read:t.read||c.read};if(e.isScope)return{value:this};if(e.isInScope)return r=c.reads(e.remainingKey),void 0!==(n=c.read(this,r,t)).value||n.parentHasKey||(n=this.readFromTemplateContext(e.remainingKey,t)),b(n,{thisArg:0<r.length?n.parent:void 0});if(e.isContextBased)return r="this"!==e.remainingKey?c.reads(e.remainingKey):[],a.shouldExit=p.makeShouldExitOnSecondNormalContext(),a.shouldSkip=p.makeShouldSkipSpecialContexts(e.parentContextWalkCount),a.shouldLookForHelper=!0,this._walk(r,t,a);if(e.walkScope)return a.shouldExit=f,a.shouldSkip=p.shouldSkipIfSpecial,a.shouldLookForHelper=!0,r=c.reads(e.remainingKey),this._walk(r,t,a);r=c.reads(e.remainingKey);var i=t&&!0===t.special;return a.shouldExit=p.makeShouldExitOnSecondNormalContext(),a.shouldSkip=i?p.shouldSkipEverythingButSpecial:p.shouldSkipIfSpecial,a.shouldLookForHelper=!i,this._walk(r,t,a)},_walk:function(n,e,t){for(var r,a,i,o,s,c=this,u=[],l=-1,f=b({foundObservable:function(e,t){a=e,i=n.slice(t)},earlyExit:function(e,t){(!0===(!0===c._meta.variable)&&0===t?w.hasKey(e,n[t].key):l<t||t===l&&"object"==typeof e&&w.hasOwnKey(e,n[t].key))&&(s=a,o=i,l=t)}},e),d=m.isRecording(),p=!1;c;)if(!0!==t.shouldSkip(c)){if(!0===t.shouldExit(c))break;p=!0,r=c._context;var h=m.trap(),v=t.read(r,n,f),y=h();if(void 0!==v.value||v.parentHasKey)return!y.length&&d?(a=v.parent,i=n.slice(n.length-1)):m.addMany(y),{scope:c,rootObserve:a,value:v.value,reads:i,thisArg:v.parent,parentHasKey:v.parentHasKey};u.push.apply(u,y),c=c._parent}else c=c._parent;if(t.shouldLookForHelper){var g=this.getHelperOrPartial(n);if(g&&g.value)return{value:g.value}}return m.addMany(u),{setRoot:s,reads:o,value:void 0,noContextAvailable:!p}},getDataForScopeSet:function(e,a){var i,t,n=p.keyInfo(e),r=b({read:function(e,t){if(void 0!==i||e instanceof d||(i=e),1<t.length){var n=t.slice(0,t.length-1),r=c.read(e,n,a).value;return null!=r&&w.hasKey(r,t[t.length-1].key)?{parent:r,parentHasKey:!0,value:void 0}:{}}return 1===t.length?w.hasKey(e,t[0].key)?{parent:e,parentHasKey:!0,value:void 0}:{}:{value:e}}},a),o=this.readKeyInfo(n,r);if("this"===n.remainingKey)return{parent:o.value,how:"setValue"};var s=n.remainingKey.split(".").pop();return o.thisArg?t=o.thisArg:i&&(t=i),void 0===t?{error:"Attempting to set a value at "+e+" where the context is undefined."}:!w.isObservableLike(t)&&w.isObservableLike(t[s])?w.isMapLike(t[s])?{parent:t,key:s,how:"updateDeep",warn:'can-view-scope: Merging data into "'+s+'" because its parent is non-observable'}:w.isValueLike(t[s])?{parent:t,key:s,how:"setValue"}:{parent:t,how:"write",key:s,passOptions:!0}:{parent:t,how:"write",key:s,passOptions:!0}},getHelper:function(e){return console.warn(".getHelper is deprecated, use .getHelperOrPartial"),this.getHelperOrPartial(e)},getHelperOrPartial:function(e){for(var t,n,r=this;r;){if((t=r._context)instanceof a){if(void 0!==(n=c.read(t.helpers,e,{proxyMethods:!1})).value)return n;if(void 0!==(n=c.read(t.partials,e,{proxyMethods:!1})).value)return n}r=r._parent}return c.read(l,e,{proxyMethods:!1})},get:function(e,t){return t=b({isArgument:!0},t),this.read(e,t).value},peek:m.ignore(function(e,t){return this.get(e,t)}),peak:m.ignore(function(e,t){return this.peek(e,t)}),getScope:function(e){for(var t=this;t;){if(e(t))return t;t=t._parent}},getContext:function(e){var t=this.getScope(e);return t&&t._context},getTemplateContext:function(){var t,e=this.getScope(function(e){return(t=e)._context instanceof a});return e||(e=new p(new a),t._parent=e),e},addTemplateContext:function(){return this.add(new a)},addLetContext:function(e){return this.add(new d(e||{}),{variable:!0})},getRoot:function(){for(var e=this,t=this;e._parent;)e=(t=e)._parent;return e._context instanceof a&&(e=t),e._context},getViewModel:function(){var e=this.getScope(function(e){return e._meta.viewModel});return e&&e._context},getTop:function(){var t;return this.getScope(function(e){return e._meta.viewModel&&(t=e),!1}),t&&t._context},getPathsForKey:function(e){},hasKey:function(e){var t,n=c.reads(e);return(t="scope"===n[0].key?c.read(this,n.slice(1),e):c.read(this._context,n,e)).foundLastParent&&t.parentHasKey},set:function(e,t,n){n=n||{};var r=this.getDataForScopeSet(e,n),a=r.parent;switch(r.warn&&s.warn(r.warn),r.how){case"set":a.set(r.key,t,r.passOptions?n:void 0);break;case"write":c.write(a,r.key,t,n);break;case"setValue":w.setValue("key"in r?a[r.key]:a,t);break;case"setKeyValue":w.setKeyValue(a,r.key,t);break;case"updateDeep":w.updateDeep(a[r.key],t)}},attr:m.ignore(function(e,t,n){return s.warn("can-view-scope::attr is deprecated, please use peek, get or set"),n=b({isArgument:!0},n),2===arguments.length?this.set(e,t,n):this.get(e,n)}),computeData:function(e,t){return i(this,e,t)},compute:function(e,t){return this.computeData(e,t).compute},cloneFromRef:function(){for(var t,e=[],n=this;n;){if(n._context instanceof a){t=n._parent;break}e.unshift(n),n=n._parent}return t?(e.forEach(function(e){t=t.add(e._context,e._meta)}),t):this},isSpecial:function(){return this._meta.notContext||this._meta.special||this._context instanceof a||this._meta.variable}}),p.prototype._read=p.prototype._walk,w.assignSymbols(p.prototype,{"can.hasKey":p.prototype.hasKey});["filename","lineNumber"].forEach(function(t){Object.defineProperty(p.prototype,t,{get:function(){return this.readFromTemplateContext(t).value},set:function(e){this.templateContext[t]=e}})}),u(p.prototype,"templateContext",function(){return this.getTemplateContext()._context}),u(p.prototype,"root",function(){return s.warn("`scope.root` is deprecated. Use either `scope.top` or `scope.vm` instead."),this.getRoot()}),u(p.prototype,"vm",function(){return this.getViewModel()}),u(p.prototype,"top",function(){return this.getTop()}),u(p.prototype,"helpers",function(){return l});["index","key","element","event","viewModel","arguments","helperOptions","args"].forEach(function(e){Object.defineProperty(p.prototype,e,{get:function(){return this.readFromSpecialContext(e).value}})}),o.view=o.view||{},r.exports=o.view.Scope=p}(0,e,0,n)}),define("can-stache/src/key-observable",["require","exports","module","can-simple-observable/settable/settable","can-stache-key"],function(e,t,n){"use strict";var r=e("can-simple-observable/settable/settable"),a=e("can-stache-key");function i(e,t){t=""+t,this.key=t,this.root=e,r.call(this,function(){return a.get(this,t)},e)}(i.prototype=Object.create(r.prototype)).set=function(e){a.set(this.root,this.key,e)},n.exports=i}),define("can-stache/src/utils",["require","exports","module","can-view-scope","can-observation-recorder","can-stache-key","can-reflect","can-stache/src/key-observable","can-symbol"],function(e,t,n){"use strict";var s=e("can-view-scope"),c=e("can-observation-recorder"),f=e("can-stache-key"),d=e("can-reflect"),p=e("can-stache/src/key-observable"),r=e("can-symbol").for("can.isView"),o=function(e){return function(){e&&(e.rendered=!0)}};n.exports={last:function(e){return null!=e&&e[e.length-1]},emptyHandler:function(){},jsonParse:function(e){return"'"===e[0]?e.substr(1,e.length-2):"undefined"===e?void 0:JSON.parse(e)},mixins:{last:function(){return this.stack[this.stack.length-1]},add:function(e){this.last().add(e)},subSectionDepth:function(){return this.stack.length-1}},createRenderers:function(e,t,n,r,a,i){e.fn=r?this.makeRendererConvertScopes(r,t,n,i,e.metadata):o(e.metadata),e.inverse=a?this.makeRendererConvertScopes(a,t,n,i,e.metadata):o(e.metadata),e.isSection=!(!r&&!a)},makeRendererConvertScopes:function(r,a,i,e,o){var t=function(e,t,n){return void 0===e||e instanceof s||(e=a?a.add(e):new s(e||{})),o&&(o.rendered=!0),r(e||a,n||i)};return e?t:c.ignore(t)},makeView:function(n){var e=c.ignore(function(e,t){return e instanceof s||(e=new s(e)),n(e,t)});return e[r]=!0,e},getItemsStringContent:function(e,t,n){for(var r="",a=f.get(e,"length"),i=d.isObservableLike(e),o=0;o<a;o++){var s=i?new p(e,o):e[o];r+=n.fn(s)}return r},getItemsFragContent:function(e,t,n){var r,a=[],i=f.get(e,"length"),o=d.isObservableLike(e),s=t.exprData&&t.exprData.hashExprs;0<d.size(s)&&(r={},d.eachKey(s,function(e,t){r[e.key]=t}));for(var c=0;c<i;c++){var u={},l=o?new p(e,c):e[c];0<d.size(r)&&(r.value&&(u[r.value]=l),r.index&&(u[r.index]=c)),a.push(t.fn(n.add(u,{notContext:!0}).add({index:c},{special:!0}).add(l)))}return a}}}),define("can-stache/src/html_section",["require","exports","module","can-view-target","can-stache/src/utils","can-globals/document/document","can-assign"],function(e,t,n){!function(e,t,n,r){"use strict";var a,i=t("can-view-target"),o=t("can-stache/src/utils"),s=t("can-globals/document/document"),c=t("can-assign"),u=o.last,l="undefined"!=typeof document&&(a=s().createElement("div"),function(e){return-1===e.indexOf("&")?e.replace(/\r\n/g,"\n"):(a.innerHTML=e,0===a.childNodes.length?"":a.childNodes.item(0).nodeValue)}),f=function(e){e&&(this.filename=e),this.stack=[new d]};c(f.prototype,o.mixins),c(f.prototype,{startSubSection:function(e){var t=new d(e);return this.stack.push(t),t},endSubSectionAndReturnRenderer:function(){if(this.last().isEmpty())return this.stack.pop(),null;var e=this.endSection();return o.makeView(e.compiled.hydrate.bind(e.compiled))},startSection:function(e){var t=new d(e);this.last().add(t.targetCallback),this.stack.push(t)},endSection:function(){return this.last().compile(),this.stack.pop()},inverse:function(){this.last().inverse()},compile:function(){var e=this.stack.pop().compile();return o.makeView(e.hydrate.bind(e))},push:function(e){this.last().push(e)},pop:function(){return this.last().pop()},removeCurrentNode:function(){this.last().removeCurrentNode()}});var d=function(n){this.data="targetData",this.targetData=[],this.targetStack=[];var r=this;this.targetCallback=function(e,t){n.call(this,e,t,r.compiled.hydrate.bind(r.compiled),r.inverseCompiled&&r.inverseCompiled.hydrate.bind(r.inverseCompiled))}};c(d.prototype,{inverse:function(){this.inverseData=[],this.data="inverseData"},push:function(e){this.add(e),this.targetStack.push(e)},pop:function(){return this.targetStack.pop()},add:function(e){"string"==typeof e&&(e=l(e)),this.targetStack.length?u(this.targetStack).children.push(e):this[this.data].push(e)},compile:function(){return this.compiled=i(this.targetData,s()),this.inverseData&&(this.inverseCompiled=i(this.inverseData,s()),delete this.inverseData),this.targetStack=this.targetData=null,this.compiled},removeCurrentNode:function(){return this.children().pop()},children:function(){return this.targetStack.length?u(this.targetStack).children:this[this.data]},isEmpty:function(){return!this.targetData.length}}),f.HTMLSection=d,r.exports=f}(0,e,0,n)}),define("can-view-live/lib/core",["require","exports","module","can-view-parser","can-dom-mutate","can-view-nodelist","can-fragment","can-child-nodes","can-reflect","can-reflect-dependencies"],function(e,t,n){"use strict";var r=e("can-view-parser"),s=e("can-dom-mutate"),i=e("can-view-nodelist"),o=e("can-fragment"),c=e("can-child-nodes"),a=e("can-reflect");e("can-reflect-dependencies");var u={setup:function(e,t,n){var r,a,i=!1,o=function(){return i||(i=!0,n(a),r&&(r(),r=void 0)),!0};return a={teardownCheck:function(e){return!e&&o()}},r=s.onNodeRemoval(e,function(){(function e(t,n){return t.contains?t.contains(n):t.nodeType===Node.DOCUMENT_NODE&&t.documentElement?e(t.documentElement,n):(n=n.parentNode)===t})(e.ownerDocument,e)||o()}),t(a),a},listen:function(e,t,n,r){return u.setup(e,function(){a.onValue(t,n,r||"notify")},function(e){a.offValue(t,n,r||"notify"),e.nodeList&&i.unregister(e.nodeList)})},getAttributeParts:function(e){var t,n={};return r.parseAttrs(e,{attrStart:function(e){n[e]="",t=e},attrValue:function(e){n[t]+=e},attrEnd:function(){}}),n},isNode:function(e){return e&&e.nodeType},addTextNodeIfNoChildren:function(e){e.firstChild||e.appendChild(e.ownerDocument.createTextNode(""))},replace:function(e,t,n){var r=e.slice(0),a=o(t);return i.register(e,n),i.update(e,c(a)),i.replace(r,a),e},getParentNode:function(e,t){return t&&11===e.parentNode.nodeType?t:e.parentNode},makeString:function(e){return null==e?"":""+e}};n.exports=u}),define("can-dom-data-state",["require","exports","module","can-namespace","can-dom-mutate","can-cid"],function(e,t,n){"use strict";var r=e("can-namespace"),i=e("can-dom-mutate"),o=e("can-cid"),s={},c={},u=function(){var e=o.get(this),t=!1;return e&&s[e]&&(t=!0,delete s[e]),c[e]&&(c[e](),delete c[e]),t},a={_data:s,_removalDisposalMap:c,getCid:function(){return o.get(this)},cid:function(){return o(this)},expando:o.domExpando,get:function(e){var t=o.get(this),n=t&&s[t];return void 0===e?n:n&&n[e]},set:function(e,t){var n=o(this),r=s[n]||(s[n]={});if(void 0!==e&&(r[e]=t,this&&"number"==typeof this.nodeType&&!c[n])){var a=this;c[n]=i.onNodeRemoval(a,function(){var e=a.ownerDocument,t=e.contains?e:e.documentElement;t&&t.contains(a)||setTimeout(function(){u.call(a)},13)})}return r},clean:function(e){var t=o.get(this),n=s[t];n&&n[e]&&delete n[e],function(e){for(var t in e)return!1;return!0}(n)&&u.call(this)},delete:u};if(r.domDataState)throw new Error("You can't have two versions of can-dom-data-state, check your dependencies");n.exports=r.domDataState=a}),define("can-attribute-observable/behaviors",["require","exports","module","can-globals/document/document","can-globals/global/global","can-dom-data-state","can-dom-events","can-dom-mutate","can-dom-mutate/node","can-globals/mutation-observer/mutation-observer","can-diff/list/list","can-queues"],function(e,t,n){!function(e,t,n,r){"use strict";var a,i=t("can-globals/document/document"),f=(e=t("can-globals/global/global")(),t("can-dom-data-state")),d=t("can-dom-events"),o=t("can-dom-mutate"),s=t("can-dom-mutate/node"),c=t("can-globals/mutation-observer/mutation-observer"),u=t("can-diff/list/list"),l=t("can-queues"),p={INPUT:!0,TEXTAREA:!0,SELECT:!0,BUTTON:!0},h=function(e){return"http://www.w3.org/2000/svg"===e.namespaceURI},v=function(){return!0},y=function(t,e){return(e=e||{}).get=function(){return this[t]},e.set=function(e){this[t]!==e&&(this[t]=e)},e},g=function(t){return{isBoolean:!0,set:function(e){t in this?this[t]=e:s.setAttribute.call(this,t,"")},remove:function(){this[t]=!1}}},m=function(e,t){if(!f.get.call(e,"attrMO")){var n=function(){t.call(e)},r=c();if(r){var a=new r(n);a.observe(e,{childList:!0,subtree:!0}),f.set.call(e,"attrMO",a)}else f.set.call(e,"attrMO",!0),f.set.call(e,"canBindingCallback",{onMutation:n})}},b=function(e,t){for(var n=e.firstChild;n;){if("OPTION"===n.nodeName&&t===n.value)return n;if("OPTGROUP"===n.nodeName){var r=b(n,t);if(r)return r}n=n.nextSibling}},w=function(e,t){var n;null!=t&&(n=b(e,t)),n?n.selected=!0:e.selectedIndex=-1},x=function(e,t){for(var n=e.firstChild;n;)"OPTION"===n.nodeName&&t(n),"OPTGROUP"===n.nodeName&&x(n,t),n=n.nextSibling},_=new Map,k=function(e,t){var n=Object.getOwnPropertyDescriptor(e,t);if(n)return n.writable||n.set;var r=Object.getPrototypeOf(e);return!!r&&k(r,t)},O={checked:{get:function(){return this.checked},set:function(e){var t=!!e||""===e||0===arguments.length;(this.checked=t)&&"radio"===this.type&&(this.defaultChecked=!0)},remove:function(){this.checked=!1},test:function(){return"INPUT"===this.nodeName}},class:{get:function(){return h(this)?this.getAttribute("class"):this.className},set:function(e){e=e||"",h(this)?s.setAttribute.call(this,"class",""+e):this.className=e}},disabled:g("disabled"),focused:{get:function(){return this===document.activeElement},set:function(e){var t=E.get(this,"focused"),n=this.ownerDocument.documentElement,r=this;function a(){e?r.focus():r.blur()}if(t!==e)if(n.contains(r))l.enqueueByQueue({mutate:[a]},null,[]);else var i=o.onNodeInsertion(r,function(){i(),a()});return!0},addEventListener:function(e,t,n){return n.call(this,"focus",t),n.call(this,"blur",t),function(e){e.call(this,"focus",t),e.call(this,"blur",t)}},test:function(){return"INPUT"===this.nodeName}},for:y("htmlFor"),innertext:y("innerText"),innerhtml:y("innerHTML"),innerHTML:y("innerHTML",{addEventListener:function(e,n,t){var r=[],a=this;return["change","blur"].forEach(function(e){var t=function(){n.apply(this,arguments)};d.addEventListener(a,e,t),r.push([e,t])}),function(t){r.forEach(function(e){t.call(a,e[0],e[1])})}}}),required:g("required"),readonly:g("readOnly"),selected:{get:function(){return this.selected},set:function(e){e=!!e,f.set.call(this,"lastSetValue",e),this.selected=e},addEventListener:function(n,t,e){var r,a,i,o=this,s=this.parentNode,c=o.selected,u=function(e){var t=o.selected;t!==(c=f.get.call(o,"lastSetValue")||c)&&(c=t,d.dispatch(o,n))},l=(r=s,a=e,(i=f.get.call(r,"attrSetChildOptions"))?Function.prototype:(i=function(){w(r,r.value)},f.set.call(r,"attrSetChildOptions",i),a.call(r,"change",i),function(e){f.clean.call(r,"attrSetChildOptions"),e.call(r,"change",i)}));return d.addEventListener(s,"change",u),e.call(o,n,t),function(e){l(e),d.removeEventListener(s,"change",u),e.call(o,n,t)}},test:function(){return"OPTION"===this.nodeName&&this.parentNode&&"SELECT"===this.parentNode.nodeName}},style:{set:(a=e.document&&i().createElement("div"),a&&a.style&&"cssText"in a.style?function(e){this.style.cssText=e||""}:function(e){s.setAttribute.call(this,"style",e)})},textcontent:y("textContent"),value:{get:function(){var e=this.value;return"SELECT"===this.nodeName&&"selectedIndex"in this&&-1===this.selectedIndex&&(e=void 0),e},set:function(e){var t,n=this.nodeName.toLowerCase();if("input"===n&&(e=null==(t=e)?"":""+t),this.value===e&&"option"!==n||(this.value=e),"input"!==n&&"textarea"!==n||(this.defaultValue=e),"select"===n){if(f.set.call(this,"attrValueLastVal",e),w(this,null===e?e:this.value),!this.ownerDocument.documentElement.contains(this))var r=this,a=o.onNodeInsertion(r,function(){a(),w(r,null===e?e:r.value)});m(this,function(){var e=f.get.call(this,"attrValueLastVal");E.set(this,"value",e),d.dispatch(this,"change")})}},test:function(){return p[this.nodeName]}},values:{get:function(){return t=[],x(this,function(e){e.selected&&t.push(e.value)}),t;var t},set:function(e){var t;t=e=e||[],x(this,function(e){e.selected=-1!==t.indexOf(e.value)}),f.set.call(this,"stickyValues",E.get(this,"values")),m(this,function(){var e=f.get.call(this,"stickyValues");E.set(this,"values",e);var t=f.get.call(this,"stickyValues");u(e.slice().sort(),t.slice().sort()).length&&d.dispatch(this,"values")})},addEventListener:function(t,n,e){var r=function(){d.dispatch(this,"values")};return d.addEventListener(this,"change",r),e.call(this,t,n),function(e){d.removeEventListener(this,"change",r),e.call(this,t,n)}}}},E={rules:_,specialAttributes:O,getRule:function(e,t){var n=O[t];if(n)return n;var r=_.get(e.constructor),a=r&&r[t];if(a)return a;if(!(t in e))return this.attribute(t);var i,o,s,c,u=k(e,t)?this.property(t):this.attribute(t);return i=e,o=t,s=u,(c=_.get(i.prototype))||(c={},_.set(i.constructor,c)),c[o]=s},attribute:function(t){return{get:function(){return this.getAttribute(t)},set:function(e){s.setAttribute.call(this,t,e)}}},property:function(t){return{get:function(){return this[t]},set:function(e){this[t]=e}}},findSpecialListener:function(e){return O[e]&&O[e].addEventListener},setAttrOrProp:function(e,t,n){return this.set(e,t,n)},set:function(e,t,n){var r=this.getRule(e,t),a=r&&r.set;if(a)return a.call(e,n)},get:function(e,t){var n=this.getRule(e,t),r=n&&n.get;if(r)return n.test?n.test.call(e)&&r.call(e):r.call(e)},remove:function(e,t){t=t.toLowerCase();var n,r=O[t],a=r&&r.set,i=r&&r.remove,o=(n=r)&&n.test||v;"function"==typeof i&&o.call(e)?i.call(e):"function"==typeof a&&o.call(e)?a.call(e,void 0):s.removeAttribute.call(e,t)}};r.exports=E}(function(){return this}(),e,0,n)}),define("can-view-live/lib/attr",["require","exports","module","can-view-live/lib/core","can-reflect","can-queues","can-attribute-observable/behaviors"],function(e,t,n){"use strict";var r=e("can-view-live/lib/core"),a=e("can-reflect"),i=e("can-queues"),o=e("can-attribute-observable/behaviors");r.attr=function(t,n,e){r.listen(t,e,function(e){i.domUIQueue.enqueue(o.set,o,[t,n,e])}),o.set(t,n,a.getValue(e))}}),define("can-view-live/lib/attrs",["require","exports","module","can-view-live/lib/core","can-view-callbacks","can-dom-mutate","can-dom-mutate/node","can-reflect","can-reflect-dependencies"],function(e,t,n){"use strict";var u=e("can-view-live/lib/core"),l=e("can-view-callbacks"),f=e("can-dom-mutate"),d=e("can-dom-mutate/node"),p=e("can-reflect");e("can-reflect-dependencies");u.attrs=function(i,t,o,s){if(p.isObservableLike(t)){var n,c={};p.onValue(t,a,"domUI");n=f.onNodeRemoval(i,function(){var e=i.ownerDocument;(e.contains?e:e.documentElement).contains(i)||(p.offValue(t,a,"domUI"),n&&(n(),n=void 0))}),a(p.getValue(t))}else{var e=u.getAttributeParts(t);for(var r in e)d.setAttribute.call(i,r,e[r])}function a(e){var t,n=u.getAttributeParts(e);for(t in n){var r=n[t];if(r!==c[t]){d.setAttribute.call(i,t,r);var a=l.attr(t);a&&a(i,{attributeName:t,scope:o,options:s})}delete c[t]}for(t in c)d.removeAttribute.call(i,t);c=n}}}),define("can-view-live/lib/html",["require","exports","module","can-view-live/lib/core","can-view-nodelist","can-fragment","can-child-nodes","can-reflect","can-symbol","can-queues"],function(e,t,n){"use strict";var l=e("can-view-live/lib/core"),f=e("can-view-nodelist"),d=e("can-fragment"),p=e("can-child-nodes"),h=e("can-reflect"),r=e("can-symbol"),v=e("can-queues"),y=r.for("can.viewInsert");function g(e,t,n){if(!0!==e.nodeList.isUnregistered){var r=h.toArray(p(t));n||f.update(e.nodeList,r,e.oldNodes);var a=e.oldNodes;e.oldNodes=r,f.replace(a,t)}}l.html=function(e,t,n,r){var i,a,o,s,c;void 0!==r&&(Array.isArray(r)?o=r:(o=r.nodeList,c=r));var u={reasonLog:"live.html replace::"+h.getName(t)};n=l.getParentNode(e,n),i=l.listen(n,t,function(e){f.first(s).parentNode&&a(e,!0);var t=f.first(s).parentNode;i.teardownCheck(t)}),s=o||[e],a=function(e,t){e&&"function"==typeof e[y]&&(e=e[y](c));var n="function"==typeof e,r=d(n?"":e);if(l.addTextNodeIfNoChildren(r),!0===t){i.oldNodes=f.unregisterChildren(s,!0);var a=!1;n&&(e(r.firstChild),a=f.first(s)===r.firstChild),v.domUIQueue.enqueue(g,null,[i,r,a],u)}else i.oldNodes=f.update(s,p(r)),n&&e(r.firstChild),f.replace(i.oldNodes,r)},i.nodeList=s,o?o.unregistered=i.teardownCheck:f.register(s,i.teardownCheck),a(h.getValue(t))}}),define("can-view-live/lib/set-observable",["require","exports","module","can-simple-observable","can-reflect"],function(e,t,n){"use strict";var r=e("can-simple-observable"),a=e("can-reflect");function i(e,t){this.setter=t,r.call(this,e)}((i.prototype=Object.create(r.prototype)).constructor=i).prototype.set=function(e){this.setter(e)},a.assignSymbols(i.prototype,{"can.setValue":i.prototype.set}),n.exports=i}),define("can-diff/patcher/patcher",["require","exports","module","can-reflect","can-key-tree","can-symbol","can-diff/list/list","can-queues","can-symbol"],function(e,t,n){"use strict";var r=e("can-reflect"),a=e("can-key-tree"),i=e("can-symbol"),o=e("can-diff/list/list"),s=e("can-queues"),c=(i=e("can-symbol")).for("can.onValue"),u=i.for("can.offValue"),l=i.for("can.onPatches"),f=i.for("can.offPatches"),d=function(e,t){this.handlers=new a([Object,Array],{onFirst:this.setup.bind(this),onEmpty:this.teardown.bind(this)}),this.observableOrList=e,this.isObservableValue=r.isValueLike(this.observableOrList)||r.isObservableLike(this.observableOrList),this.isObservableValue?this.priority=r.getPriority(e):this.priority=t||0,this.onList=this.onList.bind(this),this.onPatchesNotify=this.onPatchesNotify.bind(this),this.onPatchesDerive=this.onPatchesDerive.bind(this),this.patches=[]};d.prototype={constructor:d,setup:function(){this.observableOrList[c]?(r.onValue(this.observableOrList,this.onList,"notify"),this.setupList(r.getValue(this.observableOrList))):this.setupList(this.observableOrList)},teardown:function(){this.observableOrList[u]&&r.offValue(this.observableOrList,this.onList,"notify"),this.currentList&&this.currentList[f]&&this.currentList[f](this.onPatchesNotify,"notify")},setupList:function(e){(this.currentList=e)&&e[l]&&e[l](this.onPatchesNotify,"notify")},onList:function(e){var t=this.currentList||[];e=e||[],t[f]&&t[f](this.onPatchesNotify,"notify");var n=o(t,e);this.currentList=e,this.onPatchesNotify(n),e[l]&&e[l](this.onPatchesNotify,"notify")},onPatchesNotify:function(e){this.patches.push.apply(this.patches,e),s.deriveQueue.enqueue(this.onPatchesDerive,this,[],{priority:this.priority})},onPatchesDerive:function(){var e=this.patches;this.patches=[],s.enqueueByQueue(this.handlers.getNode([]),this.currentList,[e,this.currentList],null,["Apply patches",e])}},r.assignSymbols(d.prototype,{"can.onPatches":function(e,t){this.handlers.add([t||"mutate",e])},"can.offPatches":function(e,t){this.handlers.delete([t||"mutate",e])}}),n.exports=d}),define("can-view-live/lib/list",["require","exports","module","can-view-live/lib/core","can-view-nodelist","can-fragment","can-child-nodes","can-dom-mutate/node","can-reflect","can-symbol","can-reflect-dependencies","can-simple-observable","can-view-live/lib/set-observable","can-diff/patcher/patcher"],function(e,t,n){"use strict";var c=e("can-view-live/lib/core"),p=e("can-view-nodelist"),f=e("can-fragment"),u=e("can-child-nodes"),h=e("can-dom-mutate/node"),v=e("can-reflect"),r=e("can-symbol"),y=(e("can-reflect-dependencies"),e("can-simple-observable")),g=e("can-view-live/lib/set-observable"),l=e("can-diff/patcher/patcher"),m=[].splice,b=function(e,t,n,r,a){var i=[];t&&(p.register(i,null,!0,!0),i.parentList=t,i.expression="#each SUBEXPRESSION");var o=n.apply(r,a.concat([i])),s=f(o),c=v.toArray(u(s));return t?(p.update(i,c),e.push(i)):e.push(p.register(c)),s},w=function(e,t,n){var r=e.splice(t+1,n),a=[];return r.forEach(function(e){var t=p.unregister(e);[].push.apply(a,t)}),a},a=r.for("can.onPatches"),i=r.for("can.offPatches");function d(e,t,n,r,a,i,o){this.patcher=new l(t),a=c.getParentNode(e,a),this.value=t,this.render=n,this.context=r,this.parentNode=a,this.falseyRender=o,this.masterNodeList=i||p.register([e],null,!0),this.placeholder=e,this.indexMap=[],this.isValueLike=v.isValueLike(this.value),this.isObservableLike=v.isObservableLike(this.value),this.onPatches=this.onPatches.bind(this);var s=this.data=c.setup(a,this.setupValueBinding.bind(this),this.teardownValueBinding.bind(this));this.masterNodeList.unregistered=function(){s.teardownCheck()}}a=r.for("can.onPatches"),i=r.for("can.offPatches");d.prototype={setupValueBinding:function(){this.patcher[a](this.onPatches,"domUI"),this.patcher.currentList&&this.patcher.currentList.length?this.onPatches([{insert:this.patcher.currentList,index:0,deleteCount:0}]):this.addFalseyIfEmpty()},teardownValueBinding:function(){this.patcher[i](this.onPatches,"domUI"),this.exit=!0,this.remove({length:this.patcher.currentList?this.patcher.currentList.length:0},0,!0)},onPatches:function(e){if(!this.exit)for(var t=0,n=e.length;t<n;t++){var r=e[t];"move"===r.type?this.move(r.toIndex,r.fromIndex):(r.deleteCount&&this.remove({length:r.deleteCount},r.index,!0),r.insert&&r.insert.length&&this.add(r.insert,r.index))}},add:function(e,i){var o=this.placeholder.ownerDocument.createDocumentFragment(),s=[],c=[],u=this.masterNodeList,l=this.render,f=this.context;e.forEach(function(e,t){var n=new y(t+i),r=new g(e,function(e){v.setKeyValue(this.patcher.currentList,n.get(),e)}.bind(this)),a=b(s,u,l,f,[r,n]);o.appendChild(a),c.push(n)},this);var t=i+1;if(!this.indexMap.length){var n=w(u,0,u.length-1);p.remove(n)}if(u[t]){var r=p.first(u[t]);h.insertBefore.call(r.parentNode,o,r)}else p.after(1===t?[this.placeholder]:[p.last(this.masterNodeList[t-1])],o);m.apply(this.masterNodeList,[t,0].concat(s)),m.apply(this.indexMap,[i,0].concat(c));for(var a=i+c.length,d=this.indexMap.length;a<d;a++)this.indexMap[a].set(a)},remove:function(e,t){t<0&&(t=this.indexMap.length+t);var n=w(this.masterNodeList,t,e.length),r=this.indexMap;r.splice(t,e.length);for(var a=t,i=r.length;a<i;a++)r[a].set(a);this.exit?p.unregister(this.masterNodeList):(this.addFalseyIfEmpty(),p.remove(n))},addFalseyIfEmpty:function(){if(this.falseyRender&&0===this.indexMap.length){var e=[],t=b(e,this.masterNodeList,this.falseyRender,this.currentList,[this.currentList]);p.after([this.masterNodeList[0]],t),this.masterNodeList.push(e[0])}},move:function(e,t){e+=1,t+=1;var n,r=this.masterNodeList,a=this.indexMap,i=r[e],o=f(p.flatten(r[t]));n=t<e?p.last(i).nextSibling:p.first(i),r[0].parentNode.insertBefore(o,n);var s=r[t];[].splice.apply(r,[t,1]),[].splice.apply(r,[e,0,s]),e-=1;var c=a[t-=1];[].splice.apply(a,[t,1]),[].splice.apply(a,[e,0,c]);for(var u=Math.min(t,e),l=a.length;u<l;u++)a[u].set(u)},set:function(e,t){this.remove({length:1},t,!0),this.add([e],t)}},c.list=function(e,t,n,r,a,i,o){var s;e.nodeType!==Node.TEXT_NODE&&(e=(i?(s=document.createTextNode(""),p.replace(i,s),p.update(i,[s])):(s=document.createTextNode(""),e.parentNode.replaceChild(s,e)),s));new d(e,t,n,r,a,i,o)}}),define("can-view-live/lib/text",["require","exports","module","can-view-live/lib/core","can-view-nodelist","can-reflect"],function(e,t,n){"use strict";var s=e("can-view-live/lib/core"),c=e("can-view-nodelist"),u=e("can-reflect");s.text=function(t,e,n,r){var a;t.nodeType!==Node.TEXT_NODE&&(t=(r?(a=document.createTextNode(""),c.replace(r,a),c.update(r,[a])):(a=document.createTextNode(""),t.parentNode.replaceChild(a,t)),a));var i=s.getParentNode(t,n);t.nodeValue=s.makeString(u.getValue(e));var o=s.listen(i,e,function(e){t.nodeValue=s.makeString(e)},"domUI");r||(r=c.register([t],null,!0)),r.unregistered=o.teardownCheck,o.nodeList=r}}),define("can-view-live",["require","exports","module","can-view-live/lib/core","can-view-live/lib/attr","can-view-live/lib/attrs","can-view-live/lib/html","can-view-live/lib/list","can-view-live/lib/text"],function(e,t,n){"use strict";var r=e("can-view-live/lib/core");e("can-view-live/lib/attr"),e("can-view-live/lib/attrs"),e("can-view-live/lib/html"),e("can-view-live/lib/list"),e("can-view-live/lib/text"),n.exports=r}),define("can-stache/src/text_section",["require","exports","module","can-view-live","can-stache/src/utils","can-dom-mutate/node","can-assign","can-reflect","can-observation"],function(e,t,n){"use strict";var i=e("can-view-live"),r=e("can-stache/src/utils"),o=e("can-dom-mutate/node"),a=e("can-assign"),s=e("can-reflect"),c=e("can-observation"),u=function(){},l=function(e){e&&(this.filename=e),this.stack=[new d]};a(l.prototype,r.mixins),a(l.prototype,{startSection:function(e){var t=new d;this.last().add({process:e,truthy:t}),this.stack.push(t)},endSection:function(){this.stack.pop()},inverse:function(){this.stack.pop();var e=new d;this.last().last().falsey=e,this.stack.push(e)},compile:function(r){var a=this.stack[0].compile();return function(e){var t=new c(function(){return a(e)},null,{isObservable:!1});s.onValue(t,u);var n=s.getValue(t);s.valueHasDependencies(t)?(r.textContentOnly?i.text(this,t):r.attr?i.attr(this,r.attr,t):i.attrs(this,t,e),s.offValue(t,u)):r.textContentOnly?this.nodeValue=n:r.attr?o.setAttribute.call(this,r.attr,n):i.attrs(this,n)}}});var f=function(t,n,r){return function(e){return t.call(this,e,n,r)}},d=function(){this.values=[]};a(d.prototype,{add:function(e){this.values.push(e)},last:function(){return this.values[this.values.length-1]},compile:function(){for(var a=this.values,i=a.length,e=0;e<i;e++){var t=this.values[e];"object"==typeof t&&(a[e]=f(t.process,t.truthy&&t.truthy.compile(),t.falsey&&t.falsey.compile()))}return function(e){for(var t,n="",r=0;r<i;r++)n+="string"==typeof(t=a[r])?t:t.call(this,e);return n}}}),n.exports=l}),define("can-stache/expressions/arg",function(e,t,n){"use strict";var r=function(e,t){this.expr=e,this.modifiers=t||{},this.isCompute=!1};r.prototype.value=function(){return this.expr.value.apply(this.expr,arguments)},n.exports=r}),define("can-stache/expressions/literal",function(e,t,n){"use strict";var r=function(e){this._value=e};r.prototype.value=function(){return this._value},n.exports=r}),define("can-simple-observable/setter/setter",["require","exports","module","can-reflect","can-observation","can-simple-observable/settable/settable","can-event-queue/value/value"],function(e,t,n){"use strict";var r=e("can-reflect"),a=e("can-observation"),i=e("can-simple-observable/settable/settable");e("can-event-queue/value/value");function o(e,t){this.setter=t,this.observation=new a(e),this.handler=this.handler.bind(this)}((o.prototype=Object.create(i.prototype)).constructor=o).prototype.set=function(e){this.setter(e)},o.prototype.hasDependencies=function(){return r.valueHasDependencies(this.observation)},r.assignSymbols(o.prototype,{"can.setValue":o.prototype.set,"can.valueHasDependencies":o.prototype.hasDependencies}),n.exports=o}),define("can-stache/src/expression-helpers",["require","exports","module","can-stache/expressions/arg","can-stache/expressions/literal","can-reflect","can-stache-key","can-observation","can-observation-recorder","can-view-scope/make-compute-like","can-simple-observable/setter/setter"],function(e,t,n){"use strict";var r=e("can-stache/expressions/arg"),a=e("can-stache/expressions/literal"),s=e("can-reflect"),c=e("can-stache-key"),u=e("can-observation"),l=e("can-observation-recorder"),i=e("can-view-scope/make-compute-like"),f=e("can-simple-observable/setter/setter");n.exports={getObservableValue_fromDynamicKey_fromObservable:function(e,t,n,r){var a,i=function(){return c.reads((""+s.getValue(e)).replace(/\./g,"\\."))},o=new f(function(){var e=c.read(s.getValue(t),i());return a=e.parentHasKey,e.value},function(e){c.write(s.getValue(t),i(),e)});return u.temporarilyBind(o),o.initialValue=l.peekValue(o),o.parentHasKey=a,o},convertToArgExpression:function(e){return e instanceof r||e instanceof a?e:new r(e)},toComputeOrValue:function(e){return s.isObservableLike(e)?s.isValueLike(e)&&!1===s.valueHasDependencies(e)?s.getValue(e):e.compute?e.compute:i(e):e},toCompute:function(e){return e?e.isComputed?e:e.compute?e.compute:i(e):e}}}),define("can-stache/expressions/hashes",["require","exports","module","can-reflect","can-observation","can-stache/src/expression-helpers"],function(e,t,n){"use strict";var o=e("can-reflect"),s=e("can-observation"),c=e("can-stache/src/expression-helpers"),r=function(e){this.hashExprs=e};r.prototype.value=function(e,t){var n={};for(var r in this.hashExprs){var a=c.convertToArgExpression(this.hashExprs[r]),i=a.value.apply(a,arguments);n[r]={call:!a.modifiers||!a.modifiers.compute,value:i}}return new s(function(){var e={};for(var t in n)e[t]=n[t].call?o.getValue(n[t].value):c.toComputeOrValue(n[t].value);return e})},n.exports=r}),define("can-stache/expressions/bracket",["require","exports","module","can-stache/src/expression-helpers"],function(e,t,n){"use strict";var r=e("can-stache/src/expression-helpers"),a=function(e,t,n){this.root=t,this.key=e};a.prototype.value=function(e,t){var n=this.root?this.root.value(e,t):e.peek("this");return r.getObservableValue_fromDynamicKey_fromObservable(this.key.value(e,t),n,e,t,{})},a.prototype.closingTag=function(){},n.exports=a}),define("can-stache/src/set-identifier",function(e,t,n){"use strict";n.exports=function(e){this.value=e}}),define("can-stache/expressions/call",["require","exports","module","can-stache/expressions/hashes","can-stache/src/set-identifier","can-symbol","can-simple-observable/setter/setter","can-stache/src/expression-helpers","can-reflect","can-assign","can-view-scope","can-observation"],function(e,t,n){"use strict";var u=e("can-stache/expressions/hashes"),s=e("can-stache/src/set-identifier"),r=e("can-symbol"),c=e("can-simple-observable/setter/setter"),l=e("can-stache/src/expression-helpers"),f=e("can-reflect"),d=e("can-assign"),p=(r.for("can-stache.sourceText"),r.for("can.isView")),h=e("can-view-scope"),v=e("can-observation"),a=function(e,t){this.methodExpr=e,this.argExprs=t.map(l.convertToArgExpression)};a.prototype.args=function(e,t){for(var a={},i=[],n="function"==typeof t,r=0,o=this.argExprs.length;r<o;r++){var s=this.argExprs[r];if(s.expr instanceof u&&d(a,s.expr.hashExprs),!n||!t(r)){var c=s.value.apply(s,arguments);i.push({call:!s.modifiers||!s.modifiers.compute,value:c})}}return function(e){var t=[];0<f.size(a)&&(t.hashExprs=a);for(var n=0,r=i.length;n<r;n++)t[n]=e?i[n].value:i[n].call?f.getValue(i[n].value):l.toCompute(i[n].value);return t}},a.prototype.value=function(r,a){var i=this.methodExpr.value(r,{proxyMethods:!1});v.temporarilyBind(i);var e=f.getValue(i),o=this.args(r,e&&e.ignoreArgLookup),t=function(e){var t=f.getValue(i);if("function"==typeof t){f.isObservableLike(t)&&(t=f.getValue(t));var n=o(t.isLiveBound);return t.requiresOptionsArgument&&(n.hashExprs&&a&&a.exprData&&(a.exprData.hashExprs=n.hashExprs),void 0!==a&&n.push(a)),!0===t[p]&&(n[0]instanceof h||(n[0]=r.getTemplateContext().add(n[0])),n.push(a.nodeList)),arguments.length&&n.unshift(new s(e)),t.apply(i.thisArg||r.peek("this"),n)}};return a&&a.doNotWrapInObservation?t():new c(t,t)},a.prototype.closingTag=function(){return this.methodExpr.key},n.exports=a}),define("can-stache/expressions/helper",["require","exports","module","can-stache/expressions/literal","can-stache/expressions/hashes","can-assign","can-log/dev/dev","can-stache/src/expression-helpers","can-reflect"],function(e,t,n){"use strict";var s=e("can-stache/expressions/literal"),c=(e("can-stache/expressions/hashes"),e("can-assign")),i=(e("can-log/dev/dev"),e("can-stache/src/expression-helpers")),r=e("can-reflect"),a=function(e,t,n){this.methodExpr=e,this.argExprs=t,this.hashExprs=n,this.mode=null};a.prototype.args=function(e){for(var t=[],n=0,r=this.argExprs.length;n<r;n++){var a=this.argExprs[n];t.push(i.toComputeOrValue(a.value.apply(a,arguments)))}return t},a.prototype.hash=function(e){var t={};for(var n in this.hashExprs){var r=this.hashExprs[n];t[n]=i.toComputeOrValue(r.value.apply(r,arguments))}return t},a.prototype.value=function(n,r){var e=this.methodExpr instanceof s?""+this.methodExpr._value:this.methodExpr.key,a=this,t=n.computeData(e,{proxyMethods:!1}),i=t&&t.initialValue,o=t&&t.thisArg;return"function"==typeof i&&(t=function(){var e=a.args(n),t=c(c({},r),{hash:a.hash(n),exprData:a});return e.push(t),i.apply(o||n.peek("this"),e)}),t},a.prototype.closingTag=function(){return this.methodExpr.key},"production"!==process.env.NODE_ENV&&r.assignSymbols(a.prototype,{"can.getName":function(){return r.getName(this.constructor)+"{{"+this.sourceText()+"}}"}}),n.exports=a}),define("can-stache/expressions/lookup",["require","exports","module","can-stache/src/expression-helpers","can-reflect","can-symbol","can-assign"],function(e,t,n){"use strict";var r=e("can-stache/src/expression-helpers"),a=e("can-reflect"),i=e("can-symbol").for("can-stache.sourceText"),o=e("can-assign"),s=function(e,t,n){this.key=e,this.rootExpr=t,a.setKeyValue(this,i,n)};s.prototype.value=function(e,t){return this.rootExpr?r.getObservableValue_fromDynamicKey_fromObservable(this.key,this.rootExpr.value(e),e,{},{}):e.computeData(this.key,o({warnOnMissingKey:!0},t))},n.exports=s}),define("can-stache/src/expression",["require","exports","module","can-stache/expressions/arg","can-stache/expressions/literal","can-stache/expressions/hashes","can-stache/expressions/bracket","can-stache/expressions/call","can-stache/expressions/helper","can-stache/expressions/lookup","can-stache/src/set-identifier","can-stache/src/expression-helpers","can-stache/src/utils","can-assign","can-reflect","can-symbol"],function(e,t,n){"use strict";var l=e("can-stache/expressions/arg"),f=e("can-stache/expressions/literal"),d=e("can-stache/expressions/hashes"),p=e("can-stache/expressions/bracket"),h=e("can-stache/expressions/call"),r=e("can-stache/expressions/helper"),a=e("can-stache/expressions/lookup"),i=e("can-stache/src/set-identifier"),o=e("can-stache/src/expression-helpers"),v=e("can-stache/src/utils"),s=e("can-assign"),y=v.last,g=e("can-reflect"),m=e("can-symbol").for("can-stache.sourceText"),b=/[\w\.\\\-_@\/\&%]+/,c=/('.*?'|".*?"|=|[\w\.\\\-_@\/*%\$]+|[\(\)]|,|\~|\[|\]\s*|\s*(?=\[))/g,u=/\]\s+/,w=/^('.*?'|".*?"|-?[0-9]+\.?[0-9]*|true|false|null|undefined)$/,x=/^[\.@]\w/,_=function(e){return t=e,b.test(t)&&x.test(e);var t},k=function(e){return e.children||(e.children=[]),e},O=function(){this.root={children:[],type:"Root"},this.current=this.root,this.stack=[this.root]};s(O.prototype,{top:function(){return y(this.stack)},isRootTop:function(){return this.top()===this.root},popTo:function(e){this.popUntil(e),this.pop()},pop:function(){this.isRootTop()||this.stack.pop()},first:function(e){for(var t=this.stack.length-1;0<t&&-1===e.indexOf(this.stack[t].type);)t--;return this.stack[t]},firstParent:function(e){for(var t=this.stack.length-2;0<t&&-1===e.indexOf(this.stack[t].type);)t--;return this.stack[t]},popUntil:function(e){for(;-1===e.indexOf(this.top().type)&&!this.isRootTop();)this.stack.pop();return this.top()},addTo:function(e,t){var n=this.popUntil(e);k(n).children.push(t)},addToAndPush:function(e,t){this.addTo(e,t),this.stack.push(t)},push:function(e){this.stack.push(e)},topLastChild:function(){return y(this.top().children)},replaceTopLastChild:function(e){var t=k(this.top()).children;return t.pop(),t.push(e),e},replaceTopLastChildAndPush:function(e){this.replaceTopLastChild(e),this.stack.push(e)},replaceTopAndPush:function(e){var t;return(t=(this.top()===this.root||this.stack.pop(),k(this.top()).children)).pop(),t.push(e),this.stack.push(e),e}});var E=function(e){var t=e.lastIndexOf("./"),n=e.lastIndexOf(".");if(t<n)return e.substr(0,n)+"@"+e.substr(n+1);var r=-1===t?0:t+2,a=e.charAt(r);return"."===a||"@"===a?e.substr(0,r)+"@"+e.substr(r+1):e.substr(0,r)+"@"+e.substr(r)},L=function(e){var t=e.top();if(t&&"Lookup"===t.type){var n=e.stack[e.stack.length-2];"Helper"!==n.type&&n&&e.replaceTopAndPush({type:"Helper",method:t})}},q={toComputeOrValue:o.toComputeOrValue,convertKeyToLookup:E,Literal:f,Lookup:a,Arg:l,Hash:function(){},Hashes:d,Call:h,Helper:r,Bracket:p,SetIdentifier:i,tokenize:function(e){var n=[];return(e.trim()+" ").replace(c,function(e,t){u.test(t)?(n.push(t[0]),n.push(t.slice(1))):n.push(t)}),n},lookupRules:{default:function(e,t,n){return"Helper"===e.type?r:a},method:function(e,t,n){return a}},methodRules:{default:function(e){return"Call"===e.type?h:r},call:function(e){return h}},parse:function(e,t){t=t||{};var n=this.ast(e);return t.lookupRule||(t.lookupRule="default"),"string"==typeof t.lookupRule&&(t.lookupRule=q.lookupRules[t.lookupRule]),t.methodRule||(t.methodRule="default"),"string"==typeof t.methodRule&&(t.methodRule=q.methodRules[t.methodRule]),this.hydrateAst(n,t,t.baseMethodType||"Helper")},hydrateAst:function(t,n,r,e){var a;if("Lookup"===t.type)return new(n.lookupRule(t,r,e))(t.key,t.root&&this.hydrateAst(t.root,n,r),t[m]);if("Literal"===t.type)return new f(t.value);if("Arg"===t.type)return new l(this.hydrateAst(t.children[0],n,r,e),{compute:!0});if("Hash"===t.type)throw new Error("");if("Hashes"===t.type)return a={},t.children.forEach(function(e){a[e.prop]=this.hydrateAst(e.children[0],n,r,!0)},this),new d(a);if("Call"!==t.type&&"Helper"!==t.type)return"Bracket"===t.type?new p(this.hydrateAst(t.children[0],n),t.root?this.hydrateAst(t.root,n):void 0,void 0):void 0;a={};var i=[],o=t.children,s=n.methodRule(t);if(o)for(var c=0;c<o.length;c++){var u=o[c];"Hashes"===u.type&&"Helper"===t.type&&s!==h?u.children.forEach(function(e){a[e.prop]=this.hydrateAst(e.children[0],n,t.type,!0)},this):i.push(this.hydrateAst(u,n,t.type,!0))}return new s(this.hydrateAst(t.method,n,t.type),i,a)},ast:function(e){var t=this.tokenize(e);return this.parseAst(t,{index:0})},parseAst:function(e,t){for(var n,r,a,i,o=new O;t.index<e.length;){var s=e[t.index],c=e[t.index+1];if(t.index++,"="===c){(n=o.top())&&"Lookup"===n.type&&("Call"!==(r=o.firstParent(["Call","Helper","Hash"])).type&&"Root"!==r.type||(o.popUntil(["Call"]),n=o.top(),o.replaceTopAndPush({type:"Helper",method:"Root"===n.type?y(n.children):n})));var u={type:"Hash",prop:s};"Hashes"===(r=o.first(["Call","Helper","Hashes","Root"])).type?o.addToAndPush(["Hashes"],u):(o.addToAndPush(["Helper","Call","Root"],{type:"Hashes",children:[u]}),o.push(u)),t.index++}else if(w.test(s))L(o),"Hash"===(r=o.first(["Helper","Call","Hash","Bracket"])).type&&r.children&&0<r.children.length?o.addTo(["Helper","Call","Bracket"],{type:"Literal",value:v.jsonParse(s)}):"Bracket"===r.type&&r.children&&0<r.children.length?o.addTo(["Helper","Call","Hash"],{type:"Literal",value:v.jsonParse(s)}):o.addTo(["Helper","Call","Hash","Bracket"],{type:"Literal",value:v.jsonParse(s)});else if(b.test(s))a=o.topLastChild(),r=o.first(["Helper","Call","Hash","Bracket"]),a&&("Call"===a.type||"Bracket"===a.type)&&_(s)?o.replaceTopLastChildAndPush({type:"Lookup",root:a,key:s.slice(1)}):"Bracket"===r.type?r.children&&0<r.children.length?"Helper"===o.first(["Helper","Call","Hash","Arg"]).type&&"."!==s[0]?o.addToAndPush(["Helper"],{type:"Lookup",key:s}):o.replaceTopAndPush({type:"Lookup",key:s.slice(1),root:r}):o.addToAndPush(["Bracket"],{type:"Lookup",key:s}):(L(o),o.addToAndPush(["Helper","Call","Hash","Arg","Bracket"],{type:"Lookup",key:s}));else if("~"===s)L(o),o.addToAndPush(["Helper","Call","Hash"],{type:"Arg",key:s});else if("("===s){if("Lookup"!==(n=o.top()).type)throw new Error("Unable to understand expression "+e.join(""));o.replaceTopAndPush({type:"Call",method:(i=n,"Lookup"===i.type&&(g.setKeyValue(i,m,i.key),i.key=E(i.key)),i)})}else if(")"===s)o.popTo(["Call"]);else if(","===s){"Call"!==o.first(["Call"]).type?o.popUntil(["Hash"]):o.popUntil(["Call"])}else if("["===s)if(n=o.top(),!(a=o.topLastChild())||"Call"!==a.type&&"Bracket"!==a.type)if("Lookup"===n.type||"Bracket"===n.type){var l={type:"Bracket",root:n};o.replaceTopAndPush(l)}else"Call"===n.type?o.addToAndPush(["Call"],{type:"Bracket"}):" "===n?(o.popUntil(["Lookup","Call"]),L(o),o.addToAndPush(["Helper","Call","Hash"],{type:"Bracket"})):o.replaceTopAndPush({type:"Bracket"});else o.replaceTopLastChildAndPush({type:"Bracket",root:a});else"]"===s?o.pop():" "===s&&o.push(s)}return o.root.children[0]}};n.exports=q}),define("can-stache/src/mustache_core",["require","exports","module","can-view-live","can-view-nodelist","can-observation","can-observation-recorder","can-stache/src/utils","can-stache/src/expression","can-fragment","can-dom-mutate","can-symbol","can-reflect","can-log/dev/dev","can-globals/document/document","can-define-lazy-value"],function(e,t,n){!function(e,t,n,r){"use strict";var v=t("can-view-live"),y=t("can-view-nodelist"),g=t("can-observation"),m=t("can-observation-recorder"),l=t("can-stache/src/utils"),b=t("can-stache/src/expression"),w=t("can-fragment"),x=t("can-dom-mutate"),_=t("can-symbol"),k=t("can-reflect"),f=(t("can-log/dev/dev"),t("can-globals/document/document")),a=t("can-define-lazy-value"),i=_.for("can.toDOM");function d(e,t,n,r){this.metadata={rendered:!1},this.stringOnly=r,this.scope=e,this.nodeList=t,this.exprData=n}a(d.prototype,"context",function(){return this.scope.peek("this")});var o=/(?:(^|\r?\n)(\s*)(\{\{([\s\S]*)\}\}\}?)([^\S\n\r]*)($|\r?\n))|(\{\{([\s\S]*)\}\}\}?)/g,s=/(\s*)(\{\{\{?)(-?)([\s\S]*?)(-?)(\}\}\}?)(\s*)/g,O=function(){},E=_.for("can.viewInsert");function L(e){return null!==e&&"object"==typeof e&&("function"==typeof e[i]||"function"==typeof e[E]||"number"==typeof e.nodeType)}var q={expression:b,makeEvaluator:function(r,e,t,n,a,i,o){if("^"===t){var s=a;a=i,i=s}var c,u=new d(r,e,n,o);if(l.createRenderers(u,r,e,a,i,o),n instanceof b.Call)c=n.value(r,u);else if(n instanceof b.Bracket)c=n.value(r);else if(n instanceof b.Lookup)c=n.value(r);else if(n instanceof b.Literal)c=n.value.bind(n);else if(n instanceof b.Helper&&n.methodExpr instanceof b.Bracket)c=n.methodExpr.value(r,u);else if("function"==typeof(c=n.value(r,u)))return c;return!t||u.metadata.rendered?c:"#"===t||"^"===t?function(){var e,t=k.getValue(c);if(u.metadata.rendered)e=t;else if("string"!=typeof t&&k.isListLike(t)){var n=k.isObservableLike(t)&&k.isListLike(t);e=k.getKeyValue(t,"length")?o?l.getItemsStringContent(t,n,u):w(l.getItemsFragContent(t,u,r)):u.inverse(r)}else e=t?u.fn(t||r):u.inverse(r);return u.metadata.rendered=!1,e}:void 0},makeLiveBindingPartialRenderer:function(e,n){var u,l=(e=e.trim()).split(/\s+/).shift();return l!==e&&(u=q.expression.parse(e)),function(s,e){var c=[this];c.expression=">"+l,y.register(c,null,e||!0,n.directlyNested);var t=new g(function(){var t=l,n=s;if(u&&1===u.argExprs.length){var e=k.getValue(u.argExprs[0].value(s));void 0===e||(n=s.add(e))}var r,a=k.getKeyValue(n.templateContext.partials,t);if(a)r=function(){return a.render?a.render(n,c):a(n)};else{var i=n.read(t,{isArgument:!0}).value;if(null===i||!i&&"*"===t[0])return w("");i&&(t=i),r=function(){if("function"==typeof t)return t(n,{},c);var e=q.getTemplateById(t);return e?e(n,{},c):f().createDocumentFragment()}}var o=m.ignore(r)();return w(o)});k.setPriority(t,c.nesting),v.html(this,t,this.parentNode,c)}},makeStringBranchRenderer:function(i,e,t){var o=q.expression.parse(e),s=i+e,n=function(e,t,n){var r,a=e.__cache[s];return!i&&a||(a=S(e,null,i,o,t,n,!0),i||(e.__cache[s]=a)),null==(r=a[_.for("can.onValue")]?k.getValue(a):a())?"":""+r};return n.exprData=o,n},makeLiveBindingBranchRenderer:function(f,d,p){var h=q.expression.parse(d),e=function(e,t,n,r){var a=p.tag,i=[this];i.expression=d,y.register(i,null,t||!0,p.directlyNested);var o,s=S(e,i,f,h,n,r,a);if(o=s[_.for("can.onValue")]?s:new g(s,null,{isObservable:!1}),!1===k.setPriority(o,i.nesting))throw new Error("can-stache unable to set priority on observable");k.onValue(o,O);var c=k.getValue(o);if("function"!=typeof c||h instanceof b.Lookup){if(k.valueHasDependencies(o))p.attr?v.attr(this,p.attr,o):p.tag?v.attrs(this,o):p.text&&!L(c)?v.text(this,o,this.parentNode,i):v.html(this,o,this.parentNode,{nodeList:i});else if(p.attr)x.setAttribute(this,p.attr,c);else if(p.tag)v.attrs(this,c);else if(p.text&&!L(c))this.nodeValue=v.makeString(c);else if(null!=c)if("function"==typeof c[E]){var u=c[E]({nodeList:i}),l=y.update(i,[u]);y.replace(l,u)}else y.replace([this],w(c,this.ownerDocument))}else m.ignore(c)(this);k.offValue(o,O)};return e.exprData=h,e},splitModeFromExpression:function(e,t){var n=(e=e.trim()).charAt(0);return 0<="#/{&^>!<".indexOf(n)?e=e.substr(1).trim():n=null,"{"===n&&t.node&&(n=null),{mode:n,expression:e}},cleanLineEndings:function(e){return e.replace(o,function(e,t,n,r,a,i,o,s,c,u){i=i||"",t=t||"",n=n||"";var l=p(a||c,{});return s||0<=">{".indexOf(l.mode)?e:0<="^#!/".indexOf(l.mode)?(n=t+n&&" ")+r+(0!==u&&o.length?t+"\n":""):n+r+i+(n.length||0!==u?t+"\n":"")})},cleanWhitespaceControl:function(e){return e.replace(s,function(e,t,n,r,a,i,o,s,c){return"-"===r&&(t=""),"-"===i&&(s=""),t+n+a+o+s})},getTemplateById:function(){}},S=q.makeEvaluator,p=q.splitModeFromExpression;r.exports=q}(0,e,0,n)}),define("can-globals/base-url/base-url",["require","exports","module","can-globals/can-globals-instance","can-globals/global/global","can-globals/document/document"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-globals/can-globals-instance");t("can-globals/global/global"),t("can-globals/document/document"),a.define("base-url",function(){var e=a.getKeyValue("global"),t=a.getKeyValue("document");if(t&&"baseURI"in t)return t.baseURI;if(e.location){var n=e.location.href,r=n.lastIndexOf("/");return-1!==r?n.substr(0,r):n}return"undefined"!=typeof process?process.cwd():void 0}),r.exports=a.makeExport("base-url")}(0,e,0,n)}),define("can-parse-uri",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace");n.exports=r.parseURI=function(e){var t=String(e).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return t?{href:t[0]||"",protocol:t[1]||"",authority:t[2]||"",host:t[3]||"",hostname:t[4]||"",port:t[5]||"",pathname:t[6]||"",search:t[7]||"",hash:t[8]||""}:null}}),define("can-join-uris",["require","exports","module","can-namespace","can-parse-uri"],function(e,t,n){"use strict";var r=e("can-namespace"),a=e("can-parse-uri");n.exports=r.joinURIs=function(e,t){return t=a(t||""),e=a(e||""),t&&e?(t.protocol||e.protocol)+(t.protocol||t.authority?t.authority:e.authority)+(n=t.protocol||t.authority||"/"===t.pathname.charAt(0)?t.pathname:t.pathname?(e.authority&&!e.pathname?"/":"")+e.pathname.slice(0,e.pathname.lastIndexOf("/")+1)+t.pathname:e.pathname,r=[],n.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(e){"/.."===e?r.pop():r.push(e)}),r.join("").replace(/^\//,"/"===n.charAt(0)?"/":""))+(t.protocol||t.authority||t.pathname?t.search:t.search||e.search)+t.hash:null;var n,r}}),define("can-stache/helpers/-debugger",["require","exports","module","can-log"],function(e,t,n){"use strict";var r=e("can-log");function a(){}var i=a,o=a;function s(e,t){r.warn("Forgotten {{debugger}} helper")}s.requiresOptionsArgument=!0,n.exports={helper:s,evaluateArgs:o,resolveValue:i,__testing:{}}}),define("can-stache/src/truthy-observable",["require","exports","module","can-observation","can-reflect"],function(e,t,n){"use strict";var r=e("can-observation"),a=e("can-reflect");n.exports=function(e){return new r(function(){return!!a.getValue(e)})}}),define("can-stache/helpers/converter",["require","exports","module","can-stache/src/set-identifier","can-reflect"],function(e,t,n){"use strict";var a=e("can-stache/src/set-identifier"),i=e("can-reflect");n.exports=function(r){return r=r||{},function(e,t){var n=i.toArray(arguments);return e instanceof a?"function"==typeof r.set?r.set.apply(this,[e.value].concat(n.slice(1))):t(e.value):"function"==typeof r.get?r.get.apply(this,n):n[0]}}}),define("can-dom-data",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace"),a=new WeakMap,i=function(e){var t=!1;return a.has(e)&&(t=!0,a.delete(e)),t},o={_data:a,get:function(e,t){var n=a.get(e);return void 0===t?n:n&&n[t]},set:function(e,t,n){var r=a.get(e);return void 0===r&&(r={},a.set(e,r)),void 0!==t&&(r[t]=n),r},clean:function(e,t){var n=a.get(e);n&&n[t]&&delete n[t],function(e){for(var t in e)return!1;return!0}(n)&&i(e)},delete:i};if(r.domData)throw new Error("You can't have two versions of can-dom-data, check your dependencies");n.exports=r.domData=o}),define("can-stache/helpers/-for-of",["require","exports","module","can-reflect","can-observation","can-view-live","can-view-nodelist","can-stache/src/expression","can-stache/src/key-observable"],function(e,t,n){var p=e("can-reflect"),h=e("can-observation"),v=e("can-view-live"),y=e("can-view-nodelist"),g=e("can-stache/src/expression"),m=e("can-stache/src/key-observable");var r=function(r){if(1!==r.exprData.argExprs.length)throw new Error("for(of) broken syntax");var a,e,t=r.exprData.argExprs[0].expr;if(t instanceof g.Lookup)e=t.value(r.scope);else if(t instanceof g.Helper){if("of"!==t.argExprs[0].key)throw new Error("for(of) broken syntax");a=t.methodExpr.key,e=t.argExprs[1].value(r.scope)}var n,i,o,s,c,u=e,l=[].slice.call(arguments).pop(),f=(n=u)&&p.isValueLike(n)?(h.temporarilyBind(n),p.getValue(n)):n;if(f&&!p.isListLike(f))return i=f,o=a,s=r,c=[],p.each(i,function(e,t){var n=new m(i,t),r={};void 0!==o&&(r[o]=n),c.push(s.fn(s.scope.add({key:t},{special:!0}).addLetContext(r)))}),s.stringOnly?c.join(""):c;if(l.stringOnly){var d=[];return p.eachIndex(f,function(e,t){var n={};void 0!==a&&(n[a]=e),d.push(r.fn(l.scope.add({index:t},{special:!0}).addLetContext(n)))}),d.join("")}return l.metadata.rendered=!0,function(e){var t=[e];t.expression="live.list",y.register(t,null,l.nodeList,!0),y.update(l.nodeList,[e]);v.list(e,u,function(e,t,n){var r={};return void 0!==a&&(r[a]=e),l.fn(l.scope.add({index:t},{special:!0}).addLetContext(r),l.options,n)},l.context,e.parentNode,t,function(e,t){return l.inverse(l.scope,l.options,t)})}};r.isLiveBound=!0,r.requiresOptionsArgument=!0,r.ignoreArgLookup=function(e){return 0===e},n.exports=r}),define("can-stache/helpers/-let",["require","exports","module","can-reflect"],function(e,t,n){var r=e("can-reflect");function a(e){return!0===e._meta.variable}n.exports=function(e){if(e.isSection)return e.fn(e.scope.addLetContext(e.hash));var t=e.scope.getScope(a);if(!t)throw new Error("There is no variable scope!");return r.assignMap(t._context,e.hash),document.createTextNode("")}}),define("can-stache/helpers/-portal",["require","exports","module","can-reflect","can-view-live","can-view-nodelist","can-observation","can-globals/document/document","can-dom-mutate","can-dom-mutate/node"],function(e,t,n){!function(e,t,n,r){var u=t("can-reflect"),l=t("can-view-live"),f=t("can-view-nodelist"),d=t("can-observation"),p=t("can-globals/document/document"),h=t("can-dom-mutate"),v=t("can-dom-mutate/node");function a(i,o){function n(){return o.fn(o.scope.addLetContext({}),o.options)}var r,a;function s(){r&&(u.offValue(i,c),r=null),a&&(f.remove(a),a=null)}function c(){if(s(),r=u.getValue(i)){var e=p().createTextNode("");v.appendChild.call(r,e),(a=[e]).expression="live.html",f.register(a,null,null,!0);var t=new d(n,null,{isObservable:!1});l.html(e,t,r,a),u.onValue(i,c),h.onNodeRemoval(r,s)}}return c(),function(e){var t=p(),n=t.createComment("portal("+u.getName(i)+")"),r=t.createDocumentFragment();v.appendChild.call(r,n),f.replace([e],r);var a=[n];a.expression="portal",f.register(a,s,o.nodeList,!0),f.update(o.nodeList,[n])}}a.isLiveBound=!0,a.requiresOptionsArgument=!0,r.exports=a}(0,e,0,n)}),define("can-stache/helpers/core",["require","exports","module","can-view-live","can-view-nodelist","can-stache/src/utils","can-globals/base-url/base-url","can-join-uris","can-assign","can-log/dev/dev","can-reflect","can-stache/helpers/-debugger","can-stache/src/key-observable","can-observation","can-stache/src/truthy-observable","can-stache-helpers","can-stache/helpers/converter","can-dom-data","can-dom-data-state","can-stache/helpers/-for-of","can-stache/helpers/-let","can-stache/helpers/-portal"],function(e,t,n){!function(e,t,n,r){"use strict";var c=t("can-view-live"),u=t("can-view-nodelist"),l=t("can-stache/src/utils"),s=t("can-globals/base-url/base-url"),f=t("can-join-uris"),a=t("can-assign"),d=(t("can-log/dev/dev"),t("can-reflect")),i=t("can-stache/helpers/-debugger").helper,p=t("can-stache/src/key-observable"),o=t("can-observation"),h=t("can-stache/src/truthy-observable"),v=t("can-stache-helpers"),y=t("can-stache/helpers/converter"),g=t("can-dom-data"),m=t("can-dom-data-state"),b=t("can-stache/helpers/-for-of"),w=t("can-stache/helpers/-let"),x=t("can-stache/helpers/-portal"),_={},k={},O=new WeakMap,E={looksLikeOptions:function(e){return e&&"function"==typeof e.fn&&"function"==typeof e.inverse},resolve:function(e){return e&&d.isValueLike(e)?d.getValue(e):e},resolveHash:function(e){var t={};for(var n in e)t[n]=E.resolve(e[n]);return t},bindAndRead:function(e){return e&&d.isValueLike(e)?(o.temporarilyBind(e),d.getValue(e)):e},registerHelper:function(e,t){t.requiresOptionsArgument=!0,v[e]=t},registerHelpers:function(e){var t,n;for(t in e)n=e[t],E.registerHelper(t,E.makeSimpleHelper(n))},registerConverter:function(e,t){E.registerHelper(e,y(t))},makeSimpleHelper:function(e){return function(){var t=[];return d.eachIndex(arguments,function(e){t.push(E.resolve(e))}),e.apply(this,t)}},addHelper:function(e,t){return"object"==typeof e?E.registerHelpers(e):E.registerHelper(e,E.makeSimpleHelper(t))},addConverter:function(e,t){if("object"!=typeof e){var n=y(t);n.isLiveBound=!0,E.registerHelper(e,n)}else O.has(e)||(O.set(e,!0),d.eachKey(e,function(e,t){E.addConverter(t,e)}))},addLiveHelper:function(e,t){return t.isLiveBound=!0,E.registerHelper(e,t)},getHelper:function(e,t){var n=t&&t.getHelper(e);return n||(n=v[e]),n},__resetHelpers:function(){for(var e in v)delete v[e];O.delete(k),E.addBuiltInHelpers(),E.addBuiltInConverters()},addBuiltInHelpers:function(){d.each(_,function(e,t){v[t]=e})},addBuiltInConverters:function(){E.addConverter(k)},_makeLogicHelper:function(e,r){return a(function(){var e,t=Array.prototype.slice.call(arguments,0);E.looksLikeOptions(t[t.length-1])&&(e=t.pop());var n=new o(function(){return e?!!r(t):r(t)});return e?n.get()?e.fn():e.inverse():n.get()},{requiresOptionsArgument:!0,isLiveBound:!0})}},L=a(function(e,t){return(e&&d.isValueLike(e)?d.getValue(new h(e)):!!E.resolve(e))?t.fn(t.scope||this):t.inverse(t.scope||this)},{requiresOptionsArgument:!0,isLiveBound:!0}),q=E._makeLogicHelper("eq",function(e){for(var t,n,r=0;r<e.length;r++){if(t="function"==typeof(t=E.resolve(e[r]))?t():t,0<r&&t!==n)return!1;n=t}return!0}),S=E._makeLogicHelper("and",function(e){if(0===e.length)return!1;for(var t,n=0,r=e.length;n<r;n++)if(!(t=E.resolve(e[n])))return t;return t}),M=E._makeLogicHelper("or",function(e){if(0===e.length)return!1;for(var t,n=0,r=e.length;n<r;n++)if(t=E.resolve(e[n]))return t;return t}),P=function(n,e){E.resolve(n);var r=!1,t=function(e,t){if(!r&&E.resolve(n)===E.resolve(e))return r=!0,t.fn(t.scope)},a=function(e){if(!r)return!e||e.scope.peek("this")};a.requiresOptionsArgument=t.requiresOptionsArgument=!0,d.assignSymbols(a,{"can.isValueLike":!0,"can.isFunctionLike":!1,"can.getValue":function(){return this(e)}});var i=e.scope.add({case:t,default:a},{notContext:!0});return e.fn(i,e)},C=function(e){var t=[].slice.call(arguments),n=t.pop(),r=t.map(function(e){var t=E.resolve(e);return"function"==typeof t?t():t}).join(""),a=d.getKeyValue(n.scope.templateContext.helpers,"module"),i=a?a.uri:void 0;if("."===r[0]&&i)return f(i,r);var o="undefined"!=typeof System&&(System.renderingBaseURL||System.baseURL)||s();return"/"!==r[0]&&"/"!==o[o.length-1]&&(o+="/"),f(o,r)},V=function(n){var a,r,i=[].slice.call(arguments).pop(),e=i.exprData.hashExprs,t=E.bindAndRead(n);if(0<d.size(e)&&(a={},d.eachKey(e,function(e,t){a[e.key]=t})),(d.isObservableLike(t)&&d.isListLike(t)||d.isListLike(t)&&d.isValueLike(n))&&!i.stringOnly)return i.metadata.rendered=!0,function(e){var t=[e];t.expression="live.list",u.register(t,null,i.nodeList,!0),u.update(i.nodeList,[e]);c.list(e,n,function(e,t,n){var r={};return 0<d.size(a)&&(a.value&&(r[a.value]=e),a.index&&(r[a.index]=t)),i.fn(i.scope.add(r,{notContext:!0}).add({index:t},{special:!0}).add(e),i.options,n)},i.context,e.parentNode,t,function(e,t){return i.inverse(i.scope.add(e),i.options,t)})};var o,s=E.resolve(n);return s&&d.isListLike(s)?(o=l.getItemsFragContent(s,i,i.scope),i.stringOnly?o.join(""):o):d.isObservableLike(s)&&d.isMapLike(s)||s instanceof Object?(o=[],d.each(s,function(e,t){var n=new p(s,t);r={},0<d.size(a)&&(a.value&&(r[a.value]=n),a.key&&(r[a.key]=t)),o.push(i.fn(i.scope.add(r,{notContext:!0}).add({key:t},{special:!0}).add(n)))}),i.stringOnly?o.join(""):o):void 0};V.isLiveBound=C.requiresOptionsArgument=P.requiresOptionsArgument=!0,V.requiresOptionsArgument=!0,V.ignoreArgLookup=function(e){return 1===e};var j=a(function(e,t){t||(t=e,e=0);var n=t.scope.peek("scope.index");return""+(("function"==typeof n?n():n)+e)},{requiresOptionsArgument:!0}),D=function(e,t){var n=e;return t?(e=E.resolve(e),t.hash&&0<d.size(t.hash)&&(n=t.scope.add(t.hash,{notContext:!0}).add(n))):(t=e,e=!0,n=t.hash),t.fn(n||{})},I=function(e,t){return L.apply(this,[e,a(a({},t),{fn:t.inverse,inverse:t.fn})])};I.requiresOptionsArgument=D.requiresOptionsArgument=!0,I.isLiveBound=!0;var T={get:function(e,t){return E.looksLikeOptions(t)?d.getValue(e)?t.inverse():t.fn():!d.getValue(e)},set:function(e,t){d.setValue(t,!e)}};a(_,{debugger:i,each:V,eachOf:V,index:j,if:L,is:q,eq:q,unless:I,with:D,console:console,data:function(t,e){var n=(E.looksLikeOptions(e)?e.context:e)||this;return function(e){m.set.call(e,t,n)}},domData:function(t,e){var n=(E.looksLikeOptions(e)?e.context:e)||this;return function(e){g.set(e,t,n)}},switch:P,joinBase:C,and:S,or:M,let:w,for:b,portal:x}),a(k,{not:T}),E.addBuiltInHelpers(),E.addBuiltInConverters(),r.exports=E}(0,e,0,n)}),define("can-stache-ast/controls",function(e,t,n){"use strict";var r=/(?:(^|\r?\n)(\s*)(\{\{([\s\S]*)\}\}\}?)([^\S\n\r]*)($|\r?\n))|(\{\{([\s\S]*)\}\}\}?)/g,a=/(\s*)(\{\{\{?)(-?)([\s\S]*?)(-?)(\}\}\}?)(\s*)/g;function i(e,t,n,r,a,i,o,s){return"-"===r&&(t=""),"-"===i&&(s=""),t+n+a+o+s}t.cleanLineEndings=function(e){return e.replace(r,function(e,t,n,r,a,i,o,s,c,u){i=i||"",t=t||"",n=n||"";var l,f,d,p=(f={},d=(l=(l=a||c).trim()).charAt(0),0<="#/{&^>!<".indexOf(d)?l=l.substr(1).trim():d=null,"{"===d&&f.node&&(d=null),{mode:d,expression:l});return s||0<=">{".indexOf(p.mode)?e:0<="^#!/".indexOf(p.mode)?(n=t+n&&" ")+r+(0!==u&&o.length?t+"\n":""):n+r+i+(n.length||0!==u?t+"\n":"")})},t.cleanWhitespaceControl=function(e){return e.replace(a,i)}}),define("can-stache-ast",["require","exports","module","can-stache-ast/controls","can-view-parser"],function(e,t,n){"use strict";var m=e("can-stache-ast/controls"),b=e("can-view-parser");t.parse=function(e,t){1===arguments.length&&(t=arguments[0],e=void 0);var n=t;n=m.cleanWhitespaceControl(n),n=m.cleanLineEndings(n);var r=[],a=[],i=[],o={},s=new Map,c=!1,u=!1,l=!1,f=!1,d=!1,p="",h="",v=null;function y(e){p&&(o[p]=h,p=""),d?a.push(h):r.push(h),i.push({specifier:h,loc:{line:e},attributes:s}),s=new Map}var g=b(n,{filename:e,start:function(e,t){"can-import"===e?(f=t,c=!(d=!1)):"can-dynamic-import"===e?(f=t,c=d=!0):c&&(c=!(d=!0))},attrStart:function(e){v=e,s.set(v,!0),"from"===e?u=!0:"as"!==e&&"export-as"!==e||(l=!0)},attrEnd:function(e){"from"===e?u=!1:"as"!==e&&"export-as"!==e||(l=!1)},attrValue:function(e){c&&s.set(v,e),u&&c?h=e:l&&c&&(p=e)},end:function(e,t,n){"can-import"!==e&&"can-dynamic-import"!==e||!f||y(n)},close:function(e,t,n){"can-import"!==e&&"can-dynamic-import"!==e||y(n)},chars:function(e){0<e.trim().length&&(d=!0)},special:function(){d=!0}},!0);return{intermediate:g,program:g,imports:r,dynamicImports:a,importDeclarations:i,ases:o,exports:o}}}),define("can-import-module",["require","exports","module","can-globals/global/global","can-namespace"],function(e,t,n){!function(e,t,n,r){"use strict";var i=t("can-globals/global/global"),a=t("can-namespace");r.exports=a.import=function(r,a){return new Promise(function(t,n){try{var e=i();"object"==typeof e.System&&"function"==typeof e.System.import?e.System.import(r,{name:a}).then(t,n):e.define&&e.define.amd?e.require([r],function(e){t(e)}):e.require?t(e.require(r)):"undefined"!=typeof stealRequire?steal.import(r,{name:a}).then(t,n):t()}catch(e){n(e)}})}}(0,e,0,n)}),define("can-stache",["require","exports","module","can-view-parser","can-view-callbacks","can-stache/src/html_section","can-stache/src/text_section","can-stache/src/mustache_core","can-stache/helpers/core","can-stache-ast","can-stache/src/utils","can-attribute-encoder","can-log/dev/dev","can-namespace","can-globals/document/document","can-assign","can-import-module","can-reflect","can-view-scope","can-view-scope/template-context","can-observation-recorder","can-symbol","can-view-target","can-view-nodelist"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-view-parser"),v=t("can-view-callbacks"),y=t("can-stache/src/html_section"),g=t("can-stache/src/text_section"),m=t("can-stache/src/mustache_core"),i=t("can-stache/helpers/core"),o=t("can-stache-ast").parse,s=t("can-stache/src/utils"),b=s.makeRendererConvertScopes,w=s.last,c=(t("can-attribute-encoder"),t("can-log/dev/dev"),t("can-namespace")),u=t("can-globals/document/document"),x=t("can-assign"),l=t("can-import-module"),_=t("can-reflect"),k=t("can-view-scope"),O=t("can-view-scope/template-context"),E=t("can-observation-recorder"),f=t("can-symbol");t("can-view-target"),t("can-view-nodelist"),v.tag("content")||v.tag("content",function(e,t){return t.scope});var L=f.for("can.isView"),d="http://www.w3.org/2000/svg",q={svg:d,g:d,defs:d,path:d,filter:d,feMorphology:d,feGaussianBlur:d,feOffset:d,feComposite:d,feColorMatrix:d,use:d},S={xmlns:"http://www.w3.org/2000/xmlns/","xlink:href":"http://www.w3.org/1999/xlink"},M={style:!0,script:!0};function p(i,e){1===arguments.length&&(e=arguments[0],i=void 0);var o={};"string"==typeof e&&(e=m.cleanWhitespaceControl(e),e=m.cleanLineEndings(e));var s=new y(i),c={node:null,attr:null,sectionElementStack:[],text:!1,namespaceStack:[],textContentOnly:null},u=function(e,t,n,r){if(">"===t)e.add(m.makeLiveBindingPartialRenderer(n,f({filename:e.filename,lineNo:r})));else if("/"===t){"<"===e.last().startedWith?(o[n]=e.endSubSectionAndReturnRenderer(),e.removeCurrentNode()):e.endSection(),e instanceof y&&c.sectionElementStack.pop()}else if("else"===t)e.inverse();else{var a=e instanceof y?m.makeLiveBindingBranchRenderer:m.makeStringBranchRenderer;if("{"===t||"&"===t)e.add(a(null,n,f({filename:e.filename,lineNo:r})));else if("#"===t||"^"===t||"<"===t){var i=a(t,n,f({filename:e.filename,lineNo:r}));e.startSection(i),e.last().startedWith=t,e instanceof y&&c.sectionElementStack.push({type:"section"})}else e.add(a(null,n,f({text:!0,filename:e.filename,lineNo:r})))}},l=function(){var e=c.sectionElementStack[c.sectionElementStack.length-1];return!c.sectionElementStack.length||("section"===e.type||"custom"===e.type)},f=function(e){var t={tag:c.node&&c.node.tag,attr:c.attr&&c.attr.name,directlyNested:l(),textContentOnly:!!c.textContentOnly};return e?x(t,e):t},d=function(e,t){e.attributes||(e.attributes=[]),e.attributes.unshift(t)};a(e,{filename:i,start:function(e,t,n){var r=q[e];r&&!t&&c.namespaceStack.push(r),c.node={tag:e,children:[],namespace:r||w(c.namespaceStack)}},end:function(n,e,t){var r=v.tag(n),a=l();e?(s.add(c.node),r&&d(c.node,function(e,t){v.tagHandler(this,n,{scope:e,subtemplate:null,templateType:"stache",parentNodeList:t,directlyNested:a})})):(s.push(c.node),c.sectionElementStack.push({type:r?"custom":null,tag:r?null:n,templates:{},directlyNested:a}),r?s.startSubSection():M[n]&&(c.textContentOnly=new g(i))),c.node=null},close:function(n,e){q[n]&&c.namespaceStack.pop();var r,t=v.tag(n);t&&(r=s.endSubSectionAndReturnRenderer()),M[n]&&(s.last().add(c.textContentOnly.compile(f())),c.textContentOnly=null);var a=s.pop();if(t)if("can-template"===n){var i=c.sectionElementStack[c.sectionElementStack.length-2];r&&(i.templates[a.attrs.name]=b(r)),s.removeCurrentNode()}else{var o=c.sectionElementStack[c.sectionElementStack.length-1];d(a,function(e,t){v.tagHandler(this,n,{scope:e,subtemplate:r?b(r):r,templateType:"stache",parentNodeList:t,templates:o.templates,directlyNested:o.directlyNested})})}c.sectionElementStack.pop()},attrStart:function(e,t){c.node.section?c.node.section.add(e+'="'):c.attr={name:e,value:""}},attrEnd:function(n,e){var t=S[n];if(c.node.section)c.node.section.add('" ');else{c.node.attrs||(c.node.attrs={}),c.attr.section?c.node.attrs[c.attr.name]=c.attr.section.compile(f()):c.node.attrs[c.attr.name]=t?{value:c.attr.value,namespaceURI:S[n]}:c.attr.value;var r=v.attr(n);r&&(c.node.attributes||(c.node.attributes=[]),c.node.attributes.push(function(e,t){r(this,{attributeName:n,scope:e,nodeList:t})})),c.attr=null}},attrValue:function(e,t){var n=c.node.section||c.attr.section;n?n.add(e):c.attr.value+=e},chars:function(e,t){(c.textContentOnly||s).add(e)},special:function(e,t){var n=m.splitModeFromExpression(e,c),r=n.mode,a=n.expression;if("else"!==a){if("!"!==r)if(c.node&&c.node.section)u(c.node.section,r,a,t),0===c.node.section.subSectionDepth()&&(c.node.attributes.push(c.node.section.compile(f())),delete c.node.section);else if(c.attr)c.attr.section||(c.attr.section=new g(i),c.attr.value&&c.attr.section.add(c.attr.value)),u(c.attr.section,r,a,t);else if(c.node)if(c.node.attributes||(c.node.attributes=[]),r){if("#"!==r&&"^"!==r)throw new Error(r+" is currently not supported within a tag.");c.node.section||(c.node.section=new g(i)),u(c.node.section,r,a,t)}else c.node.attributes.push(m.makeLiveBindingBranchRenderer(null,a,f({filename:s.filename,lineNo:t})));else u(c.textContentOnly||s,r,a,t)}else(c.attr&&c.attr.section?c.attr.section:c.node&&c.node.section?c.node.section:c.textContentOnly||s).inverse()},comment:function(e){s.add({comment:e})},done:function(e){}});var p=s.compile(),h=E.ignore(function(e,t,n){void 0===n&&_.isListLike(t)&&(n=t,t=void 0),!t||t.helpers||t.partials||t.tags||(t={helpers:t}),_.eachKey(t&&t.helpers,function(e){e.requiresOptionsArgument=!0});var r=new O(t);if(_.eachKey(o,function(e,t){_.setKeyValue(r.partials,t,e)}),_.setKeyValue(r,"view",h),e instanceof k){var a=new k(r);a._parent=e._parent,e._parent=a}else e=new k(r).add(e);return p(e.addLetContext(),n)});return h[L]=!0,h}x(p,i),p.safeString=function(e){return _.assignSymbols({},{"can.toDOM":function(){return e}})},p.async=function(e){var t=o(e),n=t.imports.map(function(e){return l(e)});return Promise.all(n).then(function(){return p(t.intermediate)})};var h={};p.from=m.getTemplateById=function(e){if(!h[e]){var t=u().getElementById(e);t&&(h[e]=p("#"+e,t.innerHTML))}return h[e]},p.registerPartial=function(e,t){h[e]="string"==typeof t?p(t):t},p.addBindings=v.attrs,r.exports=c.stache=p}(0,e,0,n)}),define("can-view-model",["require","exports","module","can-simple-map","can-namespace","can-globals/document/document","can-reflect","can-symbol"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-simple-map"),i=t("can-namespace"),o=t("can-globals/document/document"),s=t("can-reflect"),c=t("can-symbol").for("can.viewModel");r.exports=i.viewModel=function(e,t,n){if("string"==typeof e?e=o().querySelector(e):s.isListLike(e)&&!e.nodeType&&(e=e[0]),s.isObservableLike(t)&&s.isMapLike(t))e[c]=t;else{var r=e[c];switch(r||(r=new a,e[c]=r),arguments.length){case 0:case 1:return r;case 2:return s.getKeyValue(r,t);default:return s.setKeyValue(r,t,n),e}}}}(0,e,0,n)}),define("can-attribute-observable/event",["require","exports","module","can-reflect","can-dom-events","can-dom-events/helpers/util"],function(e,t,n){"use strict";var r=e("can-reflect"),a=e("can-dom-events"),i=e("can-dom-events/helpers/util").isDomEventTarget,o={on:function(e,t,n){i(this)?a.addEventListener(this,e,t,n):r.onKeyValue(this,e,t,n)},off:function(e,t,n){i(this)?a.removeEventListener(this,e,t,n):r.offKeyValue(this,e,t,n)},one:function(e,t,n){var r=function(){return o.off.call(this,e,r,n),t.apply(this,arguments)};return o.on.call(this,e,r,n),this}};n.exports=o}),define("can-attribute-observable/get-event-name",["require","exports","module","can-attribute-observable/behaviors"],function(e,t,n){"use strict";var a=e("can-attribute-observable/behaviors");n.exports=function(e,t){var n,r="change";return"input"===(n=e).nodeName.toLowerCase()&&"radio"===n.type&&"checked"===t&&(r="can-attribute-observable-radiochange"),a.findSpecialListener(t)&&(r=t),r}}),define("can-event-dom-radiochange",["require","exports","module","can-globals/document/document","can-namespace"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-globals/document/document"),i=t("can-namespace");function u(){return a().documentElement}function l(e){for(;e&&"FORM"!==e.nodeName;)e=e.parentNode;return e}function f(e){return"INPUT"===e.nodeName&&"radio"===e.type}var d={defaultEventType:"radiochange",addEventListener:function(e,t,n){if(!f(e))throw new Error("Listeners for "+t+" must be radio inputs");var o,r,a,i,s=d._eventTypeTrackedRadios;s||(s=d._eventTypeTrackedRadios={},d._rootListener||(d._rootListener=(o=this,r=s,a=u(),i=function(e){var a=e.target;if(f(a))for(var t in r){var i={type:t};r[t].forEach(function(e){var t,n,r;n=e,(r=(t=a).getAttribute("name"))&&r===n.getAttribute("name")&&l(t)===l(n)&&o.dispatch(e,i,!1)})}},o.addEventListener(a,"change",i),i)));var c=d._eventTypeTrackedRadios[t];c||(c=d._eventTypeTrackedRadios[t]=new Set),c.add(e),e.addEventListener(t,n)},removeEventListener:function(e,t,n){e.removeEventListener(t,n);var r=d._eventTypeTrackedRadios;if(r){var a,i,o,s=r[t];if(s)if(s.delete(e),0===s.size){for(var c in delete r[t],r)if(r.hasOwnProperty(c))return;delete d._eventTypeTrackedRadios,a=this,i=d._rootListener,o=u(),a.removeEventListener(o,"change",i),delete d._rootListener}}}};r.exports=i.domEventRadioChange=d}(0,e,0,n)}),define("can-attribute-observable",["require","exports","module","can-queues","can-attribute-observable/event","can-reflect","can-observation","can-attribute-observable/behaviors","can-attribute-observable/get-event-name","can-reflect-dependencies","can-observation-recorder","can-simple-observable/settable/settable","can-assign","can-symbol","can-dom-events","can-event-dom-radiochange"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-queues"),i=t("can-attribute-observable/event"),o=t("can-reflect"),s=t("can-observation"),c=t("can-attribute-observable/behaviors"),u=t("can-attribute-observable/get-event-name"),l=(t("can-reflect-dependencies"),t("can-observation-recorder")),f=t("can-simple-observable/settable/settable"),d=t("can-assign"),p=t("can-symbol"),h=p.for("can.onValue"),v=p.for("can.offValue"),y=p.for("can.onEmit"),g=p.for("can.offEmit"),m=t("can-dom-events"),b=t("can-event-dom-radiochange"),w="can-attribute-observable-radiochange";m.addEvent(b,w);var x=function(e,t){return"select"===e.nodeName.toLowerCase()&&"value"===t&&e.multiple},_=Array.prototype.slice;function k(){var e=_.call(arguments,0);return e.unshift(this),m.addEventListener.apply(null,e)}function O(){var e=_.call(arguments,0);return e.unshift(this),m.removeEventListener.apply(null,e)}function E(e,t,n,r){"string"==typeof n&&(r=n,n=void 0),this.el=e,this.bound=!1,this.prop=x(e,t)?"values":t,this.event=r||u(e,t),this.handler=this.handler.bind(this),void 0!==r&&(this[h]=null,this[v]=null,this[y]=E.prototype.on,this[g]=E.prototype.off)}d(E.prototype=Object.create(f.prototype),{constructor:E,get:function(){l.isRecording()&&(l.add(this),this.bound||s.temporarilyBind(this));var e=c.get(this.el,this.prop);return"function"==typeof e&&(e=e.bind(this.el)),e},set:function(e){return c.setAttrOrProp(this.el,this.prop,e)||(this._value=e),e},handler:function(e,t){var n=this._value,r=[];this._value=c.get(this.el,this.prop),void 0===t&&this._value===n||(r=[this.handlers.getNode([]),this,[e,n]],a.enqueueByQueue.apply(a,r))},onBound:function(){var t=this;t.bound=!0,t._handler=function(e){t.handler(c.get(t.el,t.prop),e)},t.event===w&&i.on.call(t.el,"change",t._handler);var e=c.findSpecialListener(t.prop);e&&(t._specialDisposal=e.call(t.el,t.prop,t._handler,k)),i.on.call(t.el,t.event,t._handler),this._value=c.get(this.el,this.prop)},onUnbound:function(){var e=this;e.bound=!1,e.event===w&&i.off.call(e.el,"change",e._handler),e._specialDisposal&&(e._specialDisposal.call(e.el,O),e._specialDisposal=null),i.off.call(e.el,e.event,e._handler)},valueHasDependencies:function(){return!0},getValueDependencies:function(){var e=new Map,t=new Set;return t.add(this.prop),e.set(this.el,t),{keyDependencies:e}}}),o.assignSymbols(E.prototype,{"can.isMapLike":!1,"can.getValue":E.prototype.get,"can.setValue":E.prototype.set,"can.onValue":E.prototype.on,"can.offValue":E.prototype.off,"can.valueHasDependencies":E.prototype.hasDependencies,"can.getValueDependencies":E.prototype.getValueDependencies}),r.exports=E}(0,e,0,n)}),define("can-stache-bindings",["require","exports","module","can-bind","can-stache/src/expression","can-view-callbacks","can-view-model","can-stache-key","can-observation-recorder","can-simple-observable","can-assign","can-log/dev/dev","can-dom-mutate","can-dom-data-state","can-symbol","can-reflect","can-reflect-dependencies","can-attribute-encoder","can-queues","can-simple-observable/setter/setter","can-attribute-observable","can-view-scope/make-compute-like","can-view-nodelist","can-event-queue/map/map"],function(e,t,n){"use strict";var l=e("can-bind"),y=e("can-stache/src/expression"),r=e("can-view-callbacks"),g=e("can-view-model"),f=e("can-stache-key"),u=e("can-observation-recorder"),d=e("can-simple-observable"),m=e("can-assign"),b=(e("can-log/dev/dev"),e("can-dom-mutate")),p=e("can-dom-data-state"),c=e("can-symbol"),w=e("can-reflect"),h=e("can-reflect-dependencies"),x=e("can-attribute-encoder"),_=e("can-queues"),v=e("can-simple-observable/setter/setter"),k=e("can-attribute-observable"),O=e("can-view-scope/make-compute-like"),E=e("can-view-nodelist"),L=e("can-event-queue/map/map"),a=new Map,q="viewModel",S=function(){throw new Error("can-stache-bindings - you can not have contextual bindings ( this:from='value' ) and key bindings ( prop:from='value' ) on one element.")},M=c.for("can.onKeyValue"),i={viewModel:function(i,o,e,t,n){var s,a=[],c={},u={},l=m({},t),f={isSettingOnViewModel:!1,isSettingViewModel:!1,initialViewModelData:t||{}},d=!1;if(w.eachListLike(i.attributes||[],function(e){var t=T(e,i,{templateType:o.templateType,scope:o.scope,getViewModel:function(){return s},attributeViewModelBindings:l,alreadyUpdatedChild:!0,nodeList:o.parentNodeList,favorViewModel:!0});if(t){var n=t.bindingInfo;if(f=function(e,t){var n=t.parentToChild&&t.child===q;if(!n)return e;var r=t.childName;if(!n||"this"!==r&&"."!==r){if(!e.isSettingViewModel)return{isSettingOnViewModel:!0,initialViewModelData:e.initialViewModelData};S()}else{if(!e.isSettingViewModel&&!e.isSettingOnViewModel)return{isSettingViewModel:!0,initialViewModelData:void 0};S()}}(f,n),d=!0,n.parentToChild){var r=n.stickyParentToChild?O(t.parent):t.canBinding.parentValue;void 0!==r&&(f.isSettingViewModel?f.initialViewModelData=r:f.initialViewModelData[A(n.childName,o.scope)]=r)}a.push(t.canBinding.start.bind(t.canBinding)),c[e.name]=t.canBinding.stop.bind(t.canBinding)}}),!n||d){s=e(f.initialViewModelData,d,f);for(var r=0,p=a.length;r<p;r++)a[r]();var h;return f.isSettingViewModel||(h=b.onNodeAttributeChange(i,function(e){var t=e.attributeName,n=i.getAttribute(t);c[t]&&c[t]();var r=u[t]&&"attribute"===u[t].parent;if(null!==n||r){var a=T({name:t,value:n},i,{templateType:o.templateType,scope:o.scope,getViewModel:function(){return s},attributeViewModelBindings:l,initializeValues:!0,nodeList:o.parentNodeList});a&&(a.canBinding.start(),u[t]=a.bindingInfo,c[t]=a.canBinding.stop.bind(a.canBinding))}})),function(){for(var e in h&&(h(),h=void 0),c)c[e]()}}},data:function(a,i){if(!p.get.call(a,"preventDataBindings")){var e,o,t,n,s=u.ignore(function(){return e||(e=g(a))}),r=T({name:i.attributeName,value:a.getAttribute(i.attributeName),nodeList:i.nodeList},a,{templateType:i.templateType,scope:i.scope,getViewModel:s,syncChildWithParent:!1});r.canBinding.start();var c=function(){o&&(o(),o=void 0),n&&(n(),n=void 0),t&&(t(),t=void 0)};i.nodeList&&E.register([],c,i.nodeList,!1),o=r.canBinding.stop.bind(r.canBinding),t=b.onNodeAttributeChange(a,function(e){var t=e.attributeName,n=a.getAttribute(t);if(t===i.attributeName&&(o&&o(),null!==n)){var r=T({name:t,value:n},a,{templateType:i.templateType,scope:i.scope,getViewModel:s,initializeValues:!0,nodeList:i.nodeList,syncChildWithParent:!1});r&&(r.canBinding.start(),o=r.canBinding.stop.bind(r.canBinding)),o=r.onTeardown}}),n=b.onNodeRemoval(a,function(){var e=a.ownerDocument,t=e.contains?e:e.documentElement;t&&!1!==t.contains(a)||c()})}},event:function(d,p){var e,h,v=x.decode(p.attributeName);if(-1!==v.indexOf(":to:")||-1!==v.indexOf(":from:")||-1!==v.indexOf(":bind:"))return this.data(d,p);if(!C.call(v,"on:"))throw new Error("can-stache-bindings - unsupported event bindings "+v);e=v.substr("on:".length);var t=d[c.for("can.viewModel")],n=p.scope;if(C.call(e,"el:"))e=e.substr("el:".length),h=d;else{C.call(e,"vm:")?(e=e.substr("vm:".length),n=h=t):h=t||d;var r=e.indexOf(":by:");0<=r&&(h=n.get(e.substr(r+":by:".length)),e=e.substr(0,r))}var a,i,o=function(e){var t=d.getAttribute(x.encode(v));if(t){var n,r,a,i=g(d),o=y.parse(t,{lookupRule:function(){return y.Lookup},methodRule:"call"}),s=(n=arguments,r=p,a={element:d,event:e,viewModel:i,arguments:void 0!==h[M]?Array.prototype.slice.call(n,1):n,args:n},r.scope.add(a,{special:!0}));if(o instanceof y.Hashes){var c=o.hashExprs,u=Object.keys(c)[0],l=o.hashExprs[u].value(s),f=w.isObservableLike(l)&&w.isValueLike(l);s.set(u,f?w.getValue(l):l)}else{if(!(o instanceof y.Call))throw new Error("can-stache-bindings: Event bindings must be a call expression. Make sure you have a () in "+p.attributeName+"="+JSON.stringify(t));!function(t,e,n,r,a,i,o){_.batch.start();var s;s=[function(){var e=a.value(r,{doNotWrapInObservation:!0});return"function"==typeof(e=w.isValueLike(e)?w.getValue(e):e)?e(t):e},null,null,{}],_.mutateQueue.enqueue.apply(_.mutateQueue,s),_.batch.stop()}(d,0,0,s,o)}}},s=function(){L.off.call(h,e,o),a&&(a(),a=void 0),i&&(i(),i=void 0)};L.on.call(h,e,o),a=b.onNodeAttributeChange(d,function(e){var t=e.attributeName===v,n=!d.getAttribute(v);t&&n&&s()}),i=b.onNodeRemoval(d,function(){var e=d.ownerDocument,t=e.contains?e:e.documentElement;t&&t.contains(d)||s()})}};a.set(/[\w\.:]+:to$/,i.data),a.set(/[\w\.:]+:from$/,i.data),a.set(/[\w\.:]+:bind$/,i.data),a.set(/[\w\.:]+:raw$/,i.data),a.set(/[\w\.:]+:to:on:[\w\.:]+/,i.data),a.set(/[\w\.:]+:from:on:[\w\.:]+/,i.data),a.set(/[\w\.:]+:bind:on:[\w\.:]+/,i.data),a.set(/on:[\w\.:]+/,i.event);var P={viewModelOrAttribute:function(e,t,n,r,a,i,o){return e[c.for("can.viewModel")]?this.viewModel.apply(this,arguments):this.attribute.apply(this,arguments)},scope:function(e,a,r,t,n,i){if(r){if(n||0<=r.indexOf("(")||0<=r.indexOf("=")){var o=y.parse(r,{baseMethodType:"Call"});return o instanceof y.Hashes?new d(function(){var e=o.hashExprs,t=Object.keys(e)[0],n=o.hashExprs[t].value(a),r=w.isObservableLike(n)&&w.isValueLike(n);a.set(t,r?w.getValue(n):n)}):o.value(a)}var s={};w.assignSymbols(s,{"can.getValue":function(){},"can.valueHasDependencies":function(){return!1},"can.setValue":function(e){var t=y.parse(A(r,a),{baseMethodType:"Call"}).value(a);w.setValue(t,e)},"can.getWhatIChange":function(){var e=a.getDataForScopeSet(A(r,a)),t=new Map,n=new Set;return n.add(e.key),t.set(e.parent,n),{mutate:{keyDependencies:t}}},"can.getName":function(){}});var c=a.getDataForScopeSet(A(r,a));return c.parent&&c.key&&h.addMutatedBy(c.parent,c.key,s),s}return new d},viewModel:function(e,t,n,r,a,i,o){var s=A(n,t),c="."===n||"this"===n,u=c?[]:f.reads(n);return new v(function(){var e=r.getViewModel();return f.read(e,u,{}).value},function(e){var t=r.getViewModel();if(i){var n=w.getKeyValue(t,s);w.isObservableLike(n)?w.setValue(n,e):w.setKeyValue(t,s,new d(w.getValue(i)))}else c?w.setValue(t,e):w.setKeyValue(t,s,e)})},attribute:function(e,t,n,r,a,i,o,s){return"this"===n?w.assignSymbols({},{"can.getValue":function(){return e},"can.valueHasDependencies":function(){return!1},"can.getName":function(){}}):new k(e,n,{},o)}},C=String.prototype.startsWith||function(e){return 0===this.indexOf(e)};var V={to:{childToParent:!0,parentToChild:!1,syncChildWithParent:!1},from:{childToParent:!1,parentToChild:!0,syncChildWithParent:!1},bind:{childToParent:!0,parentToChild:!0,syncChildWithParent:!0},raw:{childToParent:!1,parentToChild:!0,syncChildWithParent:!1}},j=[],D={vm:!0,on:!0};w.each(V,function(e,t){j.push(t),D[t]=!0});var I=function(e,t,n,r,a){var i,o,s,c,u,l,f,d=x.decode(e.name),p=e.value||"",h=(c=d.split(":"),u={tokens:[],special:{}},c.forEach(function(e){D[e]?u.special[e]=u.tokens.push(e)-1:u.tokens.push(e)}),u);if(j.forEach(function(e){if(void 0!==h.special[e]&&0<h.special[e])return o=e,s=h.special[e],!1}),o){var v=function(e){if(void 0!==e.special.on)return e.tokens[e.special.on+1]}(h),y=!v||"bind"===o;return i=m({parent:"scope",child:(l=h.tokens,f=a,0<=l.indexOf("vm")?q:0<=l.indexOf("el")?"attribute":f?q:"viewModelOrAttribute"),childName:h.tokens[s-1],childEvent:v,bindingAttributeName:d,parentName:h.special.raw?'"'+p+'"':p,initializeValues:y},V[o]),"~"===p.trim().charAt(0)&&(i.stickyParentToChild=!0),i}},T=function(e,t,n){var r=I(e,n.attributeViewModelBindings,n.templateType,t.nodeName.toLowerCase(),n.favorViewModel);if(r){var a=P[r.parent](t,n.scope,r.parentName,n,r.parentToChild,void 0,void 0,r),i=P[r.child](t,n.scope,r.childName,n,r.childToParent,r.stickyParentToChild&&a,r.childEvent,r),o=!!r.childToParent,s=!!r.parentToChild,c={child:i,childToParent:o,cycles:!0===o&&!0===s?0:100,onInitDoNotUpdateChild:n.alreadyUpdatedChild||!1===r.initializeValues,onInitDoNotUpdateParent:!1===r.initializeValues,onInitSetUndefinedParentIfChildIsDefined:!0,parent:a,parentToChild:s,priority:n.nodeList?n.nodeList.nesting+1:void 0,queue:"domUI",sticky:r.syncChildWithParent?"childSticksToParent":void 0},u=new l(c);return u.startParent(),{bindingInfo:r,canBinding:u,parent:a}}},A=function(e,t){return e.replace(/@/g,"")},o={behaviors:i,getBindingInfo:I,bindings:a};o[c.for("can.callbackMap")]=a,r.attrs(o),n.exports=o}),define("can-component",["require","exports","module","can-component/control/control","can-namespace","can-bind","can-construct","can-stache","can-stache-bindings","can-view-scope","can-view-callbacks","can-view-nodelist","can-reflect","can-stache-key","can-simple-observable/setter/setter","can-simple-observable","can-simple-map","can-define/map/map","can-log","can-log/dev/dev","can-assign","can-observation-recorder","can-view-model","can-define/list/list","can-dom-data-state","can-child-nodes","can-string","can-dom-events","can-dom-mutate","can-dom-mutate/node","can-symbol","can-globals/document/document"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-component/control/control"),i=t("can-namespace"),_=t("can-bind"),o=t("can-construct"),k=t("can-stache"),O=t("can-stache-bindings"),E=t("can-view-scope"),s=t("can-view-callbacks"),L=t("can-view-nodelist"),q=t("can-reflect"),S=t("can-stache-key"),M=t("can-simple-observable/setter/setter"),c=t("can-simple-observable"),P=t("can-simple-map"),u=t("can-define/map/map"),l=t("can-log"),f=(t("can-log/dev/dev"),t("can-assign")),C=t("can-observation-recorder");t("can-view-model"),t("can-define/list/list");var V=t("can-dom-data-state"),j=t("can-child-nodes"),d=t("can-string"),D=t("can-dom-events"),I=t("can-dom-mutate"),T=t("can-dom-mutate/node"),p=t("can-symbol"),A=t("can-globals/document/document"),N=p("can.createdByCanComponent"),K=p.for("can.getValue"),R=p.for("can.setValue"),h=p.for("can.viewInsert"),B=p.for("can.viewModel");function v(e,t,n){var r;V.set.call(e,"preventDataBindings",!0);var a=O.behaviors.viewModel(e,n,function(e,t,n){return r=n&&!0===n.isSettingOnViewModel?new P(e):new c(e)},void 0,!0);return a?f(f({},t),{teardown:a,scope:t.scope.add(r)}):t}function H(l,f,e,d,p){var h=e.options;return function e(t,n){var r=p(t)||n.subtemplate,a=r!==n.subtemplate;if(r){var i;delete h.tags[l],i=a?d.toLightContent?v(t,{scope:n.scope.cloneFromRef(),options:n.options},n):v(t,f,n):v(t,n,n);var o=L.register([t],function(){i.teardown&&i.teardown()},n.parentNodeList||!0,n.directlyNested);o.expression="<can-slot name='"+t.getAttribute("name")+"'/>";var s=r(i.scope,i.options,o),c=q.toArray(j(s)),u=L.update(o,c);L.replace(u,s),h.tags[l]=e}}}k.addBindings(O);var y=o.extend({setup:function(){if(o.setup.apply(this,arguments),y){var n=this;void 0!==this.prototype.events&&0!==q.size(this.prototype.events)&&(this.Control=a.extend(this.prototype.events));var e=this.prototype.viewModel||this.prototype.scope;if(e&&this.prototype.ViewModel)throw new Error("Cannot provide both a ViewModel and a viewModel property");var t=d.capitalize(d.camelize(this.prototype.tag))+"VM";if(this.prototype.ViewModel?"function"==typeof this.prototype.ViewModel?this.ViewModel=this.prototype.ViewModel:this.ViewModel=u.extend(t,{},this.prototype.ViewModel):e?"function"==typeof e?q.isObservableLike(e.prototype)&&q.isMapLike(e.prototype)?this.ViewModel=e:this.viewModelHandler=e:q.isObservableLike(e)&&q.isMapLike(e)?this.viewModelInstance=e:(l.warn("can-component: "+this.prototype.tag+" is extending the viewModel into a can-simple-map"),this.ViewModel=P.extend(t,{},e)):this.ViewModel=P.extend(t,{},{}),this.prototype.template&&(this.renderer=this.prototype.template),this.prototype.view&&(this.renderer=this.prototype.view),"string"==typeof this.renderer){var r=d.capitalize(d.camelize(this.prototype.tag))+"View";this.renderer=k(r,this.renderer)}s.tag(this.prototype.tag,function(e,t){void 0===e[N]&&new n(e,t)})}}},{setup:function(i,o){this._initialArgs=[i,o];var s=this,n={helpers:{},tags:{}};void 0===o&&(void 0===i?o={}:(o=i,i=void 0)),void 0===i&&((i=A().createElement(this.tag))[N]=!0),this.element=i;var e=o.content;void 0!==e&&("function"==typeof e?o.subtemplate=e:"string"==typeof e&&(o.subtemplate=k(e)));var t=o.scope;void 0!==t&&t instanceof E==!1&&(o.scope=new E(t));var r=o.templates;void 0!==r&&q.eachKey(r,function(e,t){if("string"==typeof e){var n=t+" template";r[t]=k(n,e)}});var c,a,u,l,f,d=[],p=function(){for(var e=0,t=d.length;e<t;e++)d[e]()};V.get.call(i,"preventDataBindings")?c=i[B]:(l=o.setupBindings?o.setupBindings:o.viewModel?(f=o.viewModel,C.ignore(function(e,t,s){var c,u=[],l=[];q.eachKey(f,function(e,t){var n=null!=e&&!!e[K],r=null!=e&&!!e[R];if(!0===n||r){var a=S.reads(t),i=new M(function(){return S.read(c,a).value},function(e){q.setKeyValue(c,t,e)}),o=new _({child:i,parent:e,queue:"domUI"});o.startParent(),!0===n&&(s[t]=o.parentValue),u.push(o.start.bind(o)),l.push(o.stop.bind(o))}else s[t]=e}),c=t(s);for(var n=0,r=u.length;n<r;n++)u[n]();return function(){l.forEach(function(e){e()})}})):function(e,t,n){return O.behaviors.viewModel(e,o,t,n)},u=l(i,function(e){var t=s.constructor.ViewModel,n=s.constructor.viewModelHandler,r=s.constructor.viewModelInstance;if(n){var a=n.call(s,e,o.scope,i);q.isObservableLike(a)&&q.isMapLike(a)?r=a:t=q.isObservableLike(a.prototype)&&q.isMapLike(a.prototype)?a:P.extend(a)}return t&&(r=new s.constructor.ViewModel(e)),c=r},{}));if(this.viewModel=c,i[B]=c,i.viewModel=c,V.set.call(i,"preventDataBindings",!0),void 0!==this.helpers&&q.eachKey(this.helpers,function(e,t){"function"==typeof e&&(n.helpers[t]=e.bind(c))}),this.constructor.Control)this._control=new this.constructor.Control(i,{scope:this.viewModel,viewModel:this.viewModel,destroy:p});else var h=I.onNodeRemoval(i,function(){var e=i.ownerDocument,t=e.contains?e:e.documentElement;t&&t.contains(i)||(h(),p())});var v,y,g,m,b={toLightContent:!0===this.leakScope,intoShadowContent:!0===this.leakScope};!this.constructor.renderer?(y={scope:o.scope.add(this.viewModel,{viewModel:!0}),options:n},v=o.subtemplate||i.ownerDocument.createDocumentFragment.bind(i.ownerDocument)):(g=b.intoShadowContent?{scope:o.scope.add(this.viewModel,{viewModel:!0}),options:n}:{scope:new E(this.viewModel,null,{viewModel:!0}),options:n},n.tags["can-slot"]=H("can-slot",o,g,b,function(e){var t=o.templates;if(t)return t[e.getAttribute("name")]}),n.tags.content=H("content",o,g,b,function(){return o.subtemplate}),v=this.constructor.renderer,y=g);var w=L.register([],function(){s._torndown=!0,D.dispatch(i,"beforeremove",!1),u&&u(),m?m(i):"function"==typeof c.stopListening&&c.stopListening()},o.parentNodeList||!0,!1);if(w.expression="<"+this.tag+">",d.push(function(){L.unregister(w)}),this.nodeList=w,a=v(y.scope,y.options,w),T.appendChild.call(i,a),L.update(w,j(i)),c&&c.connectedCallback)if(A().body.contains(i))m=c.connectedCallback(i);else var x=I.onNodeInsertion(i,function(){x(),m=c.connectedCallback(i)});s._torndown=!1}});y.prototype[h]=function(e){return this._torndown&&this.setup.apply(this,this._initialArgs),e.nodeList.newDeepChildren.push(this.nodeList),this.element},r.exports=i.Component=y}(0,e,0,n)}),define("can/es/can-component",["exports","can-component"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-stache",["exports","can-stache"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-stache-bindings",["exports","can-stache-bindings"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-simple-observable/make-compute/make-compute",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var i=e("can-reflect"),o=new WeakMap;n.exports=function(r){var a=function(e){return arguments.length?i.setValue(this,e):i.getValue(this)}.bind(r);return a.on=a.bind=a.addEventListener=function(e,n){var t=o.get(n);t||(t=function(e,t){n.call(a,{type:"change"},e,t)},o.set(n,t)),i.onValue(r,t)},a.off=a.unbind=a.removeEventListener=function(e,t){i.offValue(r,o.get(t))},i.assignSymbols(a,{"can.getValue":function(){return i.getValue(r)},"can.setValue":function(e){return i.setValue(r,e)},"can.onValue":function(e,t){return i.onValue(r,e,t)},"can.offValue":function(e,t){return i.offValue(r,e,t)},"can.valueHasDependencies":function(){return i.valueHasDependencies(r)},"can.getPriority":function(){return i.getPriority(r)},"can.setPriority":function(e){i.setPriority(r,e)},"can.isValueLike":!0,"can.isFunctionLike":!1}),a.isComputed=!0,a}}),define("can-route/src/string-coercion",["require","exports","module","can-reflect","can-symbol"],function(e,t,n){var a=e("can-reflect"),i=e("can-symbol"),o=function(n){return n&&"object"==typeof n?(n=n&&"object"==typeof n&&"serialize"in n?n.serialize():"function"==typeof n.slice?n.slice():a.assign({},n),a.eachKey(n,function(e,t){n[t]=o(e)})):null!=n&&"function"==typeof n.toString&&(n=n.toString()),n};t.stringCoercingMapDecorator=function(e){var t=i.for("can.route.stringCoercingMapDecorator");if(!e.attr[t]){var r=e.attr;e.attr=function(e,t){var n;return n="string"!=typeof e||void 0!==this.define&&void 0!==this.define[e]&&!this.define[e].serialize?arguments:o(Array.apply(null,arguments)),r.apply(this,n)},a.setKeyValue(e.attr,t,!0)}return e},t.stringify=o}),define("can-route/src/routedata",["require","exports","module","can-define/map/map","can-route/src/string-coercion"],function(e,t,n){var r=e("can-define/map/map"),a=e("can-route/src/string-coercion").stringify;n.exports=r.extend("RouteData",{seal:!1},{"*":{type:a}})}),define("can-route/src/binding-proxy",["require","exports","module","can-reflect","can-symbol","can-simple-observable"],function(e,t,n){"use strict";var a=e("can-reflect"),i=e("can-symbol"),o=new(e("can-simple-observable"))(null);a.setName(o,"route.urlData");var r={defaultBinding:null,urlDataObservable:o,bindings:{},call:function(){var e=a.toArray(arguments),t=e.shift(),n=o.value;if(null===n)throw new Error("there is no current binding!!!");var r=n[0===t.indexOf("can.")?i.for(t):t];return r.apply?r.apply(n,e):r}};n.exports=r}),define("can-route/src/regexps",function(e,t,n){"use strict";n.exports={curlies:/\{\s*([\w.]+)\s*\}/g,colon:/\:([\w.]+)/g}}),define("can-diff/map/map",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var o=e("can-reflect");n.exports=function(n,r){var a,i=[];for(var e in a=o.assignMap({},n),o.eachKey(r,function(e,t){n&&n.hasOwnProperty(t)?r[t]!==n[t]&&i.push({key:t,type:"set",value:e}):i.push({key:t,type:"add",value:e}),delete a[t]}),a)i.push({key:e,type:"delete"});return i}}),define("can-route/src/register",["require","exports","module","can-reflect","can-log/dev/dev","can-route/src/binding-proxy","can-route/src/regexps","can-diff/list/list","can-diff/map/map","can-route/src/routedata"],function(e,t,n){"use strict";var d=e("can-reflect"),p=(e("can-log/dev/dev"),e("can-route/src/binding-proxy")),h=e("can-route/src/regexps"),v=(e("can-diff/list/list"),e("can-diff/map/map"),e("can-route/src/routedata")),y=function(e){return e.replace(/\\/g,"")},g={routes:{},register:function(e,r){var t=p.call("root");t.lastIndexOf("/")===t.length-1&&0===e.indexOf("/")&&(e=e.substr(1)),r=r||{};var n,a,i,o,s=[],c="",u=p.call("querySeparator"),l=p.call("matchSlashes");for(i=(a=h.colon.test(e)?h.colon:h.curlies).lastIndex=0;n=a.exec(e);)s.push(n[1]),c+=y(e.substring(i,a.lastIndex-n[0].length)),c+="([^"+("\\"+(y(e.substr(a.lastIndex,1))||u+(l?"":"|/")))+"]"+(r[n[1]]?"*":"+")+")",i=a.lastIndex;if(c+=e.substr(i).replace("\\",""),this.data instanceof v){var f=this.data;d.eachIndex(s,function(e){var t="string",n=r[e];null!=n&&(t=typeof n),d.defineInstanceKey(f.constructor,e,{type:t})})}return g.routes[e]={test:new RegExp("^"+c+"($|"+(o=u,(o+"").replace(/([.?*+\^$\[\]\\(){}|\-])/g,"\\$1"))+")"),route:e,names:s,defaults:r,length:e.split("/").length}}};n.exports=g}),define("can-deparam",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace"),a=/^\d+$/,p=/([^\[\]]+)|(\[\])/g,i=/([^?#]*)(#.*)?$/,o=/%([^0-9a-f][0-9a-f]|[0-9a-f][^0-9a-f]|[^0-9a-f][^0-9a-f])/i,h=function(t){t=t.replace(/\+/g," ");try{return decodeURIComponent(t)}catch(e){return decodeURIComponent(t.replace(o,function(e,t){return"%25"+t}))}};function v(e){return a.test(e)||"[]"===e}function s(e){return e}n.exports=r.deparam=function(e,l){l=l||s;var f,d={};return e&&i.test(e)&&e.split("&").forEach(function(e){var t=e.split("="),n=h(t.shift()),r=h(t.join("=")),a=d;if(n){for(var i=0,o=(t=n.match(p)).length-1;i<o;i++){var s=t[i],c=t[i+1],u=v(s)&&a instanceof Array;a[s]||(u?a.push(v(c)?[]:{}):a[s]=v(c)?[]:{}),a=u?a[a.length-1]:a[s]}v(f=t.pop())?a.push(l(r)):a[f]=l(r)}}),d}}),define("can-route/src/deparam",["require","exports","module","can-deparam","can-reflect","can-route/src/binding-proxy","can-route/src/register"],function(e,t,n){"use strict";var c=e("can-deparam"),u=e("can-reflect"),l=e("can-route/src/binding-proxy"),a=e("can-route/src/register");function f(e){var t=l.call("root");return t.lastIndexOf("/")===t.length-1&&0===e.indexOf("/")&&(e=e.substr(1)),e}function d(n){n=f(n);var r={length:-1};if(u.eachKey(a.routes,function(e,t){e.test.test(n)&&e.length>r.length&&(r=e)}),-1<r.length)return r}function r(e){var n=d(e),r=l.call("querySeparator"),t=l.call("paramsMatcher");if(e=f(e),n){var a=e.match(n.test),i=a.shift(),o=e.substr(i.length-(a[a.length-1]===r?1:0)),s=o&&t.test(o)?c(o.slice(1)):{};return s=u.assignDeep(u.assignDeep({},n.defaults),s),a.forEach(function(e,t){e&&e!==r&&(s[n.names[t]]=function(t){try{return decodeURIComponent(t)}catch(e){return unescape(t)}}(e))}),s}return e.charAt(0)!==r&&(e=r+e),t.test(e)?c(e.slice(1)):{}}r.getRule=d,n.exports=r}),define("can-param",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace");function s(e,t,n){if(Array.isArray(t))for(var r=0,a=t.length;r<a;++r){var i=t[r];s(e+("object"==typeof i?"["+r+"]":"[]"),i,n)}else if(t&&"object"==typeof t)for(var o in t)s(e+"["+o+"]",t[o],n);else n(e,t)}n.exports=r.param=function(e){var n=[],t=function(e,t){n.push(encodeURIComponent(e)+"="+encodeURIComponent(t))};for(var r in e)s(r,e[r],t);return n.join("&").replace(/%20/g,"+")}}),define("can-route/src/param",["require","exports","module","can-reflect","can-param","can-route/src/register","can-route/src/regexps","can-route/src/binding-proxy"],function(e,t,n){"use strict";var s=e("can-reflect"),o=e("can-param"),c=e("can-route/src/register"),u=e("can-route/src/regexps"),l=e("can-route/src/binding-proxy"),f=function(e,t){var n=0,r=0,a={};for(var i in e.defaults)e.defaults[i]===t[i]&&(a[i]=1,n++);for(;r<e.names.length;r++){if(!t.hasOwnProperty(e.names[r]))return-1;a[e.names[r]]||n++}return n};function r(n,e){var r,a,i=0,o=0;return delete n.route,s.eachKey(n,function(){o++}),s.eachKey(c.routes,function(e,t){if(a=f(e,n),i<a&&(r=e,i=a),o<=a)return!1}),c.routes[e]&&f(c.routes[e],n)===i&&(r=c.routes[e]),r}function a(n,r){var a,e,t,i;return n?(a=s.assignMap({},r),i=u.colon.test(n.route)?u.colon:u.curlies,e=n.route.replace(i,function(e,t){return delete a[t],r[t]===n.defaults[t]?"":encodeURIComponent(r[t])}).replace("\\",""),s.eachKey(n.defaults,function(e,t){a[t]===e&&delete a[t]}),e+((t=o(a))?l.call("querySeparator")+t:"")):0===s.size(r)?"":l.call("querySeparator")+o(r)}function i(e,t){return a(r(e,t),e)}(n.exports=i).paramFromRoute=a,i.getMatchedRoute=r}),define("can-route/src/url-helpers",["require","exports","module","can-route/src/binding-proxy","can-route/src/deparam","can-route/src/param","can-reflect","can-string"],function(e,t,n){"use strict";var r=e("can-route/src/binding-proxy"),a=e("can-route/src/deparam"),i=e("can-route/src/param"),o=e("can-reflect"),s=e("can-string"),c=function(e,t){for(var n in e){var r=e[n],a=t[n];if(r&&a&&"object"==typeof r&&"object"==typeof t)return c(r,a);if(r!=a)return!1}return!0};function u(e,t){if(t){var n=a(r.call("can.getValue"));e=o.assignMap(o.assignMap({},n),e)}return r.call("root")+i(e)}n.exports={url:u,link:function(e,t,n,r){return"<a "+(a=o.assignMap({href:u(t,r)},n),i=[],o.eachKey(a,function(e,t){i.push(("className"===t?"class":t)+'="'+("href"===t?e:s.esc(e))+'"')}),i.join(" "))+">"+e+"</a>";var a,i},isCurrent:function(e,t){if(t){var n=a(r.call("can.getValue"));return c(e,n)}return r.call("can.getValue")===i(e)}}}),define("can-route-hash",["require","exports","module","can-globals/location/location","can-reflect","can-observation-recorder","can-queues","can-key-tree","can-simple-observable","can-dom-events"],function(e,t,n){!function(e,t,n,r){var a=t("can-globals/location/location"),i=t("can-reflect"),o=t("can-observation-recorder"),s=t("can-queues"),c=t("can-key-tree"),u=t("can-simple-observable"),l=t("can-dom-events");function f(){return a().href.split(/#!?/)[1]||""}function d(){var e=this.dispatchHandlers.bind(this),t=this;this._value="",this.handlers=new c([Object,Array],{onFirst:function(){t._value=f(),l.addEventListener(window,"hashchange",e)},onEmpty:function(){l.removeEventListener(window,"hashchange",e)}})}d.prototype=Object.create(u.prototype),d.constructor=d,i.assign(d.prototype,{paramsMatcher:/^(?:&[^=]+=[^&]*)+/,querySeparator:"&",matchSlashes:!1,root:"#!",dispatchHandlers:function(){var e=this._value;this._value=f(),e!==this._value&&s.enqueueByQueue(this.handlers.getNode([]),this,[this._value,e])},get:function(){return o.add(this),f()},set:function(e){var t=a();return(e||t.hash)&&t.hash!=="#"+e&&(t.hash="!"+e),e}}),Object.defineProperty(d.prototype,"value",{get:function(){return i.getValue(this)},set:function(e){i.setValue(this,e)}}),i.assignSymbols(d.prototype,{"can.getValue":d.prototype.get,"can.setValue":d.prototype.set,"can.onValue":d.prototype.on,"can.offValue":d.prototype.off,"can.isMapLike":!1,"can.valueHasDependencies":function(){return!0}}),r.exports=d}(0,e,0,n)}),define("can-globals/is-web-worker/is-web-worker",["require","exports","module","can-globals/can-globals-instance"],function(o,e,t){!function(e,t,n,r){"use strict";var a=o("can-globals/can-globals-instance"),i=Function;a.define("isWebWorker",function(){var e=i("return this")();return"undefined"!=typeof WorkerGlobalScope&&e instanceof WorkerGlobalScope}),r.exports=a.makeExport("isWebWorker")}(0,0,0,t)}),define("can-route",["require","exports","module","can-bind","can-queues","can-observation","can-namespace","can-log/dev/dev","can-reflect","can-symbol","can-simple-observable/make-compute/make-compute","can-route/src/routedata","can-route/src/string-coercion","can-route/src/register","can-route/src/url-helpers","can-route/src/param","can-route/src/deparam","can-route/src/binding-proxy","can-route-hash","can-globals/is-web-worker/is-web-worker","can-globals/is-browser-window/is-browser-window"],function(e,t,n){!function(e,t,n,r){"use strict";var a,i=t("can-bind"),o=t("can-queues"),s=t("can-observation"),c=t("can-namespace"),u=(t("can-log/dev/dev"),t("can-reflect")),l=t("can-symbol"),f=t("can-simple-observable/make-compute/make-compute"),d=t("can-route/src/routedata"),p=t("can-route/src/string-coercion").stringCoercingMapDecorator,h=t("can-route/src/register"),v=t("can-route/src/url-helpers"),y=t("can-route/src/param"),g=t("can-route/src/deparam"),m=t("can-route/src/binding-proxy"),b=t("can-route-hash"),w=t("can-globals/is-web-worker/is-web-worker"),x=t("can-globals/is-browser-window/is-browser-window"),_=new b;function k(e,t){return h.register(e,t),k}m.bindings.hashchange=_,m.defaultBinding="hashchange",m.urlDataObservable.value=_;var O=new s(function(){var e=m.call("can.getValue");return k.rule(e)});function E(e){clearTimeout(a),a=setTimeout(function(){var e=u.serialize(k.data),t=O.get(),n=y.getMatchedRoute(e,t),r=y.paramFromRoute(n,e);m.call("can.setValue",r);var a=k._onStartComplete;a&&(k._onStartComplete=void 0,a())},10)}function L(){var e=m.call("can.getValue");o.batch.start();var t=k.deparam(e);delete t.route,u.update(k.data,t),o.batch.stop()}Object.defineProperty(k,"routes",{get:function(){return h.routes},set:function(e){return h.routes=e}}),Object.defineProperty(k,"defaultBinding",{get:function(){return m.defaultBinding},set:function(e){m.defaultBinding=e;var t=m.bindings[m.defaultBinding];t&&(m.urlDataObservable.value=t)}}),Object.defineProperty(k,"urlData",{get:function(){return m.urlDataObservable.value},set:function(e){k._teardown(),m.urlDataObservable.value=e}}),u.assignMap(k,{param:y,deparam:g,map:function(e){k.data=e},start:function(e){if(!0!==e&&(k._setup(),x()||w())){var t=m.call("can.getValue");o.batch.start();var n=k.deparam(t);delete n.route,u.assign(k.data,n),o.batch.stop(),E()}return k},url:v.url,link:v.link,isCurrent:v.isCurrent,bindings:m.bindings,_setup:function(){if(!k._canBinding){var e={parent:m.urlDataObservable.value,setParent:E,child:k.serializedObservation,setChild:L,onInitDoNotUpdateChild:!0,cycles:1,queue:"notify"};(k._canBinding=new i(e)).start()}},_teardown:function(){k._canBinding&&(k._canBinding.stop(),k._canBinding=null),clearTimeout(a)},stop:function(){return this._teardown(),k},currentRule:f(O),register:h.register,rule:function(e){var t=g.getRule(e);if(t)return t.route}});var q,S=function(e,t){return k.data[e]?k.data[e].apply(k.data,t):k.data.addEventListener.apply(k.data,t)};["addEventListener","removeEventListener","bind","unbind","on","off"].forEach(function(n){k[n]=function(e,t){return"__url"===e?m.call("can.onValue",t):S(n,arguments)}}),["delegate","undelegate","removeAttr","compute","_get","___get","each"].forEach(function(e){k[e]=function(){return S(e,arguments)}});var M,P,C=function(e){return q=e};Object.defineProperty(k,"serializedObservation",{get:function(){return M||(M=new s(function(){return u.serialize(k.data)})),M}}),Object.defineProperty(k,"serializedCompute",{get:function(){return P||(P=f(k.serializedObservation)),P}});var V=l.for("can.viewModel");Object.defineProperty(k,"data",{get:function(){return q||C(new d)},set:function(e){u.isConstructorLike(e)&&(e=new e),e&&void 0!==e[V]&&(e=e[V]),C("attr"in e?p(e):e)}}),k.attr=function(e,t){return console.warn("can-route: can-route.attr is deprecated. Use methods on can-route.data instead."),"attr"in k.data?k.data.attr.apply(k.data,arguments):1<arguments.length?(u.setKeyValue(k.data,e,t),k.data):"object"==typeof e?(u.assignDeep(k.data,e),k.data):1===arguments.length?u.getKeyValue(k.data,e):u.unwrap(k.data)},u.setKeyValue(k,l.for("can.isFunctionLike"),!1),k.matched=k.currentRule,k.current=k.isCurrent,r.exports=c.route=k}(0,e,0,n)}),define("can-stache-route-helpers",["require","exports","module","can-stache/helpers/core","can-route","can-stache/src/expression","can-reflect"],function(e,t,n){"use strict";var a=e("can-stache/helpers/core"),r=e("can-route"),i=e("can-stache/src/expression"),o=e("can-reflect"),s=a.looksLikeOptions,c=function(){var t,n,r;return o.eachIndex(arguments,function(e){"boolean"==typeof e?n=e:e&&"object"==typeof e&&(s(e)?r=e:t=a.resolveHash(e))}),!t&&r&&(t=a.resolveHash(r.hash)),{finalParams:t||{},finalMerge:n,optionsArg:r}};a.registerHelper("routeUrl",function(){var e=c.apply(this,arguments);return r.url(e.finalParams,"boolean"==typeof e.finalMerge?e.finalMerge:void 0)});var u=function(){var e=c.apply(this,arguments),t=r.isCurrent(e.finalParams,"boolean"==typeof e.finalMerge?e.finalMerge:void 0);return!e.optionsArg||e.optionsArg instanceof i.Call?t:t?e.optionsArg.fn():e.optionsArg.inverse()};u.callAsMethod=!0,a.registerHelper("routeCurrent",u)}),define("can/es/can-stache-route-helpers",["exports","can-stache-route-helpers"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-view-callbacks",["exports","can-view-callbacks"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-view-live",["exports","can-view-live"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-view-model",["exports","can-view-model"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-view-nodelist",["exports","can-view-nodelist"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-view-parser",["exports","can-view-parser"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-view-scope",["exports","can-view-scope"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-view-target",["exports","can-view-target"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-key/sub/sub",["require","exports","module","can-key/utils","can-key/get/get","can-reflect","can-key/delete/delete"],function(e,t,n){"use strict";var o=e("can-key/utils"),s=e("can-key/get/get"),c=e("can-reflect"),u=e("can-key/delete/delete");n.exports=function(e,r,a){var i=[];return e=e||"",i.push(e.replace(o.strReplacer,function(e,t){var n=s(r,t);return!0===a&&u(r,t),null==n?(i=null,""):!c.isPrimitive(n)&&i?(i.push(n),""):""+n})),null===i?i:i.length<=1?i[0]:i}}),define("can-query-logic/src/set",["require","exports","module","can-symbol","can-reflect"],function(e,t,n){var p,r=e("can-symbol"),h=e("can-reflect"),a=function(e){return h.assignSymbols(e,{"can.serialize":function(){return this}})};function i(n){return function(e,t){return n.call(this,t,e)}}var s=r.for("can.setComparisons");function o(e,t,n){var r=e[s];e[s]||(r=e[s]=new Map);var a=r.get(e);a||(a=new Map,r.set(e,a));var i=a.get(t);if(i)for(var o in n)i.hasOwnProperty(o)&&console.warn("Overwriting "+e.name+" "+o+" "+t.name+" comparitor"),i[o]=n[o];else a.set(t,n)}function c(){}var u={number:c,string:c,undefined:c,boolean:c},v={};["intersection","difference","union"].forEach(function(a){v[a]=function(e,t,n){if(n===p.UNIVERSAL){if("intersection"===a)return t;if("union"===a)return p.UNIVERSAL;if("difference"===a)return p.EMPTY}if(t===p.UNIVERSAL){if("intersection"===a)return t;if("union"===a)return p.UNIVERSAL}if(e&&e[a]){var r=e[a](t,n);return void 0===r&&!0===e.undefinedIsEmptySet?p.EMPTY:r}throw new Error("Unable to perform "+a+" between "+p.getType(t).name+" and "+p.getType(n).name)}});var l={intersection:function(e,t){return e===t?e:p.EMPTY},difference:function(e,t){return e===t?p.EMPTY:e},union:function(e,t){return e===t?e:p.UNDEFINABLE}};(p={UNIVERSAL:h.assignSymbols({name:"UNIVERSAL"},{"can.serialize":function(){return this},"can.isMember":function(){return!0}}),EMPTY:h.assignSymbols({name:"EMPTY"},{"can.serialize":function(){return this},"can.isMember":function(){return!1}}),UNDEFINABLE:a({name:"UNDEFINABLE"}),UNKNOWABLE:a({name:"UNKNOWABLE"}),Identity:c,isSpecial:function(e){return e===p.UNIVERSAL||e===p.EMPTY||e===p.UNDEFINABLE||e===p.UNKNOWABLE},isDefinedAndHasMembers:function(e){return e!==p.EMPTY&&e!==p.UNDEFINABLE&&e!==p.UNKNOWABLE&&e},getType:function(e){return e===p.UNIVERSAL?p.UNIVERSAL:e===p.EMPTY?p.EMPTY:e===p.UNKNOWABLE?p.UNKNOWABLE:null===e?c:u.hasOwnProperty(typeof e)?u[typeof e]:e.constructor},ownAndMemberValue:function(e,t){if(null==e&&null==t)return{own:t,member:e};var n=null!=e?e.valueOf():e,r=null!=t?t.valueOf():t;return null==e||null==t||null!=n&&n.constructor===r.constructor||(r=new e.constructor(r).valueOf()),{own:n,member:r}},getComparisons:function(e,t){var n=e[s];if(n){var r=n.get(e);if(r)return r.get(t)}},hasComparisons:function(e){return!!e[s]},defineComparison:function(e,t,n){if(o(e,t,n),e!==t){var r={};for(var a in n)"difference"!==a&&(r[a]=i(n[a]));o(t,e,r)}},isSubset:function(e,t){if(e===t)return!0;var n=p.getType(e),r=p.getType(t),a=p.getComparisons(n,r);if(a){var i=v.intersection(a,e,t),o=v.difference(a,e,t);return i===p.UNKNOWABLE||o===p.UNKNOWABLE?void 0:i!==p.EMPTY&&o===p.EMPTY}throw new Error("Unable to perform subset comparison between "+n.name+" and "+r.name)},isProperSubset:function(e,t){return p.isSubset(e,t)&&!p.isEqual(e,t)},isEqual:function(e,t){if(e===p.UNKNOWABLE||t===p.UNKNOWABLE)return p.UNKNOWABLE;var n=p.isSpecial(e),r=p.isSpecial(t);if(n&&r)return n===r;var a=p.getType(e),i=p.getType(t);if(e===t)return!0;var o=p.getComparisons(a,i),s=p.getComparisons(i,a);if(o&&s){var c=v.intersection(o,e,t),u=v.difference(o,e,t);if(c===p.EMPTY||u!==p.EMPTY)return!1;var l=v.intersection(s,t,e),f=v.difference(s,t,e);return l!==p.EMPTY&&f===p.EMPTY}var d=p.ownAndMemberValue(e,t);if(h.isPrimitive(d.own)&&h.isPrimitive(d.member))return d.own===d.member;throw new Error("Unable to perform equal comparison between "+a.name+" and "+i.name)},union:function(e,t){if(e===p.UNIVERSAL||t===p.UNIVERSAL)return p.UNIVERSAL;if(e===p.EMPTY)return t;if(t===p.EMPTY)return e;if(e===p.UNKNOWABLE||t===p.UNKNOWABLE)return p.UNKNOWABLE;var n=p.getType(e),r=p.getType(t),a=p.getComparisons(n,r);return v.union(a,e,t)},intersection:function(e,t){if(e===p.UNIVERSAL)return t;if(t===p.UNIVERSAL)return e;if(e===p.EMPTY||t===p.EMPTY)return p.EMPTY;if(e===p.UNKNOWABLE||t===p.UNKNOWABLE)return p.UNKNOWABLE;var n=p.getType(e),r=p.getType(t),a=p.getComparisons(n,r);if(a)return v.intersection(a,e,t);throw new Error("Unable to perform intersection comparison between "+n.name+" and "+r.name)},difference:function(e,t){if(e===p.EMPTY)return p.EMPTY;if(t===p.EMPTY)return e;if(e===p.UNKNOWABLE||t===p.UNKNOWABLE)return p.UNKNOWABLE;var n=p.getType(e),r=p.getType(t),a=p.getComparisons(n,r);if(a)return v.difference(a,e,t);throw new Error("Unable to perform difference comparison between "+n.name+" and "+r.name)},indexWithEqual:function(e,t){for(var n=0,r=e.length;n<r;n++)if(p.isEqual(e[n],t))return n;return-1}}).defineComparison(c,c,l),p.defineComparison(p.UNIVERSAL,p.UNIVERSAL,l),n.exports=p}),define("can-fixture/data-from-url",function(e,t,n){var o=/\{([^\}]+)\}/g;n.exports=function(e,t){if(!e)return{};var n=[],r=e.replace(".","\\.").replace("?","\\?"),a=new RegExp(r.replace(o,function(e,t){return n.push(t),"([^/]+)"})+"$").exec(t),i={};return a?(a.shift(),n.forEach(function(e){i[e]=a.shift()}),i):null}}),define("can-query-logic/src/array-union-intersection-difference",["require","exports","module","can-query-logic/src/set"],function(e,t,n){var o=e("can-query-logic/src/set");function s(e){return null==e?e:e.valueOf()}n.exports=function(e,t){var n=new Set,r=[],a=[],i=e.slice(0);return e.forEach(function(e){n.add(s(e)),a.push(e)}),t.forEach(function(e){if(n.has(s(e))){r.push(e);var t=o.indexWithEqual(i,e);-1!==t&&i.splice(t,1)}else a.push(e)}),{intersection:r,union:a,difference:i}}}),define("can-query-logic/src/types/comparisons",["require","exports","module","can-query-logic/src/set","can-query-logic/src/array-union-intersection-difference","can-symbol"],function(e,t,n){var o=e("can-query-logic/src/set"),s=e("can-query-logic/src/array-union-intersection-difference"),r=e("can-symbol").for("can.isMember"),a={In:function(e){this.values=e},NotIn:function(e){this.values=e},GreaterThan:function(e){this.value=e},GreaterThanEqual:function(e){this.value=e},LessThan:function(e){this.value=e},LessThanEqual:function(e){this.value=e},And:function(e){this.values=e},Or:function(e){this.values=e}};function i(n){return function(e,t){return null!=e&&null!=t&&n(e,t)}}function c(n){return function(e,t){return e===t||null!=e&&null!=t&&n(e,t)}}function u(e){var t=o.ownAndMemberValue(this.value,e);return this.constructor.test(t.member,t.own)}function l(e){return this.constructor.test(this.values,e)}function f(n){return{test:function(e,t){return!n.test(e,t)}}}function d(r,a,i){return function(e,t){var n=s(e.values,t.values);return n[r].length?new a(n[r]):i||o.EMPTY}}function p(n){return function(e,t){return n(t,e)}}function h(n,r){return function(e,t){return new n(t[r||"value"])}}function v(e,t){return e.value<t.value?t:e}function y(e,t){return e.value>t.value?t:e}function g(n,r){return function(e,t){return n.test(e.value,t.value)?q([e,new r(t.value)]):o.EMPTY}}function m(e,t){var n=g(e,t);return function(e,t){return e.value===t.value?new M.In([e.value]):n(e,t)}}function b(r,a,i){return function(e,t){var n=e.values.filter(function(e){return r.test(t,e)});return n.length?new a(n):i||o.EMPTY}}a.Or.prototype.orValues=function(){return this.values},a.In.test=function(e,n){return e.some(function(e){var t=o.ownAndMemberValue(e,n);return t.own===t.member})},a.NotIn.test=function(e,t){return!a.In.test(e,t)},a.NotIn.testValue=function(e,t){return!a.In.testValue(e,t)},a.GreaterThan.test=i(function(e,t){return t<e}),a.GreaterThanEqual.test=c(function(e,t){return t<=e}),a.LessThan.test=i(function(e,t){return e<t}),a.LessThanEqual.test=c(function(e,t){return e<=t}),[a.GreaterThan,a.GreaterThanEqual,a.LessThan,a.LessThanEqual,a.LessThan].forEach(function(e){e.prototype.isMember=u}),[a.In,a.NotIn].forEach(function(e){e.prototype.isMember=l}),a.And.prototype.isMember=function(t){return this.values.every(function(e){return e.isMember(t)})},a.Or.prototype.isMember=function(t){return this.values.some(function(e){return e.isMember(t)})},Object.keys(a).forEach(function(e){a[e].prototype[r]=a[e].prototype.isMember});var w={test:function(e,t){return e.isMember(t)}};function x(e){return e instanceof M.Or}function _(e){return e instanceof M.And||x(e)}function k(a){return function(e,t){var n,r=e.values.filter(function(e){return a.values.test(t,e)});return n=a.complement?o.difference(o.UNIVERSAL,t):a.with?new a.with(t.value):t,r.length?a.combinedUsing([new a.arePut(r),n]):n}}function O(n,r){return function(e,t){return n.test(e.value,t.value)?r||o.UNIVERSAL:S([e,t])}}function E(n,r){return function(e,t){return n.test(e.value,t.value)?r||o.EMPTY:q([e,t])}}function L(n){return function(e,t){return n.test(e.value,t.value)?o.difference(o.UNIVERSAL,t):e}}function q(e){return a.And?new a.And(e):o.UNDEFINABLE}function S(e){return a.Or?new a.Or(e):o.UNDEFINABLE}var M=a;function P(e,t,n){var r=new n(t.value),a=e.values.filter(function(e){return!r.isMember(e)});return a.length?a.length<e.values.length?S([new M.In(a),r]):S([e,t]):r}var C,V,j={union:k({values:f(w),arePut:M.In,combinedUsing:function(e){return function e(t,n){if(n instanceof M.Or){var r=e(t,n.values[0]);if(!(r instanceof M.Or))return o.union(r,n.values[1]);var a=e(t,n.values[1]);return a instanceof M.Or?S([t,n]):o.union(a,n.values[0])}return n instanceof M.GreaterThan?P(t,n,M.GreaterThanEqual):n instanceof M.LessThan?P(t,n,M.LessThanEqual):S([t,n])}(e[0],e[1])}}),intersection:b(w,M.In,o.EMPTY),difference:b(f(w),M.In,o.EMPTY)},D={difference:p(k({values:w,arePut:M.NotIn,combinedUsing:q}))},I=function(){return{union:b(f(w),M.NotIn,o.UNIVERSAL),intersection:k({values:w,arePut:M.NotIn,combinedUsing:q}),difference:k({values:f(w),arePut:M.NotIn,combinedUsing:q,complement:!0})}},T={difference:p(b(w,M.In,o.EMPTY))},A=function(e,t){var n=o.union(e,t.values[0]),r=o.union(e,t.values[1]);return _(n)||_(r)?new M.Or([e,t]):o.intersection(n,r)},N=function(e,t){var n=t.values[0],r=t.values[1],a=o.intersection(e,n),i=o.intersection(e,r);return a===o.EMPTY||i===o.EMPTY?o.EMPTY:_(a)?_(i)?new M.And([e,t]):new o.intersection(i,n):new o.intersection(a,r)},K=function(e,t){var n=t.values[0],r=t.values[1],a=o.difference(e,n),i=o.difference(e,r);return a===o.EMPTY?i:i===o.EMPTY?a:new M.Or([a,i])},R=function(e,t){var n=e.values[0],r=e.values[1],a=o.difference(n,t),i=o.difference(r,t);return o.intersection(a,i)},B={union:function(e,t){var n=t.values[0],r=t.values[1],a=o.union(e,n);if(!_(a))return o.union(a,r);var i=o.union(e,r);return _(i)?new M.Or([e,t]):o.union(n,i)},intersection:function(e,t){var n=t.values[0],r=t.values[1],a=o.intersection(e,n),i=o.intersection(e,r);return a===o.EMPTY?i:i===o.EMPTY?a:o.union(a,i)},difference:function(e,t){var n=t.values[0],r=t.values[1],a=o.difference(e,n),i=o.difference(e,r);return o.intersection(a,i)}},H={difference:function(e,t){var n=e.values[0],r=e.values[1],a=o.difference(n,t),i=o.difference(r,t);return o.union(a,i)}},F={In_In:{union:d("union",M.In),intersection:d("intersection",M.In),difference:d("difference",M.In)},UNIVERSAL_In:{difference:h(M.NotIn,"values")},In_NotIn:{union:p(d("difference",M.NotIn,o.UNIVERSAL)),intersection:d("difference",M.In),difference:d("intersection",M.In)},NotIn_In:{difference:d("union",M.NotIn)},In_GreaterThan:j,GreaterThan_In:D,In_GreaterThanEqual:j,GreaterThanEqual_In:D,In_LessThan:j,LessThan_In:D,In_LessThanEqual:j,LessThanEqual_In:D,In_And:j,And_In:D,In_Or:j,Or_In:D,NotIn_NotIn:{union:d("intersection",M.NotIn,o.UNIVERSAL),intersection:d("union",M.NotIn),difference:d("difference",M.In)},UNIVERSAL_NotIn:{difference:h(M.In,"values")},NotIn_GreaterThan:I(),GreaterThan_NotIn:T,NotIn_GreaterThanEqual:I(),GreaterThanEqual_NotIn:T,NotIn_LessThan:I(),LessThan_NotIn:T,NotIn_LessThanEqual:I(),LessThanEqual_NotIn:T,NotIn_And:I(),And_NotIn:T,NotIn_Or:I(),Or_NotIn:T,GreaterThan_GreaterThan:{union:y,intersection:v,difference:g(M.LessThan,M.LessThanEqual)},UNIVERSAL_GreaterThan:{difference:h(M.LessThanEqual)},GreaterThan_GreaterThanEqual:{union:y,intersection:v,difference:g(M.LessThan,M.LessThan)},GreaterThanEqual_GreaterThan:{difference:m(M.LessThan,M.LessThanEqual)},GreaterThan_LessThan:{union:(V=O(M.LessThan),function(e,t){return a.In.test([e.value],t.value)?new M.NotIn([e.value]):V(e,t)}),intersection:E(M.GreaterThan),difference:L(M.LessThan)},LessThan_GreaterThan:{difference:L(M.GreaterThan)},GreaterThan_LessThanEqual:{union:O(M.LessThanEqual),intersection:E(M.GreaterThanEqual),difference:L(M.LessThanEqual)},LessThanEqual_GreaterThan:{difference:L(M.GreaterThanEqual)},GreaterThan_And:{union:A,intersection:N,difference:K},And_GreaterThan:{difference:R},GreaterThan_Or:B,Or_GreaterThan:H,GreaterThanEqual_GreaterThanEqual:{union:y,intersection:v,difference:g(M.LessThan,M.LessThan)},UNIVERSAL_GreaterThanEqual:{difference:h(M.LessThan)},GreaterThanEqual_LessThan:{union:O(M.LessThanEqual),intersection:E(M.GreaterThanEqual),difference:L(M.LessThanEqual)},LessThan_GreaterThanEqual:{difference:L(M.GreaterThanEqual)},GreaterThanEqual_LessThanEqual:{union:O(M.LessThanEqual),intersection:(C=E(M.GreaterThan),function(e,t){var n=new M.In([e.value]);return n.isMember(t.value)?n:C(e,t)}),difference:L(M.LessThanEqual)},LessThanEqual_GreaterThanEqual:{difference:L(M.GreaterThanEqual)},GreaterThanEqual_And:{union:A,intersection:N,difference:K},And_GreaterThanEqual:{difference:R},GreaterThanEqual_Or:B,Or_GreaterThanEqual:H,LessThan_LessThan:{union:v,intersection:y,difference:g(M.GreaterThan,M.GreaterThanEqual)},UNIVERSAL_LessThan:{difference:h(M.GreaterThanEqual)},LessThan_LessThanEqual:{union:v,intersection:y,difference:g(M.GreaterThan,M.GreaterThan)},LessThanEqual_LessThan:{difference:m(M.GreaterThanEqual,M.GreaterThanEqual)},LessThan_And:{union:A,intersection:N,difference:K},And_LessThan:{difference:R},LessThan_Or:B,Or_LessThan:H,LessThanEqual_LessThanEqual:{union:v,intersection:y,difference:function(e,t){return e.value>=t.value?q([e,new M.GreaterThan(t.value)]):o.EMPTY}},UNIVERSAL_LessThanEqual:{difference:h(M.GreaterThan)},LessThanEqual_And:{union:A,intersection:N,difference:K},And_LessThanEqual:{difference:R},LessThanEqual_Or:B,Or_LessThanEqual:H,And_And:{union:function(e,t){var n=o.union(e,t.values[0]),r=o.union(e,t.values[1]);return(_(n)||_(r))&&(n=o.union(t,e.values[0]),r=o.union(t,e.values[1])),_(n)||_(r)?new M.Or([e,t]):o.intersection(n,r)},intersection:function(e,t){var n=o.intersection(e.values[0],t.values[0]),r=o.intersection(e.values[1],t.values[1]);return _(n)&&_(r)?(n=o.intersection(e.values[0],t.values[1]),r=o.intersection(e.values[1],t.values[0]),_(n)&&_(r)?new M.And([e,t]):o.intersection(n,r)):o.intersection(n,r)},difference:function(e,t){var n=o.difference(e,t.values[0]),r=o.difference(e,t.values[1]);return o.union(n,r)}},And_Or:{union:function(e,t){var n=o.union(e.values[0],t),r=o.union(e.values[1],t);return _(n)&&_(r)?new M.Or([e,t]):o.intersection(n,r)},intersection:function(e,t){var n=o.intersection(e,t.values[0]),r=o.intersection(e,t.values[1]);return x(n)||x(r)?new M.And([e,t]):o.union(n,r)},difference:function(e,t){var n=o.difference(e,t.values[0]),r=o.difference(e,t.values[1]);return o.intersection(n,r)}},Or_And:{difference:function(e,t){var n=o.difference(e,t.values[0]),r=o.difference(e,t.values[1]);return o.union(n,r)}},UNIVERSAL_And:{difference:function(e,t){var n=o.difference(e,t.values[0]),r=o.difference(e,t.values[1]);return o.union(n,r)}},Or_Or:{union:function(e,t){var n=o.union(e.values[0],t.values[0]),r=o.union(e.values[1],t.values[1]);return _(n)&&_(r)?(n=o.union(e.values[0],t.values[1]),r=o.union(e.values[1],t.values[0]),_(n)&&_(r)?new M.Or([e,t]):o.union(n,r)):o.union(n,r)},intersection:function(e,t){var n=t.values[0],r=t.values[1],a=o.intersection(e,n),i=o.intersection(e,r);return x(a)&&x(i)?(a=o.union(t,e.values[0]),i=o.union(t,e.values[1]),x(a)&&x(i)?new M.Or([e,t]):o.union(a,i)):o.union(a,i)},difference:function(e,t){var n=o.difference(e,t.values[0]),r=o.difference(e,t.values[1]);return o.intersection(n,r)}},UNIVERSAL_Or:{difference:function(e,t){var n=o.difference(e,t.values[0]),r=o.difference(e,t.values[1]);return o.intersection(n,r)}}},z=Object.keys(a);z.forEach(function(e,t){F[e+"_"+e]?o.defineComparison(a[e],a[e],F[e+"_"+e]):console.warn("no "+e+"_"+e),F["UNIVERSAL_"+e]?o.defineComparison(o.UNIVERSAL,a[e],F["UNIVERSAL_"+e]):console.warn("no UNIVERSAL_"+e);for(var n=t+1;n<z.length;n++){var r=z[n];F[e+"_"+r]?o.defineComparison(a[e],a[r],F[e+"_"+r]):console.warn("no "+e+"_"+r),F[r+"_"+e]?o.defineComparison(a[r],a[e],F[r+"_"+e]):console.warn("no "+r+"_"+e)}}),n.exports=a}),define("can-query-logic/src/types/make-real-number-range-inclusive",["require","exports","module","can-query-logic/src/set","can-query-logic/src/types/comparisons"],function(e,t,n){var l=e("can-query-logic/src/set"),f=e("can-query-logic/src/types/comparisons");n.exports=function(n,r){function o(e,t){this.start=0<arguments.length?+e:n,this.end=1<arguments.length?+t:r,this.range=new f.And([new f.GreaterThanEqual(this.start),new f.LessThanEqual(this.end)])}var a=new o(n,r);function s(e){return l.isSubset(a.range,e.range)}function c(e){var t={};if(e.values.forEach(function(e){e instanceof f.GreaterThanEqual&&(t.start=e.value),e instanceof f.GreaterThan&&(t.start=e.value+1),e instanceof f.LessThanEqual&&(t.end=e.value),e instanceof f.LessThan&&(t.end=e.value-1)}),"start"in t&&"end"in t)return new o(t.start,t.end)}function i(e){var t;if(e instanceof f.And&&(t=c(e)),e instanceof f.Or){var n=c(e.values[0]),r=c(e.values[1]);if(!n||!r)return l.UNDEFINABLE;var a=n.range.values,i=r.range.values;if(a[1].value+1===i[0].value)t=new o(a[0].value,i[1].value);else{if(i[1].value+1!==a[0].value)return l.UNDEFINABLE;t=new o(i[0].value,a[1].value)}}return t&&s(t)?l.UNIVERSAL:t}function u(e,t){var n=i(l.difference(e.range,t.range));return n||l.EMPTY}return l.defineComparison(o,o,{union:function(e,t){var n=i(l.union(e.range,t.range));return n||l.EMPTY},intersection:function(e,t){var n=i(l.intersection(e.range,t.range));return n||l.EMPTY},difference:u}),l.defineComparison(l.UNIVERSAL,o,{difference:function(e,t){return s(t)?l.EMPTY:u(a,t)}}),o}}),define("can-query-logic/src/types/types",function(e,t,n){n.exports={}}),define("can-query-logic/src/types/values-or",["require","exports","module","can-query-logic/src/set","can-query-logic/src/types/types"],function(e,t,n){var r=e("can-query-logic/src/set"),a=e("can-query-logic/src/types/types");function i(e){this.values=e}i.prototype.isMember=function(t){return this.values.some(function(e){return e&&e.isMember?e.isMember(t):e===t})},r.defineComparison(r.UNIVERSAL,i,{difference:function(){return r.UNDEFINABLE}}),n.exports=a.ValuesOr=i}),define("can-query-logic/src/types/values-not",["require","exports","module","can-query-logic/src/set","can-query-logic/src/types/types"],function(e,t,n){var r=e("can-query-logic/src/set"),a=e("can-query-logic/src/types/types");function i(e){this.value=e}var o=r.Identity;r.defineComparison(r.UNIVERSAL,o,{difference:function(e,t){return new i(t)}}),r.defineComparison(r.UNIVERSAL,i,{difference:function(e,t){return t.value}}),r.defineComparison(i,i,{}),r.defineComparison(i,o,{union:function(e,t){if(r.isEqual(e.value,t))return r.UNIVERSAL;throw new Error("Not,Identity Union is not filled out")},intersection:function(e,t){return r.isEqual(!e.value,t)?t:r.EMPTY},difference:function(e,t){return r.isEqual(e.value,t)?e:r.UNDEFINABLE}}),r.defineComparison(o,i,{difference:function(e,t){return r.isEqual(e,t.value)?e:r.UNDEFINABLE}}),n.exports=a.Not=i}),define("can-query-logic/src/types/keys-and",["require","exports","module","can-query-logic/src/set","can-assign","can-query-logic/src/array-union-intersection-difference","can-reflect","can-key/get/get","can-symbol","can-reflect","can-query-logic/src/types/types"],function(e,t,n){var m=e("can-query-logic/src/set"),b=e("can-assign"),r=e("can-query-logic/src/array-union-intersection-difference"),u=e("can-reflect"),s=e("can-key/get/get"),a=e("can-symbol"),w=(u=e("can-reflect"),e("can-query-logic/src/types/types"));function x(e){var n=this.values={};u.eachKey(e,function(e,t){u.isPlainObject(e)&&!m.isSpecial(e)?n[t]=new x(e):n[t]=e})}var c=a.for("can.isMember");function l(e){return m.isEqual(e,m.UNIVERSAL)?m.UNIVERSAL:e}x.prototype.isMember=function(r,a,e){var i=!0,o=e?e+".":"";return u.eachKey(this.values,function(e,t){var n=e&&(e[c]||e.isMember);n?n.call(e,s(r,t),a||r,o+t)||(i=!1):e!==s(r,t)&&(i=!1)}),i};var f={};function _(e,t){var n=r(Object.keys(e),Object.keys(t));return{aOnlyKeys:n.difference,aAndBKeys:n.intersection,bOnlyKeys:r(Object.keys(t),Object.keys(e)).difference}}function k(e){return e!==m.EMPTY}function i(e,t){var r=e.values,a=t.values,n=_(r,a),i=n.aOnlyKeys,o=n.aAndBKeys,s=n.bOnlyKeys,c={},u={},l={};o.forEach(function(e){var t=m.difference(r[e],a[e]);if(t===m.EMPTY)c[e]=r[e];else{var n=m.intersection(r[e],a[e]);n!==m.EMPTY?u[e]={difference:t,intersection:n}:l[e]=r[e]}});var f,d=Object.keys(u);if(1===d.length&&((f={})[d[0]]=u[d[0]].difference),Object.keys(l).length)return e;if(0===i.length&&0===s.length)return 1<d.length?m.UNDEFINABLE:1===d.length?(b(c,f),new x(c)):m.EMPTY;if(0<i.length&&0===s.length)return 1<d.length?m.UNDEFINABLE:1===d.length?(b(c,f),i.forEach(function(e){c[e]=r[e]}),new x(c)):m.EMPTY;if(0===i.length&&0<s.length){if(1<d.length)return m.UNDEFINABLE;var p;if(1===d.length){var h=d[0];(p=b({},c))[h]=u[h].difference,c[h]=u[h].intersection}var v=s.map(function(e){var t=b({},c),n=t[e]=m.difference(m.UNIVERSAL,a[e]);return n===m.EMPTY?n:new x(t)}).filter(k);return p&&v.push(new x(p)),1<v.length?new w.ValuesOr(v):1===v.length?v[0]:m.EMPTY}if(0<i.length&&0<s.length){if(d.length)throw new Error("Can't handle any productable keys right now");if(i.forEach(function(e){c[e]=r[e]}),1!==s.length)return m.UNDEFINABLE;var y=s[0],g=b({},c);return g[y]=m.difference(m.UNIVERSAL,a[y]),new x(g)}}m.defineComparison(x,x,{union:function(t,n){var e=_(t.values,n.values),r=[],a={};e.aAndBKeys.forEach(function(e){m.isEqual(t.values[e],n.values[e])?a[e]=t.values[e]:r.push(e)});var i={},o={};if(r.forEach(function(e){i[e]=t.values[e],o[e]=n.values[e]}),!e.aOnlyKeys.length&&!e.bOnlyKeys.length){if(1===r.length){var s=r[0],c=a[s]=m.union(t.values[s],n.values[s]);return 1===u.size(a)&&m.isEqual(c,m.UNIVERSAL)?m.UNIVERSAL:new x(a)}if(0===r.length)return t}if(0===r.length){if(0<e.aOnlyKeys.length&&0===e.bOnlyKeys.length)return l(n);if(0===e.aOnlyKeys.length&&0<e.bOnlyKeys.length)return l(t)}return 0<e.aOnlyKeys.length&&0===e.bOnlyKeys.length&&m.isSubset(new x(i),new x(o))?n:0<e.bOnlyKeys.length&&0===e.aOnlyKeys.length&&m.isSubset(new x(o),new x(i))?t:new w.ValuesOr([t,n])},intersection:function(e,t){var n=e.values,r=t.values,a=!1,i={};return function(e,t,n,r,a){var i,o=b({},n);for(var s in e){if(void 0!==(i=t(s,e[s],s in n?n[s]:f,e,n)))return;delete o[s]}for(s in o)if(void 0!==(i=r(s,f,n[s],e,n)))return}(n,function(e,t,n){i[e]=n===f?t:m.intersection(t,n),i[e]===m.EMPTY&&(a=!0)},r,function(e,t,n){i[e]=n,i[e]===m.EMPTY&&(a=!0)}),a?m.EMPTY:new x(i)},difference:i}),m.defineComparison(m.UNIVERSAL,x,{difference:function(e,t){return i({values:{}},t)}}),n.exports=w.KeysAnd=x}),define("can-query-logic/src/types/and-or-not",["require","exports","module","can-query-logic/src/types/values-or","can-query-logic/src/types/values-not","can-query-logic/src/types/keys-and"],function(e,t,n){var r=e("can-query-logic/src/types/values-or"),a=e("can-query-logic/src/types/values-not"),i=e("can-query-logic/src/types/keys-and");n.exports={KeysAnd:i,ValuesOr:r,ValuesNot:a}}),define("can-query-logic/src/helpers",["require","exports","module","can-reflect"],function(e,t,n){var s=e("can-reflect"),r={undefined:0,null:1,number:3,string:4,object:5,boolean:6},a=function(e){var t=typeof e;return null===e&&(t="null"),r[t]},i={$gt:function(e,t){return a(e)>a(t)},$lt:function(e,t){return a(e)<a(t)}},c={$gt:function(e,t){return null==e||null==t?i.$gt(e,t):t<e},$lt:function(e,t){return null==e||null==t?i.$gt(e,t):e<t}},u={uniqueConcat:function(e,t,n){var r=new Set;return e.concat(t).filter(function(e){var t=n(e);return!r.has(t)&&(r.add(t),!0)})},getIndex:function(e,t,n){if(t&&t.length){if(-1===e(n,t[0]))return 0;if(1===e(n,t[t.length-1]))return t.length;for(var r=0,a=t.length;r<a;){var i=r+a>>>1;-1===e(n,t[i])?a=i:r=i+1}return a}},sortData:function(e){return"-"===e[0]?{prop:e.slice(1),desc:!0}:{prop:e,desc:!1}},defaultCompare:c,typeCompare:i,sorter:function(e,t){var i,o=u.sortData(e);return i=t&&t[o.prop]?t[o.prop]:c,function(e,t){var n,r=s.getKeyValue(e,o.prop),a=s.getKeyValue(t,o.prop);return o.desc&&(n=r,r=a,a=n),i.$lt(r,a)?-1:i.$gt(r,a)?1:0}},valueHydrator:function(e){if(s.isBuiltIn(e))return e;throw new Error("can-query-logic doesn't support comparison operator: "+JSON.stringify(e))}};n.exports=u}),define("can-query-logic/src/types/basic-query",["require","exports","module","can-query-logic/src/set","can-query-logic/src/types/make-real-number-range-inclusive","can-assign","can-reflect","can-query-logic/src/types/and-or-not","can-query-logic/src/helpers","can-define-lazy-value","can-symbol"],function(e,t,n){var l=e("can-query-logic/src/set"),r=e("can-query-logic/src/types/make-real-number-range-inclusive"),a=e("can-assign"),i=e("can-reflect"),o=e("can-query-logic/src/types/and-or-not"),s=e("can-query-logic/src/helpers"),c=e("can-define-lazy-value"),u=(e("can-symbol").for("can.isMember"),o.KeysAnd),f=o.ValuesOr,d=o.ValuesNot,p=r(0,1/0);function h(e,o){var t={};function n(e){this.key=e,this.compare=s.sorter(e,t)}return i.eachKey(e,function(a,i){t[i]={$gt:function(e,t){if(null==e||null==t)return s.typeCompare.$gt(e,t);var n=o({$gt:t},i,a,s.valueHydrator),r=o({$eq:e},i,a,s.valueHydrator);return l.isEqual(l.union(n,r),n)},$lt:function(e,t){if(null==e||null==t)return s.typeCompare.$lt(e,t);var n=o({$lt:t},i,a,s.valueHydrator),r=o({$eq:e},i,a,s.valueHydrator);return l.isEqual(l.union(n,r),n)}}}),l.defineComparison(n,n,{intersection:function(e,t){return e.key===t.key?e:l.EMPTY},difference:function(e,t){return e.key===t.key?l.EMPTY:e},union:function(e,t){return e.key===t.key?e:l.UNDEFINABLE}}),n}var v=h({});function y(e){a(this,e),this.filter||(this.filter=l.UNIVERSAL),this.page||(this.page=new p),this.sort||(this.sort="id"),"string"==typeof this.sort&&(this.sort=new v(this.sort))}y.KeysAnd=u,y.Or=f,y.Not=d,y.RecordRange=p,y.makeSort=h,i.assignMap(y.prototype,{count:function(){return this.page.end-this.page.start+1},sortData:function(e){return e.slice(0).sort(this.sort.compare)},filterMembersAndGetCount:function(e,t){if(t){if(!l.isSubset(this,t))throw new Error("can-query-logic: Unable to get members from a set that is not a superset of the current set.")}else t=new y;var n=e.filter(function(e){return this.filter.isMember(e)},this),r=n.length;r&&this.sort.key!==t.sort.key&&(n=this.sortData(n));var a=l.isEqual(this.page,l.UNIVERSAL);if(l.isEqual(t.page,l.UNIVERSAL))return a?{data:n,count:r}:{data:n.slice(this.page.start,this.page.end+1),count:r};if(this.sort.key===t.sort.key&&l.isEqual(t.filter,this.filter))return{data:n.slice(this.page.start-t.page.start,this.page.end-t.page.start+1),count:r};throw new Error("can-query-logic: Unable to get members from the parent set for this subset.")},filterFrom:function(e,t){return this.filterMembersAndGetCount(e,t).data},merge:function(e,t,n,r){var a=l.union(this,e);if(a!==l.UNDEFINABLE){var i=s.uniqueConcat(t,n,r);return a.sortData(i)}},index:function(e,t){var n=s.sortData(this.sort.key);if(i.hasOwnKey(e,n.prop))return s.getIndex(this.sort.compare,t,e)},isMember:function(e){return this.filter.isMember(e)},removePagination:function(){this.page=new p}});var g=["filter","page","sort"];function m(e,t,n){return!!n[e+"FilterIsSubset"]&&(!!n[t+"PageIsUniversal"]||n[e+"PageIsSubset"]&&n.sortIsEqual)}function b(e,t){this.queryA=e,this.queryB=t}function w(e,t){return new b(e,t)}i.eachKey({pageIsEqual:function(){return l.isEqual(this.queryA.page,this.queryB.page)},aPageIsUniversal:function(){return l.isEqual(this.queryA.page,l.UNIVERSAL)},bPageIsUniversal:function(){return l.isEqual(this.queryB.page,l.UNIVERSAL)},pagesAreUniversal:function(){return this.pageIsEqual&&this.aPageIsUniversal},sortIsEqual:function(){return this.queryA.sort.key===this.queryB.sort.key},aFilterIsSubset:function(){return l.isSubset(this.queryA.filter,this.queryB.filter)},bFilterIsSubset:function(){return l.isSubset(this.queryB.filter,this.queryA.filter)},aPageIsSubset:function(){return l.isSubset(this.queryA.page,this.queryB.page)},bPageIsSubset:function(){return l.isSubset(this.queryB.page,this.queryA.page)},filterIsEqual:function(){return l.isEqual(this.queryA.filter,this.queryB.filter)},aIsSubset:function(){return m("a","b",this)},bIsSubset:function(){return m("b","a",this)}},function(e,t){c(b.prototype,t,e)}),l.defineComparison(y,y,{union:function(e,t){var n=w(e,t),r=l.union(e.filter,t.filter);if(n.pagesAreUniversal)return new y({filter:r,sort:n.sortIsEqual?e.sort.key:void 0});if(n.filterIsEqual)return n.sortIsEqual?new y({filter:e.filter,sort:e.sort.key,page:l.union(e.page,t.page)}):n.aIsSubset?t:n.bIsSubset?e:l.UNDEFINABLE;throw new Error("different filters, non-universal pages")},intersection:function(e,t){var n=w(e,t);if(n.pagesAreUniversal){var r=l.intersection(e.filter,t.filter);return l.isDefinedAndHasMembers(r)?new y({filter:r,sort:n.sortIsEqual?e.sort.key:void 0}):r}return l.intersection(e.filter,t.filter)===l.EMPTY?l.EMPTY:n.filterIsEqual?n.sortIsEqual?new y({filter:e.filter,sort:e.sort.key,page:l.intersection(e.page,t.page)}):n.aIsSubset?e:n.bIsSubset?t:l.UNKNOWABLE:n.aIsSubset?e:n.bIsSubset?t:l.UNDEFINABLE},difference:function(e,t){var n,r,a,i,o=(n=e,r=t,a=[],g.forEach(function(e){l.isEqual(n[e],r[e])||a.push(e)}),a),s=w(e,t);if(1<o.length)return s.aIsSubset?l.EMPTY:s.pagesAreUniversal?new y({filter:l.difference(e.filter,t.filter),sort:e.sort.key}):l.UNDEFINABLE;switch(i=o[0]){case void 0:return l.EMPTY;case"sort":return s.pagesAreUniversal?l.EMPTY:l.UNKNOWABLE;case"page":case"filter":var c=l.difference(e[i],t[i]);if(l.isSpecial(c))return c;var u={filter:e.filter,page:e.page,sort:e.sort.key};return u[i]=c,new y(u)}}}),n.exports=y}),define("can-query-logic/src/serializer",["require","exports","module","can-reflect"],function(e,t,n){var r=e("can-reflect"),a=function(e){var r=this.serializers=new Map;e&&e.forEach(function(e){var t=e[0],n=e[1];r.set(t,n)}),this.serialize=this.serialize.bind(this)};a.prototype.add=function(e){r.assign(this.serializers,e instanceof a?e.serializers:e)},a.prototype.serialize=function(e){if(!e)return e;var t=e.constructor,n=this.serializers.get(t);return n?n(e,this.serialize):r.serialize(e)},n.exports=a}),define("can-query-logic/src/serializers/comparisons",["require","exports","module","can-query-logic/src/types/comparisons","can-query-logic/src/serializer","can-reflect"],function(e,t,n){var a=e("can-query-logic/src/types/comparisons"),r=e("can-query-logic/src/serializer"),i=e("can-reflect");function o(t){return function(e){return new t(e)}}var s={};function c(n,r){s[n]=function(e,t){return r(t?t(e[n]):e[n])},Object.defineProperty(s[n],"name",{value:"hydrate "+n,writable:!0})}function u(r,a){s[r]=function(e,t){var n=e[r];return t&&(n=n.map(function(e){return t(e)})),a(n)},Object.defineProperty(s[r],"name",{value:"hydrate "+r,writable:!0})}c("$eq",function(e){return new a.In([e])}),c("$ne",function(e){return new a.NotIn([e])}),c("$gt",o(a.GreaterThan)),c("$gte",o(a.GreaterThanEqual)),u("$in",o(a.In)),c("$lt",o(a.LessThan)),c("$lte",o(a.LessThanEqual)),u("$nin",o(a.GreaterThan));var l=new r([[a.In,function(e,t){return 1===e.values.length?t(e.values[0]):{$in:e.values.map(t)}}],[a.NotIn,function(e,t){return 1===e.values.length?{$ne:t(e.values[0])}:{$nin:e.values.map(t)}}],[a.GreaterThan,function(e,t){return{$gt:t(e.value)}}],[a.GreaterThanEqual,function(e,t){return{$gte:t(e.value)}}],[a.LessThan,function(e,t){return{$lt:t(e.value)}}],[a.LessThanEqual,function(e,t){return{$lte:t(e.value)}}],[a.And,function(e,t){var n={};return e.values.forEach(function(e){i.assignMap(n,t(e))}),n}]]);n.exports={hydrate:function(n,r){if(r||(r=function(){throw new Error("can-query-logic doesn't recognize operator: "+JSON.stringify(n))}),Array.isArray(n))return new a.In(n.map(function(e){return r(e)}));if(n&&"object"==typeof n){var e=Object.keys(n);if(e.every(function(e){return s[e]})){var t=e.map(function(e){var t={};return t[e]=n[e],(0,s[e])(t,r)});return 1<t.length?new a.And(t):t[0]}return r(n)}return new a.In([r(n)])},serializer:l}}),define("can-query-logic/src/schema-helpers",["require","exports","module","can-reflect","can-query-logic/src/set","can-symbol"],function(e,t,n){var r,a=e("can-reflect"),i=e("can-query-logic/src/set"),o=e("can-symbol");n.exports=r={isRangedType:function(e){return e&&a.isConstructorLike(e)&&!i.hasComparisons(e)&&!e[o.for("can.SetType")]&&e.prototype.valueOf&&e.prototype.valueOf!==Object.prototype.valueOf},categorizeOrValues:function(e){var t={primitives:[],valueOfTypes:[],others:[]};return e.forEach(function(e){a.isPrimitive(e)?t.primitives.push(e):r.isRangedType(e)?t.valueOfTypes.push(e):t.others.push(e)}),t}}}),define("can-query-logic/src/types/make-maybe",["require","exports","module","can-query-logic/src/set","can-query-logic/src/types/comparisons","can-reflect","can-query-logic/src/schema-helpers","can-symbol"],function(e,t,n){var s=e("can-query-logic/src/set"),c=e("can-query-logic/src/types/comparisons"),u=e("can-reflect"),a=e("can-query-logic/src/schema-helpers"),r=e("can-symbol"),i=r.for("can.ComparisonSetType"),l=r.for("can.isMember");function o(e,n){var i=new c.In(e);function o(e){var t=function t(n,e){var r;if(e instanceof c.And)return e.values.map(function(e){return t(n,e)}).reduce(function(e,t){return{range:s.intersection(e.range,t.range),enum:s.intersection(e.enum,t.enum)}},{range:s.UNIVERSAL,enum:n});if(e instanceof c.In){var a=e.values.filter(function(e){return n.isMember(e)});if(a.length){var i=e.values.slice(0);return u.removeValues(i,a),{enum:new c.In(a),range:i.length?new c.In(i):s.EMPTY}}return{enum:s.EMPTY,range:e}}if(e instanceof c.NotIn){r=s.intersection(n,e);var o=e.values.filter(function(e){return!n.isMember(e)});return{range:o.length?new c.NotIn(o):s.UNIVERSAL,enum:r}}return{enum:s.EMPTY,range:e}}(i,e.range);if(this.range=t.range||s.EMPTY,e.enum?t.enum!==s.EMPTY?this.enum=s.union(t.enum,e.enum):this.enum=e.enum:this.enum=t.enum,this.enum===s.EMPTY&&this.range===s.EMPTY)return s.EMPTY}return o.prototype.orValues=function(){var e=[];return this.range!==s.EMPTY&&e.push(this.range),this.enum!==s.EMPTY&&e.push(this.enum),e},o.prototype[l]=function(){var e=this.range[l]||this.range.isMember,t=this.enum[l]||this.enum.isMember;return e.apply(this.range,arguments)||t.apply(this.enum,arguments)},s.defineComparison(o,o,{union:function(e,t){return new o({enum:s.union(e.enum,t.enum),range:s.union(e.range,t.range)})},difference:function(e,t){return new o({enum:s.difference(e.enum,t.enum),range:s.difference(e.range,t.range)})},intersection:function(e,t){return new o({enum:s.intersection(e.enum,t.enum),range:s.intersection(e.range,t.range)})}}),o.inValues=e,s.defineComparison(s.UNIVERSAL,o,{difference:function(e,t){var n;if(t.range===s.UNIVERSAL)return new o({range:t.range,enum:s.difference(i,t.enum)});if(t.enum!==s.EMPTY)return n=s.difference(e,t.range),new o({enum:s.difference(i,t.enum),range:n});var r=s.difference(s.UNIVERSAL,t.range),a=s.difference(i,t.range);return new o({range:r,enum:s.difference(a,r)})}}),n=n||function(e){return e},o.hydrate=function(e,t){return new o({range:t(e,n)})},o}o.canMakeMaybeSetType=function(e){var t=u.getSchema(e);if(t&&"Or"===t.type){var n=a.categorizeOrValues(t.values);return 1===n.valueOfTypes.length&&n.valueOfTypes.length+n.primitives.length===t.values.length}return!1},o.makeMaybeSetTypes=function(t){var n,e=u.getSchema(t),r=a.categorizeOrValues(e.values);return t[i]?n=t[i]:((n=function(e){this.value=u.new(t,e)}).prototype.valueOf=function(){return this.value},u.assignSymbols(n.prototype,{"can.serialize":function(){return this.value}})),{Maybe:o(r.primitives,function(e){return new n(e)}),ComparisonSetType:n}},n.exports=o}),define("can-query-logic/src/types/make-enum",["require","exports","module","can-query-logic/src/set","can-query-logic/src/array-union-intersection-difference","can-query-logic/src/schema-helpers","can-reflect","can-symbol"],function(e,t,n){var o=e("can-query-logic/src/set"),s=e("can-query-logic/src/array-union-intersection-difference"),a=e("can-query-logic/src/schema-helpers"),c=e("can-reflect"),r=e("can-symbol"),i=r.for("can.SetType"),u=r.for("can.isMember"),l=r.for("can.new");function f(n,r){function a(e){var t=Array.isArray(e)?e:[e];this.values=r?t.map(r):t}c.assignSymbols(a.prototype,{"can.serialize":function(){return 1===this.values.length?this.values[0]:this.values}}),a.prototype[u]=function(t){return this.values.some(function(e){return o.isEqual(e,t)})},a.UNIVERSAL=new a(n);var i=function(e,t){var n=s(e.values,t.values);return n.difference.length?new a(n.difference):o.EMPTY};return o.defineComparison(a,a,{union:function(e,t){var n=s(e.values,t.values);return n.union.length?new a(n.union):o.EMPTY},intersection:function(e,t){var n=s(e.values,t.values);return n.intersection.length?new a(n.intersection):o.EMPTY},difference:i}),o.defineComparison(a,o.UNIVERSAL,{difference:function(e){return i(e,{values:n.slice(0)})}}),o.defineComparison(o.UNIVERSAL,a,{difference:function(e,t){return i({values:n.slice(0)},t)}}),a}function d(e,n,t){var r=f(n,t);return e[i]=r,e[u]=function(t){return n.some(function(e){return o.isEqual(e,t)})},r}d.canMakeEnumSetType=function(e){var t=c.getSchema(e);return!(!t||"Or"!==t.type)&&a.categorizeOrValues(t.values).primitives.length===t.values.length},d.makeEnumSetType=function(e){var t=c.getSchema(e),n=a.categorizeOrValues(t.values),r=e[l]?e[l].bind(e):void 0;return f(n.primitives,r)},n.exports=d}),define("can-query-logic/src/serializers/basic-query",["require","exports","module","can-symbol","can-reflect","can-query-logic/src/types/basic-query","can-query-logic/src/set","can-query-logic/src/serializers/comparisons","can-query-logic/src/serializer","can-query-logic/src/types/comparisons","can-query-logic/src/types/make-maybe","can-query-logic/src/types/make-enum","can-log/dev/dev","can-query-logic/src/helpers"],function(e,t,n){var r=e("can-symbol"),c=e("can-reflect"),u=e("can-query-logic/src/types/basic-query"),l=e("can-query-logic/src/set"),o=e("can-query-logic/src/serializers/comparisons"),s=e("can-query-logic/src/serializer"),f=e("can-query-logic/src/types/comparisons"),i=e("can-query-logic/src/types/make-maybe"),d=e("can-query-logic/src/types/make-enum"),p=(e("can-log/dev/dev"),e("can-query-logic/src/helpers")),h=r.for("can.SetType"),v=r.for("can.getSchema"),y=new u({});function g(e,t,n){return e&&"object"==typeof e&&"$or"in e?function(e,t,n){var r=e.map(function(e){return w(e,t,n)}),a=function(e){var t=Object.keys(e[0].values),n={},r=new f.In(t);if(t.map(function(e){n[e]=[]}),!e.every(function(e){return!!l.isEqual(r,new f.In(Object.keys(e.values)))&&(c.eachKey(e.values,function(e,t){n[t].push(e)}),!0)}))return;var a=[];if(t.forEach(function(e){n[e].reduce(function(e,t){return!1!==t&&(void 0===t?e:!!l.isEqual(e,t)&&e)})||a.push(e)}),1!==a.length)return;var i=a[0],o=n[i].reduce(function(e,t){return l.union(e,t)},l.EMPTY),s={};return t.map(function(e){s[e]=n[e][0]}),s[i]=o,new u.KeysAnd(s)}(r);if(a)return a;return new u.Or(r)}(e.$or,t,n):w(e,t,n)}var m=new WeakMap;function b(e,t,n,r){if(n){var a=n[h];return a?a.hydrate?a.hydrate(e,o.hydrate):l.hasComparisons(a)?new a(e):o.hydrate(e,function(e){return new a(e)}):d.canMakeEnumSetType(n)?(m.has(n)||m.set(n,d.makeEnumSetType(n)),new(a=m.get(n))(e)):i.canMakeMaybeSetType(n)?(m.has(n)||m.set(n,i.makeMaybeSetTypes(n)),(a=m.get(n).Maybe).hydrate(e,o.hydrate)):o.hydrate(e,r)}return o.hydrate(e,r)}function w(e,n,r){function a(e){if(e){if(Array.isArray(e))return e.map(r);if(c.isPlainObject(e))return w(e,(t=e.constructor)&&t[v]&&t[v]().keys||{})}var t;return r?r(e):e}n=n||{};var i={};return c.eachKey(e,function(e,t){i[t]=b(e,0,n[t],a)}),new u.KeysAnd(i)}n.exports=function(e){var a=e.identity&&e.identity[0],n=e.keys,t=[[u.Or,function(e,t){return e.values.map(function(e){return t(e)})}],[u.KeysAnd,function(e,n){var r=[],a={};return c.eachKey(e.values,function(e,t){"function"==typeof e.orValues?function n(r,e,a,i){e.orValues().forEach(function(e){if("function"==typeof e.orValues)n(r,e,a,i);else{var t={};t[i]=a(e),r.push(t)}})}(r,e,n,t):a[t]=n(e)}),r.length?1===r.length?r[0]:{$or:r.map(function(e){return c.assign(c.serialize(a),e)})}:a}],[u.RecordRange,function(e){return{start:e.start,end:e.end}}],[u,function(e,t){var n=l.isEqual(e.filter,l.UNIVERSAL)?{}:t(e.filter),r={};return 0!==c.size(n)&&(r.filter=n),l.isEqual(e.page,y.page)||(r.page={start:e.page.start},e.page.end!==y.page.end&&(r.page.end=e.page.end)),e.sort.key!==a&&(r.sort=e.sort.key),r}]],r=u.makeSort(n,b),i=new s(t);return i.add(o.serializer),{hydrate:function(e){var t={filter:g(c.serialize(e.filter),n,p.valueHydrator)};return e.page&&(t.page=new u.RecordRange(e.page.start,e.page.end)),e.sort?t.sort=new r(e.sort):t.sort=new r(a),new u(t)},serializer:i}}}),define("can-query-logic",["require","exports","module","can-query-logic/src/set","can-symbol","can-reflect","can-query-logic/src/serializers/basic-query","can-query-logic/src/types/basic-query","can-query-logic/src/types/comparisons","can-query-logic/src/types/make-enum"],function(e,t,n){var o=e("can-query-logic/src/set"),r=e("can-symbol"),s=e("can-reflect"),c=e("can-query-logic/src/serializers/basic-query"),a=e("can-query-logic/src/types/basic-query"),i=e("can-query-logic/src/types/comparisons"),u=r.for("can.getSchema"),l=r.for("can.new"),f=e("can-query-logic/src/types/make-enum");function d(e,t){e=e||{};var n,r=t&&t.toQuery,a=t&&t.toParams;(n=e[u]?e[u]():e).identity&&n.identity[0]||(n.identity=["id"]);var i,o,s=c(n);i=r?function(e){return s.hydrate(r(e))}:s.hydrate,o=a?function(e){return a(s.serializer.serialize(e))}:s.serializer.serialize,this.hydrate=i,this.serialize=o,this.schema=n}function p(i){return function(e,t){var n=this.hydrate(e),r=this.hydrate(t),a=o[i](n,r);return this.serialize(a)}}function h(a){return function(e,t){var n=this.hydrate(e),r=this.hydrate(t);return o[a](n,r)}}for(var v in s.assignSymbols(d.prototype,{"can.getSchema":function(){return this.schema}}),s.assign(d.prototype,{union:p("union"),difference:p("difference"),intersection:p("intersection"),isEqual:h("isEqual"),isProperSubset:h("isProperSubset"),isSubset:h("isSubset"),isSpecial:o.isSpecial,isDefinedAndHasMembers:o.isDefinedAndHasMembers,count:function(e){var t=this.hydrate(e);return t.page.end-t.page.start+1},identityKeys:function(){return this.schema.identity},filterMembers:function(e,t,n){var r=this.hydrate(e);if(3<=arguments.length){var a=this.hydrate(t);return r.filterFrom(n,a)}return r.filterFrom(t)},filterMembersAndGetCount:function(e,t,n){var r=this.hydrate(e),a=this.hydrate(t);return r.filterMembersAndGetCount(n,a)},unionMembers:function(e,t,n,r){var a=this.hydrate(e),i=this.hydrate(t),o=this.schema;return a.merge(i,n,r,function(e){return s.getIdentity(e,o)})},isMember:function(e,t){return this.hydrate(e).isMember(t)},memberIdentity:function(e){return s.getIdentity(e,this.schema)},index:function(e,t,n){return this.hydrate(e).index(n,t)},insert:function(e,t,n){var r=this.index(e,t,n);void 0===r&&(r=t.length);var a=t.slice(0);return a.splice(r,0,n),a},isPaginated:function(e){var t=this.hydrate(e);return!o.isEqual(t.page,o.UNIVERSAL)},removePagination:function(e){var t=this.hydrate(e);return t.removePagination(),this.serialize(t)}}),o)void 0===d[v]&&(d[v]=o[v]);d.makeEnum=function(e){var t=function(){};return t[l]=function(e){return e},f(t,e),t},d.KeysAnd=a.KeysAnd,d.ValuesOr=a.Or,d.In=i.In,d.NotIn=i.NotIn,d.GreaterThan=i.GreaterThan,d.GreaterThanEqual=i.GreaterThanEqual,d.LessThan=i.LessThan,d.LessThanEqual=i.LessThanEqual,d.ValueAnd=i.And,d.ValueOr=i.Or,n.exports=d}),define("can-fixture/matches",["require","exports","module","can-query-logic/src/set","can-reflect","can-fixture/data-from-url","can-query-logic"],function(e,t,n){var o=e("can-query-logic/src/set"),s=e("can-reflect"),r=e("can-fixture/data-from-url"),c=e("can-query-logic");function u(e){if(e.fixture||e.xhr||e.data){var t=s.serialize(e);return delete t.fixture,delete t.xhr,delete t.data,t}return e}var a={intersection:function(e,t){return e.value===t.value?e:o.EMPTY},difference:function(e,t){return e.value===t.value?o.EMPTY:e},union:function(e,t){return e.value===t.value?e:o.UNDEFINABLE}};function i(r){var e=function(){},t=function(e){this.value=e};return t.prototype.isMember=function(e,t,n){return r(this.value,e,t,n)},s.assignSymbols(e,{"can.SetType":t}),o.defineComparison(t,t,a),o.defineComparison(o.UNIVERSAL,t,{difference:function(){return o.UNDEFINABLE}}),e}function l(e,t){var n=e.data,r=t.data;if(n&&r&&!function n(e,r){if(e===r)return!0;if(Array.isArray(e)&&Array.isArray(r))return e.every(function(e,t){return n(e,r[t])});if(e&&r&&s.isPlainObject(e)&&s.isPlainObject(r)){for(var t in e){if(!r.hasOwnProperty(t))return!1;if(!n(e[t],r[t]))return!1}return!0}return!1}(n,r))return!1;var a=new c.KeysAnd(u(e)),i=new c.KeysAnd(u(t));return o.isEqual(a,i)}var f={};s.eachKey({IsEmptyOrNull:function(e,t){return null==e&&0===s.size(t)||(null==t&&0===s.size(e)||l(e,t))},isEmptyOrSubset:function(e,t){return null==e&&0===s.size(t)||(null==t&&0===s.size(e)||(n=e,r=t,o.isSubset(new c.KeysAnd(n),new c.KeysAnd(r))));var n,r},TemplateUrl:function(e,t){return!!r(e,t)},StringIgnoreCase:function(e,t){return t&&e?e.toLowerCase()===t.toLowerCase():t===e},Ignore:function(){return!0}},function(e,t){f[t]=i(e)});var d={identity:["id"],keys:{url:f.TemplateUrl,fixture:f.Ignore,xhr:f.Ignore,type:f.StringIgnoreCase,method:f.StringIgnoreCase,helpers:f.Ignore,headers:f.IsEmptyOrNull,data:f.IsEmptyOrSubset}},p=new c(d);n.exports={fixture:l,request:function(e,t){return p.isMember({filter:t},e)},matches:function(e,t,n){return n?this.fixture(e,t):this.request(e,t)},makeComparatorType:i}}),define("can-memory-store/make-simple-store",["require","exports","module","can-reflect"],function(e,t,n){var g=e("can-reflect");n.exports=function e(t){t.constructor=e;var n=Object.create(t);return g.assignMap(n,{getRecordFromParams:function(e){var t=g.getIdentity(e,this.queryLogic.schema);return this.getRecord(t)},log:function(){this._log=!0},getSets:function(){return this.getQueries()},getQueries:function(){return Promise.resolve(this.getQueriesSync())},getQueriesSync:function(){return this.getQueryDataSync().map(function(e){return e.query})},getListData:function(e){e=e||{};var t=this.getListDataSync(e);return t?Promise.resolve(t):Promise.reject({title:"no data",status:"404",detail:"No data available for this query.\nAvailable queries: "+JSON.stringify(this.getQueriesSync())})},getPaginatedListDataSync:function(e){var t=this.getAllRecords(),n=this.queryLogic.removePagination(e.query),r=this.queryLogic.filterMembersAndGetCount(n,{},t),a=function(e,t,n){for(var r=g.getSchema(n),a=0;a<e.length;a++)if(t===g.getIdentity(e[a],r))return a;return-1}(r.data,e.startIdentity,this.queryLogic),i=r.data.slice(a,a+this.queryLogic.count(e.query));return{count:r.data.length,data:i}},getListDataSync:function(e){for(var t,n=this.getQueryDataSync(),r=this.queryLogic.isPaginated(e),a=0;a<n.length;a++){var i=n[a].query;this.queryLogic.isSubset(e,i)&&(t=n[a])}var o=this.getAllRecords();if(r&&this.queryLogic.isPaginated(t.query)){var s=this.getPaginatedListDataSync(t);return this.queryLogic.filterMembersAndGetCount(e,t.query,s.data)}var c=this.queryLogic.filterMembersAndGetCount(e,{},o);return c&&c.count?c:t?{count:0,data:[]}:void 0},updateListData:function(e,t){var n=this.getQueryDataSync();t=t||{};var r,a=g.serialize(e),i=(r=a,Array.isArray(r)?r:r.data);this.updateRecordsSync(i);var o=this.queryLogic.isPaginated(t),s=i.length?g.getIdentity(i[0],this.queryLogic.schema):void 0;if(o){for(var c=0;c<n.length;c++){var u=n[c].query,l=this.queryLogic.union(u,t);if(this.queryLogic.isDefinedAndHasMembers(l)){var f=this.getPaginatedListDataSync(n[c]),d=this.queryLogic.unionMembers(u,t,f.data,i);return s=g.getIdentity(d[0],this.queryLogic.schema),n[c]={query:l,startIdentity:s},this.updateQueryDataSync(n),Promise.resolve()}}return n.push({query:t,startIdentity:s}),this.updateQueryDataSync(n),Promise.resolve()}var p=this.getAllRecords(),h=this.queryLogic.filterMembers(t,p);if(h.length){var v=new Map;h.forEach(function(e){v.set(g.getIdentity(e,this.queryLogic.schema),e)},this),i.forEach(function(e){v.delete(g.getIdentity(e,this.queryLogic.schema))},this),this.destroyRecords(g.toArray(v))}var y=this.getQueryDataSync().filter(function(e){return!this.queryLogic.isSubset(e.query,t)},this);return y.filter(function(e){return this.queryLogic.isSubset(t,e.query)},this).length?this.updateQueryDataSync(y):this.updateQueryDataSync(y.concat([{query:t,startIdentity:s}])),Promise.resolve()},getData:function(e){var t=g.getIdentity(e,g.getSchema(this.queryLogic)),n=this.getRecord(t);return n?Promise.resolve(n):Promise.reject({title:"no data",status:"404",detail:"No record with matching identity ("+t+")."})},createData:function(e){return this.updateRecordsSync([e]),Promise.resolve(g.assignMap({},this.getRecordFromParams(e)))},updateData:function(e){if(!this.errorOnMissingRecord||this.getRecordFromParams(e))return this.updateRecordsSync([e]),Promise.resolve(g.assignMap({},this.getRecordFromParams(e)));var t=g.getIdentity(e,this.queryLogic.schema);return Promise.reject({title:"no data",status:"404",detail:"No record with matching identity ("+t+")."})},destroyData:function(e){var t=g.getIdentity(e,this.queryLogic.schema),n=this.getRecordFromParams(e);return this.errorOnMissingRecord&&!n?Promise.reject({title:"no data",status:"404",detail:"No record with matching identity ("+t+")."}):(this.destroyRecords([e]),Promise.resolve(g.assignMap({},n||e)))}})}}),define("can-memory-store",["require","exports","module","can-reflect","can-namespace","can-memory-store/make-simple-store"],function(e,t,n){var r=e("can-reflect"),a=e("can-namespace"),i=e("can-memory-store/make-simple-store");n.exports=a.memoryStore=function e(t){t.constructor=e;var n=Object.create(i(t));return r.assignMap(n,{clear:function(){this._instances={},this._queries=[]},_queryData:[],updateQueryDataSync:function(e){this._queryData=e},getQueryDataSync:function(){return this._queryData},_instances:{},getRecord:function(e){return this._instances[e]},getAllRecords:function(){var e=[];for(var t in this._instances)e.push(this._instances[t]);return e},destroyRecords:function(e){r.eachIndex(e,function(e){var t=r.getIdentity(e,this.queryLogic.schema);delete this._instances[t]},this)},updateRecordsSync:function(e){e.forEach(function(e){var t=r.getIdentity(e,this.queryLogic.schema);this._instances[t]=e},this)}}),n}}),define("can-fixture/store",["require","exports","module","can-query-logic","can-reflect","can-memory-store"],function(e,t,n){var r=e("can-query-logic"),i=e("can-reflect"),s=e("can-memory-store"),a=function(n,r){return function(e,t){this.connection[n](r.call(this,e.data)).then(function(e){t(e)},function(e){t(parseInt(e.status,10),e)})}},c=function(e,r){return function(){var t=[],n=0;return e.forEach(function(e){t.push(i.serialize(e)),n=Math.max(e[r],n)}),{maxId:n,items:t}}},u=function(e,t,n){var r=e.queryLogic.schema,a=r.identity[0],i=r.keys;for(var o in i&&i[a]||console.warn("No type specified for identity key. Going to convert strings to reasonable type."),this.connection=e,this.makeItems=t,this.idProp=n,this.reset(),u.prototype)this[o]=this[o].bind(this)};function o(e){var t=this.connection.queryLogic.schema,n=t.identity[0],r=t.keys;r&&r[n]||((r={})[n]=function(e){return"string"==typeof e?function(e){switch(e){case"NaN":case"Infinity":return+e;case"null":return null;case"undefined":return;case"true":case"false":return"true"===e;default:var t=+e;return isNaN(t)?e:t}}(e):e});var a={};return i.eachKey(e,function(e,t){r[t]?a[t]=i.convert(e,r[t]):a[t]=e}),a}function l(e){return e&&"identityKeys"in e}i.assignMap(u.prototype,{getListData:a("getListData",function(e){return e}),getData:a("getData",o),createData:function(e,t){var n=this.idProp;e.data[n]=++this.maxId,this.connection.createData(o.call(this,e.data)).then(function(e){t(e)},function(e){t(403,e)})},createInstance:function(e){var t=this.idProp;return t in e||(e[t]=++this.maxId),this.connection.createData(e)},updateData:a("updateData",o),updateInstance:function(e){return this.connection.updateData(e)},destroyInstance:function(e){return this.connection.destroyData(e)},destroyData:a("destroyData",o),reset:function(e){e&&(this.makeItems=c(e,this.idProp));var t=this.makeItems();this.maxId=t.maxId,this.connection.updateListData(t.items,{})},get:function(e){var t=this.connection.queryLogic.memberIdentity(e);return this.connection.getRecord(t)},getList:function(e){return this.connection.getListDataSync(e)}}),u.make=function(a,i,e){var t,o;"number"==typeof a?(e?l(e)||(e=new r(e)):e=new r({}),o=e.identityKeys()[0]||"id",t=function(){for(var e=[],t=0,n=0;n<a;n++){var r=i(n,e);r[o]||(r[o]=n),t=Math.max(r[o],t),e.push(r)}return{maxId:t,items:e}}):Array.isArray(a)&&((e=i)?l(e)||(e=new r(e)):e=new r({}),o=e.identityKeys()[0]||"id",t=c(a,o));var n=s({queryLogic:e,errorOnMissingRecord:!0});return new u(n,t,o)},n.exports=u}),define("can-fixture/core",["require","exports","module","can-key/sub/sub","can-reflect","can-fixture/matches","can-log","can-log/dev/dev","can-fixture/data-from-url","can-fixture/store"],function(e,o,t){"use strict";var s=e("can-key/sub/sub"),c=e("can-reflect"),r=e("can-fixture/matches"),w=(e("can-log"),e("can-log/dev/dev")),u=e("can-fixture/data-from-url");e("can-fixture/store");var l=[];o.fixtures=l;var x={item:{GET:"getData",PUT:"updateData",DELETE:"destroyData"},list:{GET:"getListData",POST:"createData"}};function _(e){var t=e.match(/(GET|POST|PUT|DELETE|PATCH) (.+)/i);return t?[t[1],t[2]]:[void 0,e]}function f(e,t){var n={},r=_(e),a=r[0],i=function(e,t){if(!(t=t||function(e){var t=e.match(/\{(.*)\}/);if(t&&2===t.length)return t[1]}(e)))return[void 0,e];var n=new RegExp("\\/\\{"+t+"\\}.*"),r=n.test(e),a=r?e.replace(n,""):e;return[r?e:e.trim()+"/{"+t+"}",a]}(r[1],t.idProp),o=i[0],s=i[1];if(a){var c=['fixture("'+e+'", fixture) must use a store method, not a store directly.'];if(o){var u=x.item[a];if(u){n[a+" "+o]=t[u];var l='Replace with fixture("'+a+" "+o+'", fixture.'+u+") for items.";c.push(l)}}var f=x.list[a];if(f){n[a+" "+s]=t[f];var d='Replace with fixture("'+a+" "+s+'", fixture.'+f+") for lists.";c.push(d)}var p=c.join(" ");w.warn(p)}else{var h=x.item;for(var v in h){var y=h[v];n[v+" "+o]=t[y]}var g=x.list;for(var m in g){var b=g[m];n[m+" "+s]=t[b]}}return n}o.add=function(e,t){if(void 0!==t){if((n=t)&&(n.getData||n.getListData))return e=f(e,t),void o.add(e);var n,r,a,i;"string"==typeof e&&(r=_(e),a=r[0],i=r[1],e=a?{type:a,url:i}:{url:i}),function(e,t,n){var r=o.index(t,!0);if(-1<r&&l.splice(r,1),null!=n){if("object"==typeof n){var a=n;n=function(){return a}}t.fixture=n,l.unshift(t)}}(0,e,t)}else c.eachKey(e,function(e,t){o.add(t,e)})};var d=o.add;d.on=!0,d.delay=10,o.callDynamicFixture=function(t,n,r){t.data=n.data;var a=function(){var e=o.extractResponse.apply(t,arguments);return r.apply(this,e)},e=function(){var e=n.fixture(t,a,t.headers,n);void 0!==e&&a(200,e)};return t.async?setTimeout(e,d.delay):(e(),null)},o.index=function(e,t){for(var n=0;n<l.length;n++)if(r.matches(e,l[n],t))return n;return-1},o.get=function(e){if(d.on){var t=o.index(e,!0);-1===t&&(t=o.index(e,!1));var n=0<=t?c.assignMap({},l[t]):void 0;if(n){var r=n.fixture,a=u(n.url,e.url);if("string"==typeof n.fixture)a&&(r=s(r,a)),n.url=r,n.data=null,n.type="GET",n.error||(n.error=function(e,t,n){throw"fixtures.js Error "+t+" "+n});else if(c.isPlainObject(e.data)||null==e.data){var i=c.assignMap({},e.data||{});n.data=c.assignMap(i,a)}else n.data=e.data}return n}},o.matches=r,o.extractResponse=function(e,t,n,r){return"number"!=typeof e&&(n=t,t=e,e=200),"string"==typeof n&&(r=n,n={}),[e,t,n,r]}}),define("can-fixture/xhr",["require","exports","module","can-fixture/core","can-deparam","can-reflect","can-log"],function(e,t,n){!function(e,t,n,r){"use strict";var o=t("can-fixture/core"),s=t("can-deparam"),c=t("can-reflect"),u=t("can-log"),a=XMLHttpRequest,i=void 0!==e?e:window,l=["type","url","async","response","responseText","responseType","responseXML","responseURL","status","statusText","readyState"],f=["abort","error","load","loadend","loadstart","progress","readystatechange"];function d(e,t){for(var n=e.__events[t]||[],r=0,a=n.length;r<a;r++)n[r].call(e)}function p(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!0,writable:!0,value:n})}!function(){var e=new a;for(var t in e)0===t.indexOf("on")?-1===f.indexOf(t.substr(2))&&f.push(t.substr(2)):-1===l.indexOf(t)&&"function"!=typeof e[t]&&l.push(t)}(),i.XMLHttpRequest=function(){var t=this,n=new a;p(this,"_xhr",n),p(this,"_requestHeaders",{}),p(this,"__events",{}),f.forEach(function(e){n["on"+e]=function(){if(d(t,e),t["on"+e])return t["on"+e].apply(t,arguments)}}),this.onload=null},i.XMLHttpRequest._XHR=a,c.assignMap(XMLHttpRequest.prototype,{setRequestHeader:function(e,t){this._requestHeaders[e]=t},open:function(e,t,n){this.type=e,this.url=t,this.async=!1!==n},getAllResponseHeaders:function(){return this._xhr.getAllResponseHeaders.apply(this._xhr,arguments)},addEventListener:function(e,t){(this.__events[e]=this.__events[e]||[]).push(t)},removeEventListener:function(e,t){var n=this.__events[e]=this.__events[e]||[],r=n.indexOf(t);0<=r&&n.splice(r,1)},setDisableHeaderCheck:function(e){this._disableHeaderCheck=!!e},getResponseHeader:function(e){return this._xhr.getResponseHeader(e)},abort:function(){var e=this._xhr;return void 0!==this.timeoutId&&(clearTimeout(this.timeoutId),e.open(this.type,this.url,!1!==this.async),e.send()),e.abort()},send:function(e){var t=this.type.toLowerCase()||"get",n={url:this.url,data:e,headers:this._requestHeaders,type:t,method:t,async:this.async,xhr:this};if((!n.data&&"get"===n.type||"delete"===n.type)&&(n.data=s(n.url.split("?")[1]),n.url=n.url.split("?")[0]),"string"==typeof n.data)try{n.data=JSON.parse(n.data)}catch(e){n.data=s(n.data)}var r=o.get(n),a=this;if(!r||"function"!=typeof r.fixture){var i=function(){return a._xhr.open(a._xhr.type,a._xhr.url,a._xhr.async),a._requestHeaders&&Object.keys(a._requestHeaders).forEach(function(e){a._xhr.setRequestHeader(e,a._requestHeaders[e])}),a._xhr.send(e)};return r&&"number"==typeof r.fixture?(u.log("can-fixture: "+n.url+" => delay "+r.fixture+"ms"),void(this.timeoutId=setTimeout(i,r.fixture))):(r&&(u.log("can-fixture: "+n.url+" => "+r.url),c.assignMap(a,r)),i())}this.timeoutId=o.callDynamicFixture(n,r,function(e,t,r,n){t="string"==typeof t?t:JSON.stringify(t),a._xhr={open:function(){},send:function(){},abort:function(){},getResponseHeader:function(){}},c.assignMap(a,{readyState:4,status:e}),200<=e&&e<300||304===e?c.assignMap(a,{statusText:n||"OK",responseText:t}):c.assignMap(a,{statusText:n||"error",responseText:t}),a.getAllResponseHeaders=function(){var n=[];return c.eachKey(r||{},function(e,t){Array.prototype.push.apply(n,[t,": ",e,"\r\n"])}),n.join("")},a.onreadystatechange&&a.onreadystatechange({target:a}),d(a,"progress"),a.onprogress&&a.onprogress(),d(a,"load"),a.onload&&a.onload(),d(a,"loadend"),a.onloadend&&a.onloadend()})}}),l.forEach(function(t){Object.defineProperty(XMLHttpRequest.prototype,t,{get:function(){return this._xhr[t]},set:function(e){try{this._xhr[t]=e}catch(e){}}})})}(function(){return this}(),e)}),define("can-fixture",["require","exports","module","can-fixture/core","can-fixture/store","can-fixture/xhr","can-reflect","can-namespace"],function(e,t,n){"use strict";var r=e("can-fixture/core"),a=r.add,i=e("can-fixture/store");e("can-fixture/xhr");var o=e("can-reflect"),s=e("can-namespace"),c=function(){};o.assignMap(a,{rand:function e(t,n,r){if("number"==typeof t)return"number"==typeof n?t+Math.floor(Math.random()*(n-t+1)):Math.floor(Math.random()*(t+1));var a=t.slice(0);void 0===n?(n=1,r=a.length):void 0===r&&(r=n);for(var i=[],o=n+Math.round(e(r-n)),s=0;s<o;s++){var c=e(a.length-1),u=a.splice(c,1)[0];i.push(u)}return i},xhr:function(e){return o.assignMap({},{abort:c,getAllResponseHeaders:function(){return""},getResponseHeader:function(){return""},open:c,overrideMimeType:c,readyState:4,responseText:"",responseXML:null,send:c,setRequestHeader:c,status:200,statusText:"OK"},e)},store:i.make,fixtures:r.fixtures}),"undefined"!=typeof window&&"function"!=typeof e.resolve&&(window.fixture=a),n.exports=s.fixture=a}),define("can/es/can-fixture",["exports","can-fixture"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-query-logic",["exports","can-query-logic"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-connect/behavior",function(e,t,n){"use strict";var r={};function a(i,o){"string"!=typeof i&&(o=i,i=void 0);var e=function(e){var t=function(){};Object.defineProperty(t,"name",{value:i,configurable:!0}),t.prototype=e;var n=new t,r="function"==typeof o?o.apply(n,arguments):o;for(var a in r)r.hasOwnProperty(a)?Object.defineProperty(n,a,Object.getOwnPropertyDescriptor(r,a)):n[a]=r[a];return n.__behaviorName=i,n};return i&&(r[e.behaviorName=i]=e),e.isBehavior=!0,e}a.map=r,n.exports=a}),define("can-connect/connect",["require","exports","module","can-reflect","can-connect/behavior"],function(e,t,n){e("can-reflect").assignMap;var r=e("can-connect/behavior"),a=function(e,t){(e=e.map(function(e,t){var n=-1;return"string"==typeof e?(n=a.order.indexOf(e),e=e.map[e]):e.isBehavior?n=a.order.indexOf(e.behaviorName):e=a.behavior(e),{originalIndex:t,sortedIndex:n,behavior:e}})).sort(function(e,t){return~e.sortedIndex&&~t.sortedIndex?e.sortedIndex-t.sortedIndex:e.originalIndex-t.originalIndex}),e=e.map(function(e){return e.behavior});var n=a.base(a.behavior("options",function(){return t})());return e.forEach(function(e){n=e(n)}),n.init&&n.init(),n};a.order=["data/localstorage-cache","data/url","data/parse","cache-requests","data/combine-requests","constructor","constructor/store","can/map","can/ref","fall-through-cache","data/worker","real-time","data/callbacks-cache","data/callbacks","constructor/callbacks-once"],a.behavior=r,n.exports=a}),define("can-connect/base/base",["require","exports","module","can-connect/behavior","can-reflect","can-symbol"],function(e,t,n){"use strict";var r=e("can-connect/behavior"),a=e("can-reflect"),i=e("can-symbol");n.exports=r("base",function(e){var t;return{id:function(e){if(this.queryLogic)return a.getIdentity(e,this.queryLogic.schema);if(this.idProp)return e[this.idProp];throw new Error("can-connect/base/base - Please add a queryLogic option.")},listQuery:function(e){return e[this.listQueryProp]},listQueryProp:i.for("can.listQuery"),init:function(){},get queryLogic(){return t||(e.queryLogic?e.queryLogic:e.algebra?e.algebra:void 0)},set queryLogic(e){t=e}}})}),define("can-connect",["require","exports","module","can-connect/connect","can-connect/base/base","can-namespace"],function(e,t,n){"use strict";var r=e("can-connect/connect"),a=e("can-connect/base/base"),i=e("can-namespace");r.base=a,n.exports=i.connect=r}),define("can-connect/helpers/weak-reference-map",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var r=function(){this.set={}};(0,e("can-reflect").assignMap)(r.prototype,{has:function(e){return!!this.set[e]},addReference:function(e,t,n){if(void 0===e)throw new Error("can-connect: You must provide a key to store a value in a WeakReferenceMap");var r=this.set[e];r||(r=this.set[e]={item:t,referenceCount:0,key:e}),r.referenceCount+=n||1},referenceCount:function(e){var t=this.set[e];if(t)return t.referenceCount},deleteReference:function(e){var t=this.set[e];t&&(t.referenceCount--,0===t.referenceCount&&delete this.set[e])},get:function(e){var t=this.set[e];if(t)return t.item},forEach:function(e){for(var t in this.set)e(this.set[t].item,t)}}),n.exports=r}),define("can-diff/update-deep-except-identity/update-deep-except-identity",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var a=e("can-reflect");n.exports=function(n,r,e){if(e||(e=a.getSchema(n)),!e)throw new Error("can-diff/update-except-id is unable to update without a schema.");e.identity.forEach(function(e){var t=a.getKeyValue(n,e);void 0!==t&&a.setKeyValue(r,e,t)}),a.updateDeep(n,r)}}),define("can-connect/helpers/id-merge",["require","exports","module","can-diff/list/list","can-reflect"],function(e,t,n){"use strict";var a=e("can-diff/list/list"),i=e("can-reflect");n.exports=function(t,e,n,r){a(t,e,function(e,t){return n(e)===n(t)}).forEach(function(e){i.splice(t,e.index,e.deleteCount,e.insert.map(r))})}}),define("can-connect/constructor/constructor",["require","exports","module","can-reflect","can-connect/helpers/weak-reference-map","can-diff/update-deep-except-identity/update-deep-except-identity","can-connect/helpers/id-merge","can-connect/behavior"],function(e,t,n){"use strict";var r=e("can-reflect"),a=r.toArray,i=r.assignMap,o=e("can-connect/helpers/weak-reference-map"),s=e("can-diff/update-deep-except-identity/update-deep-except-identity"),c=e("can-connect/helpers/id-merge"),u=e("can-connect/behavior");function l(e,t){for(var n in e)"data"!==n&&("function"==typeof t.set?t.set(n,e[n]):"function"==typeof t.attr?t.attr(n,e[n]):t[n]=e[n])}n.exports=u("constructor",function(e){return{cidStore:new o,_cid:0,get:function(e){var t=this;return this.getData(e).then(function(e){return t.hydrateInstance(e)})},getList:function(t){t=t||{};var n=this;return this.getListData(t).then(function(e){return n.hydrateList(e,t)})},hydrateList:function(e,t){Array.isArray(e)&&(e={data:e});for(var n=[],r=0;r<e.data.length;r++)n.push(this.hydrateInstance(e.data[r]));if(e.data=n,this.list)return this.list(e,t);var a=e.data.slice(0);return a[this.listQueryProp||"__listQuery"]=t,l(e,a),a},hydrateInstance:function(e){return this.instance?this.instance(e):i({},e)},save:function(t){var e=this.serializeInstance(t),n=this.id(t),r=this;if(void 0!==n)return this.updateData(e).then(function(e){return void 0!==e&&r.updatedInstance(t,e),t});var a=this._cid++;return this.cidStore.addReference(a,t),this.createData(e,a).then(function(e){return void 0!==e&&r.createdInstance(t,e),r.cidStore.deleteReference(a,t),t})},destroy:function(t){var e=this.serializeInstance(t),n=this;return this.destroyData(e).then(function(e){return void 0!==e&&n.destroyedInstance(t,e),t})},createdInstance:function(e,t){i(e,t)},updatedInstance:function(e,t){s(e,t,this.queryLogic.schema)},updatedList:function(e,t,n){for(var r=[],a=0;a<t.data.length;a++)r.push(this.hydrateInstance(t.data[a]));c(e,r,this.id.bind(this),this.hydrateInstance.bind(this)),l(t,e)},destroyedInstance:function(e,t){s(e,t,this.queryLogic.schema)},serializeInstance:function(e){return i({},e)},serializeList:function(e){var t=this;return a(e).map(function(e){return t.serializeInstance(e)})},isNew:function(e){var t=this.id(e);return!(t||0===t)}}})}),define("can-diff/assign-deep-except-identity/assign-deep-except-identity",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var a=e("can-reflect");n.exports=function(n,r,e){if(e||(e=a.getSchema(n)),!e)throw new Error("can-diff/update-except-id is unable to update without a schema.");e.identity.forEach(function(e){var t=a.getKeyValue(n,e);void 0!==t&&a.setKeyValue(r,e,t)}),a.assignDeep(n,r)}}),define("can-validate-interface",function(e,t,n){"use strict";n.exports=function(e){var t=e.reduce(function(e,t){return e.concat(t)},[]);return function(n){var e=t.reduce(function(e,t){return t in n?e:e.concat(t)},[]);return e.length?{message:"missing expected properties",related:e}:void 0}}}),define("can-connect/helpers/validate",["require","exports","module","can-validate-interface"],function(e,t,n){"use strict";var s=e("can-validate-interface");function c(e,t,n){var r='can-connect: Extending behavior "'+(t.behaviorName||"anonymous behavior")+'" found base behavior "'+(e.__behaviorName||"anonymous behavior")+'" was missing required properties: '+JSON.stringify(n.related),a=new Error(r);return Object.setPrototypeOf&&Object.setPrototypeOf(a,Object.getPrototypeOf(this)),a}n.exports=function(n,e){var t,r,a,i,o=(t=n,r=0,a=e,i=function(e,t){throw new c(t,n,e)},function(){var e=s(a)(arguments[r]);return e&&i&&i(e,arguments[r]),t.apply(this,arguments)});return Object.keys(n).forEach(function(e){o[e]=n[e]}),o.__interfaces=e,o},c.prototype=Object.create(Error.prototype,{constructor:{value:Error}}),Object.setPrototypeOf?Object.setPrototypeOf(c,Error):c.__proto__=Error}),define("can-connect/can/map/map",["require","exports","module","can-reflect","can-queues","can-event-queue/map/map","can-observation-recorder","can-symbol","can-query-logic","can-log/dev/dev","can-connect/behavior","can-diff/update-deep-except-identity/update-deep-except-identity","can-diff/assign-deep-except-identity/assign-deep-except-identity","can-diff/merge-deep/merge-deep","can-symbol"],function(e,t,n){"use strict";var i=e("can-reflect"),r=i.each,a=i.isPlainObject,o=e("can-queues"),s=e("can-event-queue/map/map"),c=(e("can-observation-recorder"),e("can-symbol")),u=e("can-query-logic"),l=(e("can-log/dev/dev"),e("can-connect/behavior")),f=e("can-diff/update-deep-except-identity/update-deep-except-identity"),d=e("can-diff/assign-deep-except-identity/assign-deep-except-identity"),p=e("can-diff/merge-deep/merge-deep"),h=(c=e("can-symbol")).for("can.getName");var v=l("can/map",function(a){var e={init:function(){if(!this.Map)throw new Error("can-connect/can/map/map must be configured with a Map type");if(this[h]||(this[h]=function(){return this.name?"Connection{"+this.name+"}":this.Map?"Connection{"+i.getName(this.Map)+"}":"string"==typeof this.url?"Connection{"+this.url+"}":"Connection{}"}),this.List=this.List||this.Map.List,!this.List)throw new Error("can-connect/can/map/map - "+i.getName(this)+" must be configured with a List type.");m(this,this.Map,y),m(this,this.List,g),this.queryLogic||(this.queryLogic=new u(this.Map));var r=this;if(this.Map[c.for("can.onInstanceBoundChange")]){this.Map[c.for("can.onInstanceBoundChange")](function(e,t){var n=t?"addInstanceReference":"deleteInstanceReference";r[n]&&r[n](e)})}else console.warn("can-connect/can/map is unable to listen to onInstanceBoundChange on the Map type");if(this.List[c.for("can.onInstanceBoundChange")]){this.List[c.for("can.onInstanceBoundChange")](function(e,t){var n=t?"addListReference":"deleteListReference";r[n]&&r[n](e)})}else console.warn("can-connect/can/map is unable to listen to onInstanceBoundChange on the List type");this.Map[c.for("can.onInstancePatches")]?this.Map[c.for("can.onInstancePatches")](function(t,e){e.forEach(function(e){"add"!==e.type&&"set"!==e.type||e.key!==r.idProp||!t[c.for("can.isBound")]()||r.addInstanceReference(t)})}):console.warn("can-connect/can/map is unable to listen to onInstancePatches on the Map type"),a.init.apply(this,arguments)},serializeInstance:function(e){return i.serialize(e)},serializeList:function(e){return i.serialize(e)},instance:function(e){return new this.Map(e)},list:function(e,t){var n=new(this.List||this.Map&&this.Map.List)(e.data);return i.eachKey(e,function(e,t){"data"!==t&&i.setKeyValue(n,t,e)}),n[this.listQueryProp]=t,n},updatedList:function(e,t,n){o.batch.start();o.mutateQueue.enqueue(a.updatedList,this,arguments,{}),o.batch.stop()},save:function(e){i.setKeyValue(e,"_saving",!0);var t=function(){i.setKeyValue(e,"_saving",!1)},n=a.save.apply(this,arguments);return n.then(t,t),n},destroy:function(e){i.setKeyValue(e,"_destroying",!0);var t=function(){i.setKeyValue(e,"_destroying",!1)},n=a.destroy.apply(this,arguments);return n.then(t,t),n}};return r(["created","updated","destroyed"],function(n){e[n+"Instance"]=function(e,t){t&&"object"==typeof t&&("destroyed"===n&&0===i.size(t)||(this.constructor.removeAttr?f(e,t,this.queryLogic.schema):this.updateInstanceWithAssignDeep?d(e,t,this.queryLogic.schema):function(n,r,e){if(e||(e=i.getSchema(n)),!e)throw new Error("can-connect/can/map/ is unable to update without a schema.");e.identity.forEach(function(e){var t=i.getKeyValue(n,e);void 0!==t&&i.setKeyValue(r,e,t)}),p(n,r)}(e,t,this.queryLogic.schema))),"created"===n&&this.moveCreatedInstanceToInstanceStore&&this.moveCreatedInstanceToInstanceStore(e),v.callbackInstanceEvents(n,e)}}),e}),y={static:{getList:function(e,t){return function(e){return t.getList(e)}},findAll:function(e,t){return function(e){return t.getList(e)}},get:function(e,t){return function(e){return t.get(e)}},findOne:function(e,t){return function(e){return t.get(e)}}},prototype:{isNew:function(e,t){return function(){return t.isNew(this)}},isSaving:function(e,t){return function(){return!!i.getKeyValue(this,"_saving")}},isDestroying:function(e,t){return function(){return!!i.getKeyValue(this,"_destroying")}},save:function(e,r){return function(e,t){var n=r.save(this);return n.then(e,t),n}},destroy:function(e,r){return function(e,t){var n;return this.isNew()?(n=Promise.resolve(this),r.destroyedInstance(this,{})):n=r.destroy(this),n.then(e,t),n}}},properties:{_saving:{enumerable:!(v.callbackInstanceEvents=function(e,t){var n=t.constructor;o.batch.start(),s.dispatch.call(t,{type:e,target:t}),s.dispatch.call(n,e,[t]),o.batch.stop()}),value:!1,configurable:!0,writable:!0},_destroying:{enumerable:!1,value:!1,configurable:!0,writable:!0}}},g={static:{_bubbleRule:function(r,e){return function(e,t){var n=r(e,t);return n.push("destroyed"),n}}},prototype:{setup:function(t,n){return function(e){a(e)&&!Array.isArray(e)?(this[n.listQueryProp]=e,t.apply(this),this.replace(i.isPromise(e)?e:n.getList(e))):t.apply(this,arguments)}}},properties:{}},m=function(e,t,n){var r;for(r in n.properties)i.defineInstanceKey(t,r,n.properties[r]);for(r in n.prototype)t.prototype[r]=n.prototype[r](t.prototype[r],e);if(n.static)for(r in n.static)t[r]=n.static[r](t[r],e)};n.exports=v}),define("can-connect/helpers/weak-reference-set",["require","exports","module","can-reflect"],function(e,t,n){var r=function(){this.set=[]};(0,e("can-reflect").assignMap)(r.prototype,{has:function(e){return-1!==this._getIndex(e)},addReference:function(e,t){var n=this._getIndex(e),r=this.set[n];r||(r={item:e,referenceCount:0},this.set.push(r)),r.referenceCount+=t||1},deleteReference:function(e){var t=this._getIndex(e),n=this.set[t];n&&(n.referenceCount--,0===n.referenceCount&&this.set.splice(t,1))},delete:function(e){var t=this._getIndex(e);-1!==t&&this.set.splice(t,1)},get:function(e){var t=this.set[this._getIndex(e)];if(t)return t.item},referenceCount:function(e){var t=this.set[this._getIndex(e)];if(t)return t.referenceCount},_getIndex:function(n){var r;return this.set.every(function(e,t){if(e.item===n)return r=t,!1}),void 0!==r?r:-1},forEach:function(e){return this.set.forEach(e)}}),n.exports=r}),define("can-connect/helpers/sorted-set-json",["require","exports","module","can-reflect"],function(e,t,n){var r=e("can-reflect");n.exports=function(e){return null==e?e:JSON.stringify(r.cloneKeySort(e))}}),define("can-connect/constructor/store/store",["require","exports","module","can-connect","can-connect/helpers/weak-reference-map","can-connect/helpers/weak-reference-set","can-connect/helpers/sorted-set-json","can-event-queue/map/map"],function(e,t,n){"use strict";var r=e("can-connect"),a=e("can-connect/helpers/weak-reference-map"),o=e("can-connect/helpers/weak-reference-set"),s=e("can-connect/helpers/sorted-set-json"),i=e("can-event-queue/map/map"),c=0,u=null,l={increment:function(e){c++,clearTimeout(u)},decrement:function(e){0===--c&&(u=setTimeout(function(){l.dispatch("end")},n.exports.requestCleanupDelay)),c<0&&(c=0)},count:function(){return c}};i(l);var f=r.behavior("constructor/store",function(i){return{instanceStore:new a,newInstanceStore:new o,listStore:new a,init:function(){i.init&&i.init.apply(this,arguments),this.hasOwnProperty("_requestInstances")||(this._requestInstances={}),this.hasOwnProperty("_requestLists")||(this._requestLists={}),l.on("end",function(){var e;for(e in this._requestInstances)this.instanceStore.deleteReference(e);for(e in this._requestInstances={},this._requestLists)this.listStore.deleteReference(e),this._requestLists[e].forEach(this.deleteInstanceReference.bind(this));this._requestLists={}}.bind(this))},_finishedRequest:function(){l.decrement(this)},addInstanceReference:function(e,t){var n=t||this.id(e);void 0===n?this.newInstanceStore.addReference(e):this.instanceStore.addReference(n,e)},createdInstance:function(e,t){i.createdInstance.apply(this,arguments),this.moveCreatedInstanceToInstanceStore(e)},moveCreatedInstanceToInstanceStore:function(e){var t=this.id(e);if(this.newInstanceStore.has(e)&&void 0!==t){var n=this.newInstanceStore.referenceCount(e);this.newInstanceStore.delete(e),this.instanceStore.addReference(t,e,n)}},addInstanceMetaData:function(e,t,n){var r=this.instanceStore.set[this.id(e)];r&&(r[t]=n)},getInstanceMetaData:function(e,t){var n=this.instanceStore.set[this.id(e)];if(n)return n[t]},deleteInstanceMetaData:function(e,t){delete this.instanceStore.set[this.id(e)][t]},deleteInstanceReference:function(e){void 0===this.id(e)?this.newInstanceStore.deleteReference(e):this.instanceStore.deleteReference(this.id(e),e)},addListReference:function(e,t){var n=s(t||this.listQuery(e));n&&(this.listStore.addReference(n,e),e.forEach(function(e){this.addInstanceReference(e)}.bind(this)))},deleteListReference:function(e,t){var n=s(t||this.listQuery(e));n&&(this.listStore.deleteReference(n,e),e.forEach(this.deleteInstanceReference.bind(this)))},hydratedInstance:function(e){if(0<l.count()){var t=this.id(e);this._requestInstances[t]||(this.addInstanceReference(e),this._requestInstances[t]=e)}},hydrateInstance:function(e){var t=this.id(e);if((t||0===t)&&this.instanceStore.has(t)){var n=this.instanceStore.get(t);return this.updatedInstance(n,e),n}var r=i.hydrateInstance.call(this,e);return this.hydratedInstance(r),r},hydratedList:function(e,t){if(0<l.count()){var n=s(t||this.listQuery(e));n&&(this._requestLists[n]||(this.addListReference(e,t),this._requestLists[n]=e))}},hydrateList:function(e,t){t=t||this.listQuery(e);var n=s(t);if(n&&this.listStore.has(n)){var r=this.listStore.get(n);return this.updatedList(r,e,t),r}var a=i.hydrateList.call(this,e,t);return this.hydratedList(a,t),a},getList:function(e){var t=this;l.increment(this);var n=i.getList.call(this,e);return n.then(function(e){t._finishedRequest()},function(){t._finishedRequest()}),n},get:function(e){var t=this;l.increment(this);var n=i.get.call(this,e);return n.then(function(e){t._finishedRequest()},function(){t._finishedRequest()}),n},save:function(t){var n=this;l.increment(this);var r=!this.isNew(t);r&&this.addInstanceReference(t);var e=i.save.call(this,t);return e.then(function(e){r&&n.deleteInstanceReference(t),n._finishedRequest()},function(){n._finishedRequest()}),e},destroy:function(e){var t=this;this.addInstanceReference(e),l.increment(this);var n=i.destroy.call(this,e);return n.then(function(e){t._finishedRequest(),t.deleteInstanceReference(e)},function(){t._finishedRequest()}),n},updatedList:function(e,t,n){var r=e.slice(0);t.data||"number"!=typeof t.length||(t={data:t}),i.updatedList?(i.updatedList.call(this,e,t,n),e.forEach(function(e){this.addInstanceReference(e)}.bind(this))):t.data&&t.data.forEach(function(e){this.addInstanceReference(e)}.bind(this)),r.forEach(this.deleteInstanceReference.bind(this))}}});f.requests=l,f.requestCleanupDelay=10,n.exports=f}),define("can-connect/data/callbacks/callbacks",["require","exports","module","can-connect","can-reflect"],function(e,t,n){"use strict";var r=e("can-connect"),a=e("can-reflect").each,o={getListData:"gotListData",createData:"createdData",updateData:"updatedData",destroyData:"destroyedData"},i=r.behavior("data/callbacks",function(i){var t={};return a(o,function(a,e){t[e]=function(t,n){var r=this;return i[e].call(this,t).then(function(e){return r[a]?r[a].call(r,e,t,n):e})}}),t});n.exports=i}),define("can-connect/data/parse/parse",["require","exports","module","can-reflect","can-key/get/get","can-connect/behavior"],function(e,t,n){"use strict";var r=e("can-reflect").each,o=e("can-key/get/get"),a=e("can-connect/behavior");n.exports=a("data/parse",function(i){var e={parseListData:function(e){var t;if(i.parseListData&&(e=i.parseListData.apply(this,arguments)),Array.isArray(e))t={data:e};else{var n=this.parseListProp||"data";if(e.data=o(e,n),t=e,"data"!==n&&delete e[n],!Array.isArray(t.data))throw new Error("Could not get any raw data while converting using .parseListData")}for(var r=[],a=0;a<t.data.length;a++)r.push(this.parseInstanceData(t.data[a]));return t.data=r,t},parseInstanceData:function(e){return i.parseInstanceData&&(e=i.parseInstanceData.apply(this,arguments)||e),this.parseInstanceProp&&o(e,this.parseInstanceProp)||e}};return r(s,function(n,r){e[r]=function(e){var t=this;return i[r].call(this,e).then(function(){return t[n].apply(t,arguments)})}}),e});var s={getListData:"parseListData",getData:"parseInstanceData",createData:"parseInstanceData",updateData:"parseInstanceData",destroyData:"parseInstanceData"}}),define("can-ajax",["require","exports","module","can-globals/global/global","can-reflect","can-namespace","can-parse-uri","can-param"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-globals/global/global"),y=t("can-reflect"),i=t("can-namespace"),g=t("can-parse-uri"),m=t("can-param"),b=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Microsoft.XMLHTTP")},function(){return new ActiveXObject("MSXML2.XMLHTTP.3.0")},function(){return new ActiveXObject("MSXML2.XMLHTTP")}],w=null,x=g(a().location.href),_={},k="application/json",O="application/x-www-form-urlencoded",E=function(t,e){try{var n=e.dataType||t.getResponseHeader("Content-Type").split(";")[0];if(!n||!t.responseText&&!t.responseXML)return t;switch(n){case"text/xml":case"xml":return t.responseXML;case"text/json":case"application/json":case"text/javascript":case"application/javascript":case"application/x-javascript":case"json":return t.responseText&&JSON.parse(t.responseText);default:return t.responseText}}catch(e){return t}};r.exports=i.ajax=function(t){var e,n,r,a=function(){if(null!=w)return w();for(var e=0,t=b.length;e<t;e++)try{var n=b[e],r=n();if(null!=r)return w=n,r}catch(e){continue}return function(){}}(),i=0,o={},s=new Promise(function(e,t){o.resolve=e,o.reject=t});if(s.abort=function(){a.abort()},(t=[{userAgent:"XMLHttpRequest",lang:"en",type:"GET",data:null,dataType:"json"},_,t].reduce(function(e,t,n){return y.assignDeep(e,t)})).contentType||(t.contentType="GET"===t.type.toUpperCase()?O:k),null==t.crossDomain)try{r=g(t.url),t.crossDomain=!!(r.protocol&&r.protocol!==x.protocol||r.host&&r.host!==x.host)}catch(e){t.crossDomain=!0}t.timeout&&(e=setTimeout(function(){a.abort(),t.timeoutFn&&t.timeoutFn(t.url)},t.timeout)),a.onreadystatechange=function(){try{4===a.readyState?(e&&clearTimeout(e),a.status<300?t.success&&t.success(E(a,t)):t.error&&t.error(a,a.status,a.statusText),t.complete&&t.complete(a,a.statusText),200<=a.status&&a.status<300?o.resolve(E(a,t)):o.reject(E(a,t))):t.progress&&t.progress(++i)}catch(e){o.reject(e)}};var c=t.url,u=null,l=t.type.toUpperCase(),f=t.contentType===k,d="POST"===l||"PUT"===l;!d&&t.data&&(c+="?"+(f?JSON.stringify(t.data):m(t.data))),a.open(l,c);var p=t.crossDomain&&-1!==["GET","POST","HEAD"].indexOf(l);if(n="undefined"!=typeof FormData&&t.data instanceof FormData,d){u=n?t.data:f&&!p?"object"==typeof t.data?JSON.stringify(t.data):t.data:m(t.data);var h=f&&!p?"application/json":"application/x-www-form-urlencoded";a.setRequestHeader("Content-Type",h)}else a.setRequestHeader("Content-Type",t.contentType);if(p||a.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.beforeSend&&t.beforeSend.call(t,a,t),t.xhrFields)for(var v in t.xhrFields)a[v]=t.xhrFields[v];return a.send(u),s},r.exports.ajaxSetup=function(e){_=e||{}}}(0,e,0,n)}),define("can-util/js/is-array-like/is-array-like",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace");n.exports=r.isArrayLike=function(e){var t=typeof e;if("string"===t)return!0;if("number"===t)return!1;var n=e&&"boolean"!==t&&"number"!=typeof e&&"length"in e&&e.length;return"function"!=typeof e&&(0===n||"number"==typeof n&&0<n&&n-1 in e)}}),define("can-util/js/is-iterable/is-iterable",["require","exports","module","can-symbol"],function(e,t,n){"use strict";var r=e("can-symbol");n.exports=function(e){return e&&!!e[r.iterator||r.for("iterator")]}}),define("can-util/js/each/each",["require","exports","module","can-util/js/is-array-like/is-array-like","can-util/js/is-iterable/is-iterable","can-symbol","can-namespace"],function(e,t,n){"use strict";var l=e("can-util/js/is-array-like/is-array-like"),f=Object.prototype.hasOwnProperty,d=e("can-util/js/is-iterable/is-iterable"),p=e("can-symbol"),r=e("can-namespace");n.exports=r.each=function(e,t,n){var r,a,i,o=0;if(e)if(l(e))for(a=e.length;o<a&&(i=e[o],!1!==t.call(n||i,i,o,e));o++);else if(d(e))for(var s,c,u=e[p.iterator||p.for("iterator")]();!(s=u.next()).done;)c=s.value,t.call(n||e,Array.isArray(c)?c[1]:c,c[0]);else if("object"==typeof e)for(r in e)if(f.call(e,r)&&!1===t.call(n||e[r],e[r],r,e))break;return e}}),define("can-make-rest",["require","exports","module","can-util/js/each/each"],function(e,t,n){var a=e("can-util/js/each/each"),i={item:{GET:"getData",PUT:"updateData",DELETE:"destroyData"},list:{GET:"getListData",POST:"createData"}};n.exports=function(e,t){var r={};return a(function(e,t){t=t||function(e){var t=e.match(/\{(.*)\}/);if(t&&2===t.length)return t[1]}(e)||"id";var n=new RegExp("\\/\\{"+t+"\\}.*"),r=n.test(e),a=r?e.replace(n,""):e;return{item:r?e:e.trim()+"/{"+t+"}",list:a}}(e,t),function(n,e){a(i[e],function(e,t){r[e]={method:t,url:n}})}),r}}),define("can-connect/helpers/make-promise",["require","exports","module","can-reflect"],function(e,t,n){var r=e("can-reflect");n.exports=function(n){return n&&"function"==typeof n.then&&!r.isPromise(n)?new Promise(function(e,t){n.then(e,t)}):n}}),define("can-connect/data/url/url",["require","exports","module","can-ajax","can-key/replace-with/replace-with","can-reflect","can-log/dev/dev","can-connect/behavior","can-make-rest","can-connect/helpers/make-promise"],function(e,t,n){"use strict";var l=e("can-ajax"),c=e("can-key/replace-with/replace-with"),f=e("can-reflect"),r=(e("can-log/dev/dev"),e("can-connect/behavior")),d=e("can-make-rest"),a=d("/resource/{id}"),p=e("can-connect/helpers/make-promise"),i=r("data/url",function(u){var e={};return f.eachKey(a,function(s,c){e[c]=function(e){var t=h[c];if("object"==typeof this.url){if("function"==typeof this.url[c])return p(this.url[c](e));if(this.url[c]){var n=y(this.url[c],e,s.method,this.ajax||l,v(this.url,s.method),t);return p(n)}}var r="string"==typeof this.url?this.url:this.url.resource;if(r){var a=f.getSchema(this.queryLogic).identity,i=r.replace(/\/+$/,""),o=d(i,a[0])[c];return p(y(o.url,e,o.method,this.ajax||l,v(this.url,o.method),t))}return u[name].call(this,e)}}),e}),h={getListData:{},getData:{},createData:{},updateData:{},destroyData:{includeData:!1}},v=function(e,t){if("object"==typeof e&&e.contentType&&("application/x-www-form-urlencoded"===e.contentType||"application/json"===e.contentType))return e.contentType;return"GET"===t?"application/x-www-form-urlencoded":"application/json"};function u(e,t){return encodeURIComponent(t)}var y=function(e,t,n,r,a,i){var o={};if("string"==typeof e){var s=e.split(/\s+/);o.url=s.pop(),s.length&&(o.type=s.pop())}else f.assignMap(o,e);return o.data="object"!=typeof t||Array.isArray(t)?t:f.assignMap(o.data||{},t),o.url=c(o.url,o.data,u,!0),o.contentType=a,!1===i.includeData&&delete o.data,r(f.assignMap({type:n||"post",dataType:"json"},o))};n.exports=i}),define("can-diff/index-by-identity/index-by-identity",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var o=e("can-reflect");n.exports=function(e,t,n){var r=o.size(e);if(!n&&0<r&&(n=o.getSchema(e[0])),n||(n=o.getSchema(t)),!n)throw new Error("No schema to use to get identity.");for(var a=o.getIdentity(t,n),i=0;i<r;i++){if(a===o.getIdentity(e[i],n))return i}return-1}}),define("can-connect/real-time/real-time",["require","exports","module","can-connect","can-diff/index-by-identity/index-by-identity","can-log/dev/dev","can-symbol","can-reflect"],function(e,t,n){"use strict";var r=e("can-connect"),s=e("can-diff/index-by-identity/index-by-identity"),a=(e("can-log/dev/dev"),e("can-symbol")),i=e("can-reflect"),c=a.for("can.splice");function u(e,t,n,r){-1===n?-1!==r&&i.splice(e,r,0,[t()]):-1===r?i.splice(e,n,1,[]):r!==n&&(n<r?(i.splice(e,r,0,[t()]),i.splice(e,n,1,[])):(i.splice(e,n,1,[]),i.splice(e,r,0,[t()])))}function l(e,t,n,r,a,i){if(-1===n||r!==n+1&&r!==n)if(void 0!==e[c])u(e,function(){return a.hydrateInstance(t)},n,r);else{var o=a.serializeList(e);u(o,function(){return t},n,r),a.updatedList(e,{data:o},i)}}n.exports=r.behavior("real-time",function(n){var o=Promise.resolve();return{createData:function(){var e=n.createData.apply(this,arguments),t=e.catch(function(){return""});return o=Promise.all([o,t]),e},createInstance:function(a){var i=this;return new Promise(function(r,e){o.then(function(){setTimeout(function(){var e,t=i.id(a),n=i.instanceStore.get(t);n?r(i.updateInstance(a)):(n=i.hydrateInstance(a),e=i.serializeInstance(n),i.addInstanceReference(n),Promise.resolve(i.createdData(a,e)).then(function(){i.deleteInstanceReference(n),r(n)}))},1)})})},createdData:function(e,t,n){var r;r=void 0!==n?this.cidStore.get(n):this.instanceStore.get(this.id(e)),this.addInstanceReference(r,this.id(e)),this.createdInstance(r,e),f.call(this,this.serializeInstance(r)),this.deleteInstanceReference(r)},updatedData:function(e,t){var n=this.instanceStore.get(this.id(t));this.updatedInstance(n,e),d.call(this,this.serializeInstance(n))},updateInstance:function(e){var t=this.id(e),n=this.instanceStore.get(t);n||(n=this.hydrateInstance(e)),this.addInstanceReference(n);var r=this.serializeInstance(n),a=this;return Promise.resolve(this.updatedData(e,r)).then(function(){return a.deleteInstanceReference(n),n})},destroyedData:function(e,t){var n=this.id(t||e),r=this.instanceStore.get(n);r||(r=this.hydrateInstance(e));var a=this.serializeInstance(r);this.destroyedInstance(r,e),p.call(this,a)},destroyInstance:function(e){var t=this.id(e),n=this.instanceStore.get(t);n||(n=this.hydrateInstance(e)),this.addInstanceReference(n);var r=this.serializeInstance(n),a=this;return Promise.resolve(this.destroyedData(e,r)).then(function(){return a.deleteInstanceReference(n),n})}}});var f=function(i){var o=this;this.listStore.forEach(function(e,t){var n=JSON.parse(t),r=s(e,i,o.queryLogic.schema);if(o.queryLogic.isMember(n,i)){var a=o.queryLogic.index(n,e,i);l(e,i,r,a,o,n)}})},d=function(i){var o=this;this.listStore.forEach(function(e,t){var n=JSON.parse(t),r=s(e,i,o.queryLogic.schema);if(o.queryLogic.isMember(n,i)){var a=o.queryLogic.index(n,e,i);l(e,i,r,a,o,n)}else-1!==r&&l(e,i,r,-1,o,n)})},p=function(a){var i=this;this.listStore.forEach(function(e,t){var n=JSON.parse(t),r=s(e,a,i.queryLogic.schema);-1!==r&&l(e,a,r,-1,i,n)})}}),define("can-connect/constructor/callbacks-once/callbacks-once",["require","exports","module","can-connect","can-connect/helpers/sorted-set-json"],function(e,t,n){"use strict";var r=e("can-connect"),s=e("can-connect/helpers/sorted-set-json"),a=[].forEach,i=["createdInstance","updatedInstance","destroyedInstance"],o=r.behavior("constructor/callbacks-once",function(o){var e={};return a.call(i,function(i){e[i]=function(e,t){var n=this.getInstanceMetaData(e,"last-data-"+i),r=s(t);if(n!==r){var a=o[i].apply(this,arguments);return this.addInstanceMetaData(e,"last-data-"+i,r),a}}}),e});n.exports=o}),define("can-realtime-rest-model",["require","exports","module","can-connect","can-connect/constructor/constructor","can-connect/can/map/map","can-connect/constructor/store/store","can-connect/data/callbacks/callbacks","can-connect/data/parse/parse","can-connect/data/url/url","can-connect/real-time/real-time","can-connect/constructor/callbacks-once/callbacks-once","can-namespace"],function(e,t,n){var r=e("can-connect"),a=e("can-connect/constructor/constructor"),i=e("can-connect/can/map/map"),o=e("can-connect/constructor/store/store"),s=e("can-connect/data/callbacks/callbacks"),c=e("can-connect/data/parse/parse"),u=e("can-connect/data/url/url"),l=e("can-connect/real-time/real-time"),f=e("can-connect/constructor/callbacks-once/callbacks-once"),d=e("can-namespace");n.exports=d.realtimeRestModel=function(e){return r([a,i,o,s,c,u,l,f],e)}}),define("can/es/can-realtime-rest-model",["exports","can-realtime-rest-model"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-rest-model",["require","exports","module","can-connect/constructor/constructor","can-connect/can/map/map","can-connect/data/parse/parse","can-connect/data/url/url","can-namespace","can-connect/base/base"],function(e,t,n){var r=e("can-connect/constructor/constructor"),a=e("can-connect/can/map/map"),i=e("can-connect/data/parse/parse"),o=e("can-connect/data/url/url"),s=e("can-namespace"),c=e("can-connect/base/base");n.exports=s.restModel=function(e){var t=[c,o,i,r,a].reduce(function(e,t){return t(e)},e);return t.init(),t}}),define("can/es/can-rest-model",["exports","can-rest-model"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-connect/helpers/get-items",function(e,t,n){"use strict";n.exports=function(e){return Array.isArray(e)?e:e.data}}),define("can-connect/cache-requests/cache-requests",["require","exports","module","can-connect","can-connect/helpers/get-items"],function(e,t,n){var r=e("can-connect"),u=e("can-connect/helpers/get-items"),s=Array.prototype.forEach,a=r.behavior("cache-requests",function(c){return{getDiff:function(a,e){var i,o=this;return s.call(e,function(e){var t,n=o.queryLogic.difference(a,e);if(o.queryLogic.isDefinedAndHasMembers(n)){var r=o.queryLogic.intersection(a,e);t={needed:n,cached:!!o.queryLogic.isDefinedAndHasMembers(r)&&r,count:o.queryLogic.count(n)}}else o.queryLogic.isSubset(a,e)&&(t={cached:a,count:0});t&&(!i||t.count<i.count)&&(i=t)}),i?{needed:i.needed,cached:i.cached}:{needed:a}},unionMembers:function(e,t,n,r){return{data:this.queryLogic.unionMembers(t.needed,t.cached,u(n),u(r))}},getListData:function(o){o=o||{};var s=this;return this.cacheConnection.getSets(o).then(function(e){var r=s.getDiff(o,e);if(r.needed){if(r.cached){var t=s.cacheConnection.getListData(r.cached),n=c.getListData(r.needed),a=n.then(function(e){return s.cacheConnection.updateListData(u(e),r.needed).then(function(){return e})}),i=Promise.all([t,n]).then(function(e){var t=e[0],n=e[1];return s.unionMembers(o,r,n,t)});return Promise.all([i,a]).then(function(e){return e[0]})}return c.getListData(r.needed).then(function(e){return s.cacheConnection.updateListData(u(e),r.needed).then(function(){return e})})}return s.cacheConnection.getListData(r.cached)})}}});n.exports=a}),define("can-connect/data/callbacks-cache/callbacks-cache",["require","exports","module","can-connect","can-reflect","can-reflect"],function(e,t,n){"use strict";var r=e("can-connect"),o=e("can-reflect").assignMap,a=e("can-reflect").each,s={createdData:"createData",updatedData:"updateData",destroyedData:"destroyData"},i=r.behavior("data/callbacks-cache",function(i){var e={};return a(s,function(r,a){e[a]=function(e,t,n){return this.cacheConnection[r](o(o({},t),e)),i[a]?i[a].call(this,e,t,n):e}}),e});n.exports=i}),define("can-connect/helpers/deferred",function(e,t,n){"use strict";n.exports=function(){var n={};return n.promise=new Promise(function(e,t){n.resolve=e,n.reject=t}),n}}),define("can-connect/data/combine-requests/combine-requests",["require","exports","module","can-connect","can-connect/helpers/get-items","can-reflect","can-connect/helpers/deferred"],function(e,t,n){var r=e("can-connect"),i=e("can-connect/helpers/get-items"),o=e("can-reflect"),s=e("can-connect/helpers/deferred"),c=[].forEach,a=r.behavior("data/combine-requests",function(a){var n;return{unionPendingRequests:function(e){var n=this;e.sort(function(e,t){return n.queryLogic.isSubset(e.set,t.set)?1:n.queryLogic.isSubset(t.set,e.set)?-1:0});var r,t=[];return u(e,{start:function(e){r={set:e.set,pendingRequests:[e]},t.push(r)},iterate:function(e){var t=n.queryLogic.union(r.set,e.set);if(n.queryLogic.isDefinedAndHasMembers(t))return r.set=t,r.pendingRequests.push(e),!0}}),Promise.resolve(t)},time:1,getListData:function(e){e=e||{};var r=this;n||(n=[],setTimeout(function(){var e=r.unionPendingRequests(n);n=null,e.then(function(e){c.call(e,function(n){var e=o.serialize(n.set);a.getListData(e).then(function(t){1===n.pendingRequests.length?n.pendingRequests[0].deferred.resolve(t):c.call(n.pendingRequests,function(e){e.deferred.resolve({data:r.queryLogic.filterMembers(e.set,n.set,i(t))})})},function(t){1===n.pendingRequests.length?n.pendingRequests[0].deferred.reject(t):c.call(n.pendingRequests,function(e){e.deferred.reject(t)})})})})},this.time||1));var t=s();return n.push({deferred:t,set:e}),t.promise}}});n.exports=a;var u=function(e,t){for(var n=0;n<e.length;){t.start(e[n]);for(var r=n+1;r<e.length;)!0===t.iterate(e[r])?e.splice(r,1):r++;n++}}}),define("can-local-store",["require","exports","module","can-reflect","can-memory-store/make-simple-store","can-namespace"],function(e,t,n){var r=e("can-reflect"),a=e("can-memory-store/make-simple-store"),i=e("can-namespace");n.exports=i.localStore=function e(t){t.constructor=e;var n=Object.create(a(t));return r.assignMap(n,{clear:function(){return localStorage.removeItem(this.name+"/queries"),localStorage.removeItem(this.name+"/records"),this._recordsMap=null,Promise.resolve()},updateQueryDataSync:function(e){localStorage.setItem(this.name+"/queries",JSON.stringify(e))},getQueryDataSync:function(){return JSON.parse(localStorage.getItem(this.name+"/queries"))||[]},getRecord:function(e){return this._recordsMap||this.getAllRecords(),this._recordsMap[e]},getAllRecords:function(){if(!this.cacheLocalStorageReads||!this._recordsMap){var e=JSON.parse(localStorage.getItem(this.name+"/records"))||{};this._recordsMap=e}var t=[];for(var n in this._recordsMap)t.push(this._recordsMap[n]);return t},destroyRecords:function(e){this._recordsMap||this.getAllRecords(),r.eachIndex(e,function(e){var t=r.getIdentity(e,this.queryLogic.schema);delete this._recordsMap[t]},this),localStorage.setItem(this.name+"/records",JSON.stringify(this._recordsMap))},updateRecordsSync:function(e){this._recordsMap||this.getAllRecords(),e.forEach(function(e){var t=r.getIdentity(e,this.queryLogic.schema);this._recordsMap[t]=e},this),localStorage.setItem(this.name+"/records",JSON.stringify(this._recordsMap))}}),n}}),define("can-connect/data/localstorage-cache/localstorage-cache",["require","exports","module","can-local-store"],function(e,t,n){"use strict";n.exports=e("can-local-store")}),define("can-connect/data/memory-cache/memory-cache",["require","exports","module","can-memory-store"],function(e,t,n){"use strict";var r=e("can-memory-store");n.exports=r}),define("can-connect/fall-through-cache/fall-through-cache",["require","exports","module","can-connect","can-connect/helpers/sorted-set-json","can-log"],function(e,t,n){"use strict";var r=e("can-connect"),i=e("can-connect/helpers/sorted-set-json"),o=e("can-log"),a=r.behavior("fall-through-cache",function(a){return{hydrateList:function(e,t){t=t||this.listQuery(e);var n=i(t),r=a.hydrateList.call(this,e,t);return this._getHydrateListCallbacks[n]&&(this._getHydrateListCallbacks[n].shift()(r),this._getHydrateListCallbacks[n].length||delete this._getHydrateListCallbacks[n]),r},_getHydrateListCallbacks:{},_getHydrateList:function(e,t){var n=i(e);this._getHydrateListCallbacks[n]||(this._getHydrateListCallbacks[n]=[]),this._getHydrateListCallbacks[n].push(t)},getListData:function(n){n=n||{};var r=this;return this.cacheConnection.getListData(n).then(function(e){return r._getHydrateList(n,function(t){r.addListReference(t,n),setTimeout(function(){a.getListData.call(r,n).then(function(e){r.cacheConnection.updateListData(e,n),r.updatedList(t,e,n),r.deleteListReference(t,n)},function(e){o.log("REJECTED",e)})},1)}),e},function(){var e=a.getListData.call(r,n);return e.then(function(e){r.cacheConnection.updateListData(e,n)}),e})},hydrateInstance:function(e){var t=this.id(e),n=a.hydrateInstance.apply(this,arguments);return this._getMakeInstanceCallbacks[t]&&(this._getMakeInstanceCallbacks[t].shift()(n),this._getMakeInstanceCallbacks[t].length||delete this._getMakeInstanceCallbacks[t]),n},_getMakeInstanceCallbacks:{},_getMakeInstance:function(e,t){this._getMakeInstanceCallbacks[e]||(this._getMakeInstanceCallbacks[e]=[]),this._getMakeInstanceCallbacks[e].push(t)},getData:function(n){var r=this;return this.cacheConnection.getData(n).then(function(e){return r._getMakeInstance(r.id(e)||r.id(n),function(t){r.addInstanceReference(t),setTimeout(function(){a.getData.call(r,n).then(function(e){r.cacheConnection.updateData(e),r.updatedInstance(t,e),r.deleteInstanceReference(t)},function(e){o.log("REJECTED",e)})},1)}),e},function(){var e=a.getData.call(r,n);return e.then(function(e){r.cacheConnection.updateData(e)}),e})}}});n.exports=a}),define("can-connect/can/ref/ref",["require","exports","module","can-connect","can-connect/helpers/weak-reference-map","can-observation-recorder","can-connect/constructor/store/store","can-define","can-reflect"],function(e,t,n){"use strict";var r=e("can-connect"),o=e("can-connect/helpers/weak-reference-map"),s=e("can-observation-recorder"),c=e("can-connect/constructor/store/store"),u=e("can-define"),l=e("can-reflect");n.exports=r.behavior("can/ref",function(e){return{init:function(){e.init.apply(this,arguments),this.Map.Ref=function(r){var a=l.getSchema(r.queryLogic).identity[0],i=function(e,t){"object"==typeof e&&(e=(t=e)[a]);var n=i.store.get(e);if(n)return t&&!n._value&&(t instanceof r.Map?n._value=t:n._value=r.hydrateInstance(t)),n;this[a]=e,t&&(t instanceof r.Map?this._value=t:this._value=r.hydrateInstance(t)),0<c.requests.count()&&(i._requestInstances[e]||(i.store.addReference(e,this),i._requestInstances[e]=this))};i.store=new o,i._requestInstances={},i.type=function(e){return e&&"object"!=typeof e?new i(e):new i(e[a],e)};var e={promise:{get:function(){if(this._value)return Promise.resolve(this._value);var e={};return e[a]=this[a],r.Map.get(e)}},_state:{get:function(e,t){return t&&this.promise.then(function(){t("resolved")},function(){t("rejected")}),"pending"}},value:{get:function(e,t){if(this._value)return this._value;t&&this.promise.then(function(e){t(e)})}},reason:{get:function(e,t){this._value||this.promise.catch(function(e){t(e)})}}};e[a]={type:"*",set:function(){this._value=void 0}},u(i.prototype,e),i.prototype.unobservedId=s.ignore(function(){return this[a]}),i.prototype.isResolved=function(){return!!this._value||"resolved"===this._state},i.prototype.isRejected=function(){return"rejected"===this._state},i.prototype.isPending=function(){return!this._value&&("resolved"!==this._state||"rejected"!==this._state)},i.prototype.serialize=function(){return this[a]},l.assignSymbols(i.prototype,{"can.serialize":i.prototype.serialize,"can.getName":function(){return l.getName(this.constructor)+"{"+this[a]+"}"}});var t=i.prototype._eventSetup;i.prototype._eventSetup=function(){return i.store.addReference(this.unobservedId(),this),t.apply(this,arguments)};var n=i.prototype._eventTeardown;return i.prototype._eventTeardown=function(){return i.store.deleteReference(this.unobservedId(),this),n.apply(this,arguments)},c.requests.on("end",function(){for(var e in i._requestInstances)i.store.deleteReference(e);i._requestInstances={}}),i}(this)}}})}),define("can-connect/can/super-map/super-map",["require","exports","module","can-connect","can-connect/constructor/constructor","can-connect/can/map/map","can-connect/can/ref/ref","can-connect/constructor/store/store","can-connect/data/callbacks/callbacks","can-connect/data/callbacks-cache/callbacks-cache","can-connect/data/combine-requests/combine-requests","can-connect/data/localstorage-cache/localstorage-cache","can-connect/data/parse/parse","can-connect/data/url/url","can-connect/fall-through-cache/fall-through-cache","can-connect/real-time/real-time","can-connect/constructor/callbacks-once/callbacks-once","can-globals/global/global"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("can-connect"),i=t("can-connect/constructor/constructor"),o=t("can-connect/can/map/map"),s=t("can-connect/can/ref/ref"),c=t("can-connect/constructor/store/store"),u=t("can-connect/data/callbacks/callbacks"),l=t("can-connect/data/callbacks-cache/callbacks-cache"),f=t("can-connect/data/combine-requests/combine-requests"),d=t("can-connect/data/localstorage-cache/localstorage-cache"),p=t("can-connect/data/parse/parse"),h=t("can-connect/data/url/url"),v=t("can-connect/fall-through-cache/fall-through-cache"),y=t("can-connect/real-time/real-time"),g=t("can-connect/constructor/callbacks-once/callbacks-once"),m=t("can-globals/global/global")().$;a.superMap=function(e){var t=[i,o,s,c,u,f,p,h,y,g];return"undefined"!=typeof localStorage&&(e.cacheConnection||(e.cacheConnection=a([d],{name:e.name+"Cache",idProp:e.idProp,queryLogic:e.queryLogic})),t.push(l,v)),m&&m.ajax&&(e.ajax=m.ajax),a(t,e)},r.exports=a.superMap}(0,e,0,n)}),define("can-connect/can/base-map/base-map",["require","exports","module","can-connect","can-connect/constructor/constructor","can-connect/can/map/map","can-connect/can/ref/ref","can-connect/constructor/store/store","can-connect/data/callbacks/callbacks","can-connect/data/callbacks-cache/callbacks-cache","can-connect/data/parse/parse","can-connect/data/url/url","can-connect/real-time/real-time","can-connect/constructor/callbacks-once/callbacks-once","can-globals/global/global"],function(e,t,n){var r,a,i,o,s,c,u,l,f,d,p,h,v;a=n,i=(r=e)("can-connect"),o=r("can-connect/constructor/constructor"),s=r("can-connect/can/map/map"),c=r("can-connect/can/ref/ref"),u=r("can-connect/constructor/store/store"),l=r("can-connect/data/callbacks/callbacks"),r("can-connect/data/callbacks-cache/callbacks-cache"),f=r("can-connect/data/parse/parse"),d=r("can-connect/data/url/url"),p=r("can-connect/real-time/real-time"),h=r("can-connect/constructor/callbacks-once/callbacks-once"),v=r("can-globals/global/global")().$,i.baseMap=function(e){var t=[o,s,c,u,l,f,d,p,h];return v&&v.ajax&&(e.ajax=v.ajax),i(t,e)},a.exports=i.baseMap}),define("can-connect/all",["require","exports","module","can-connect","can-connect/cache-requests/cache-requests","can-connect/constructor/constructor","can-connect/constructor/callbacks-once/callbacks-once","can-connect/constructor/store/store","can-connect/data/callbacks/callbacks","can-connect/data/callbacks-cache/callbacks-cache","can-connect/data/combine-requests/combine-requests","can-connect/data/localstorage-cache/localstorage-cache","can-connect/data/memory-cache/memory-cache","can-connect/data/parse/parse","can-connect/data/url/url","can-connect/fall-through-cache/fall-through-cache","can-connect/real-time/real-time","can-connect/can/super-map/super-map","can-connect/can/base-map/base-map"],function(e,t,n){"use strict";var r=e("can-connect");r.cacheRequests=e("can-connect/cache-requests/cache-requests"),r.constructor=e("can-connect/constructor/constructor"),r.constructorCallbacksOnce=e("can-connect/constructor/callbacks-once/callbacks-once"),r.constructorStore=e("can-connect/constructor/store/store"),r.dataCallbacks=e("can-connect/data/callbacks/callbacks"),r.dataCallbacksCache=e("can-connect/data/callbacks-cache/callbacks-cache"),r.dataCombineRequests=e("can-connect/data/combine-requests/combine-requests"),r.dataLocalStorageCache=e("can-connect/data/localstorage-cache/localstorage-cache"),r.dataMemoryCache=e("can-connect/data/memory-cache/memory-cache"),r.dataParse=e("can-connect/data/parse/parse"),r.dataUrl=e("can-connect/data/url/url"),r.fallThroughCache=e("can-connect/fall-through-cache/fall-through-cache"),r.realTime=e("can-connect/real-time/real-time"),r.superMap=e("can-connect/can/super-map/super-map"),r.baseMap=e("can-connect/can/base-map/base-map"),n.exports=r}),define("can/es/can-connect",["exports","can-connect/all"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-local-store",["exports","can-local-store"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-memory-store",["exports","can-memory-store"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-route",["exports","can-route"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-route-hash",["exports","can-route-hash"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-route-pushstate",["require","exports","module","can-route","can-route/src/binding-proxy","can-reflect","can-symbol","can-simple-observable","can-observation-recorder","can-globals/is-node/is-node","can-globals/location/location","can-globals/document/document","can-globals/global/global","can-dom-events","can-diff/map/map"],function(e,t,n){!function(e,t,n,r){"use strict";var o=t("can-route"),i=t("can-route/src/binding-proxy"),a=t("can-reflect"),s=t("can-symbol"),c=t("can-simple-observable"),u=t("can-observation-recorder"),l=t("can-globals/is-node/is-node"),f=t("can-globals/location/location"),d=t("can-globals/document/document"),p=t("can-globals/global/global"),h=t("can-dom-events"),v=t("can-diff/map/map"),y=["pushState","replaceState"],g=s.for("can.dispatch");function m(){var e=f(),t=e.protocol+"//"+e.host,n=i.call("root");return 0===n.indexOf(t)?n.substr(t.length):n}function b(){var e=m(),t=f(),n=t.pathname+t.search,r=n.indexOf(e);return n.substr(r+e.length)}function w(){this.replaceStateOnceKeys=[],this.replaceStateKeys=[],this.dispatchHandlers=this.dispatchHandlers.bind(this),this.anchorClickHandler=function(e){w.prototype.anchorClickHandler.call(this,this,e)},this.keepHash=!0}w.prototype=Object.create(c.prototype),w.constructor=w,a.assign(w.prototype,{root:"/",matchSlashes:!1,paramsMatcher:/^\?(?:[^=]+=[^&]*&)*[^=]+=[^&]*/,querySeparator:"?",dispatchHandlers:function(){var e=this._value;this._value=b(),e!==this._value&&this[g](this._value,e)},anchorClickHandler:function(e,t){if(!(t.isDefaultPrevented?t.isDefaultPrevented():!0===t.defaultPrevented)){if("javascript://"===e.href)return;if("_blank"===e.target)return;if(t.altKey||t.ctrlKey||t.metaKey||t.shiftKey)return;var n=e.host||window.location.host;if(window.location.host===n){var r=m();if(0===e.pathname.indexOf(r)){var a=e.pathname+e.search,i=a.substr(r.length);if(void 0!==o.rule(i))0<=e.href.indexOf("#")&&(this.keepHash=!0),(a!==window.location.pathname+window.location.search||e.hash===window.location.hash)&&t.preventDefault&&t.preventDefault(),window.history.pushState(null,null,e.href)}}}},onBound:function(){if(!l()){var e=d(),s=p();this._value=b(),h.addDelegateListener(e.documentElement,"click","a",this.anchorClickHandler);var c=this.originalMethods={},u=this.dispatchHandlers;a.eachKey(y,function(o){this.originalMethods[o]=s.history[o],s.history[o]=function(e,t,n){var r=0===n.indexOf("http"),a=f(),i=a.search+a.hash;(!r&&n!==a.pathname+i||r&&n!==a.href+i)&&(c[o].apply(s.history,arguments),u())}},this),h.addEventListener(s,"popstate",this.dispatchHandlers)}},onUnbound:function(){if(!l()){var e=d(),t=p();h.removeDelegateListener(e.documentElement,"click","a",this.anchorClickHandler),a.eachKey(y,function(e){t.history[e]=this.originalMethods[e]},this),h.removeEventListener(t,"popstate",this.dispatchHandlers)}},get:function(){return u.add(this),b()},set:function(e){var t=o.deparam(e),n=o.deparam(b()),r="pushState",a={};this.keepHash&&-1===e.indexOf("#")&&window.location.hash&&(e+=window.location.hash),v(n,t).forEach(function(e){return a[e.key]=!0}),this.replaceStateKeys.length&&this.replaceStateKeys.forEach(function(e){a[e]&&(r="replaceState")}),this.replaceStateOnceKeys.length&&this.replaceStateOnceKeys.forEach(function(e,t,n){a[e]&&(r="replaceState",n.splice(t,1))}),window.history[r](null,null,i.call("root")+e)},replaceStateOn:function(){a.addValues(this.replaceStateKeys,a.toArray(arguments))},replaceStateOnce:function(){a.addValues(this.replaceStateOnceKeys,a.toArray(arguments))},replaceStateOff:function(){a.removeValues(this.replaceStateKeys,a.toArray(arguments)),a.removeValues(this.replaceStateOnceKeys,a.toArray(arguments))}}),a.assignSymbols(w.prototype,{"can.getValue":w.prototype.get,"can.setValue":w.prototype.set}),r.exports=w}(0,e,0,n)}),define("can/es/can-route-pushstate",["exports","can-route-pushstate"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-param",["exports","can-param"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-deparam",["exports","can-deparam"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-assign",["exports","can-assign"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-define-lazy-value",["exports","can-define-lazy-value"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-diff/deep/deep",["require","exports","module","can-diff/map/map","can-diff/list/list","can-reflect"],function(e,t,n){"use strict";var a=e("can-diff/map/map"),i=e("can-diff/list/list"),f=e("can-reflect");function o(e,t,a,i){var n,o,r=f.getSchema(e),s=f.size(e);return null!=r&&null!=r.values&&(n=f.getSchema(r.values)),null==n&&0<s&&(n=f.getSchema(f.getKeyValue(e,0))),n&&(o=function(n){if(n.identity&&n.identity.length)return function(e,t){return f.getIdentity(e,n)===f.getIdentity(t,n)}}(n)),function(e,t,n){if(f.isPrimitive(e))return e===t;if(f.isPrimitive(t))return e===t;if(o&&o(e,t)){var r=d(e,t,a?a+"."+n:""+n);return i.push.apply(i,r),!0}return 0===d(e,t).length}}function d(s,c,u){if(s&&f.isMoreListLikeThanMapLike(s)){var e=[],t=o(s,0,u,e),n=i(s,c,t).map(function(e){return u&&(e.key=u),e});return e.concat(n)}u=u?u+".":"";var r=a(s,c),l=[];return r.forEach(function(e){var t=e.key;e.key=u+e.key;var n,r,a=s&&f.getKeyValue(s,t),i=c&&f.getKeyValue(c,t);if(n=a,r=i,"set"===e.type&&n&&r&&"object"==typeof n&&"object"==typeof r){var o=d(a,i,e.key);l.push.apply(l,o)}else l.push(e)}),l}n.exports=d}),define("can-diff",["require","exports","module","can-diff/deep/deep","can-diff/list/list","can-diff/map/map","can-diff/merge-deep/merge-deep","can-diff/patcher/patcher","can-namespace"],function(e,t,n){"use strict";var r=e("can-diff/deep/deep"),a=e("can-diff/list/list"),i=e("can-diff/map/map"),o=e("can-diff/merge-deep/merge-deep"),s=e("can-diff/patcher/patcher"),c=e("can-namespace"),u={deep:r,list:a,map:i,mergeDeep:o,Patcher:s};n.exports=c.diff=u}),define("can/es/can-diff",["exports","can-diff"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-globals",["exports","can-globals"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-key",["exports","can-key"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-key-tree",["exports","can-key-tree"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-make-map",function(e,t,n){"use strict";n.exports=function(e){var t={};return e.split(",").forEach(function(e){t[e]=!0}),t}}),define("can/es/can-make-map",["exports","can-make-map"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-parse-uri",["exports","can-parse-uri"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-queues",["exports","can-queues"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-string",["exports","can-string"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-string-to-any",["exports","can-string-to-any"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-ajax",["exports","can-ajax"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-attribute-encoder",["exports","can-attribute-encoder"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-child-nodes",["exports","can-child-nodes"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-control",["exports","can-control"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-dom-events",["exports","can-dom-events"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-dom-mutate/events/events",["require","exports","module","can-dom-mutate","can-namespace"],function(e,t,n){"use strict";var r=e("can-dom-mutate"),a=e("can-namespace");function i(e,n,o){var s=new Map;return{_subscriptions:s,defaultEventType:e,addEventListener:function(r,a,e){var i=this.dispatch,t=s.get(r);t||(t={removeListener:null,listeners:new Set},s.set(r,t)),0===t.listeners.size&&(t.removeListener=n(r,function(e){var t={type:a};for(var n in e)t[n]=e[n];i(r,t,!1!==o)})),t.listeners.add(e),r.addEventListener(a,e)},removeEventListener:function(e,t,n){e.removeEventListener(t,n);var r=s.get(e);r&&(r.listeners.delete(n),0===r.listeners.size&&(r.removeListener(),s.delete(e)))}}}n.exports=a.domMutateDomEvents={attributes:i("attributes",r.onNodeAttributeChange),inserted:i("inserted",r.onNodeInsertion,!1),removed:i("removed",r.onNodeRemoval)}}),define("can-dom-mutate/dom-events",["require","exports","module","can-namespace","can-dom-mutate/events/events"],function(e,t,n){"use strict";var r=e("can-namespace"),a=e("can-dom-mutate/events/events");n.exports=r.domMutateDomEvents=a}),define("can/es/can-dom-mutate",["exports","can-dom-mutate","can-dom-mutate/node","can-dom-mutate/dom-events"],function(e,t,n,r){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return a(t).default}}),Object.defineProperty(e,"domMutateNode",{enumerable:!0,get:function(){return a(n).default}}),Object.defineProperty(e,"domMutateDomEvents",{enumerable:!0,get:function(){return a(r).default}})}),define("can/es/can-fragment",["exports","can-fragment"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-validate-interface",["exports","can-validate-interface"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-data-types",["exports","can-data-types/maybe-boolean/maybe-boolean","can-data-types/maybe-date/maybe-date","can-data-types/maybe-number/maybe-number","can-data-types/maybe-string/maybe-string"],function(e,t,n,r,a){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"MaybeBoolean",{enumerable:!0,get:function(){return i(t).default}}),Object.defineProperty(e,"MaybeDate",{enumerable:!0,get:function(){return i(n).default}}),Object.defineProperty(e,"MaybeNumber",{enumerable:!0,get:function(){return i(r).default}}),Object.defineProperty(e,"MaybeString",{enumerable:!0,get:function(){return i(a).default}})}),define("can/es/can-namespace",["exports","can-namespace"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-reflect",["exports","can-reflect"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-reflect-dependencies",["exports","can-reflect-dependencies"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-reflect-promise",["exports","can-reflect-promise"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/core",["exports","can/es/can-define","can/es/can-value","can/es/can-observation","can/es/can-observation-recorder","can/es/can-simple-map","can/es/can-bind","can/es/can-event-queue","can/es/can-simple-observable","can/es/can-component","can/es/can-stache","can/es/can-stache-bindings","can/es/can-stache-route-helpers","can/es/can-view-callbacks","can/es/can-view-live","can/es/can-view-model","can/es/can-view-nodelist","can/es/can-view-parser","can/es/can-view-scope","can/es/can-view-target","can/es/can-fixture","can/es/can-query-logic","can/es/can-realtime-rest-model","can/es/can-rest-model","can/es/can-connect","can/es/can-local-store","can/es/can-memory-store","can/es/can-route","can/es/can-route-hash","can/es/can-route-pushstate","can/es/can-param","can/es/can-deparam","can/es/can-assign","can/es/can-define-lazy-value","can/es/can-diff","can/es/can-globals","can/es/can-key","can/es/can-key-tree","can/es/can-make-map","can/es/can-parse-uri","can/es/can-queues","can/es/can-string","can/es/can-string-to-any","can/es/can-ajax","can/es/can-attribute-encoder","can/es/can-child-nodes","can/es/can-control","can/es/can-dom-events","can/es/can-dom-mutate","can/es/can-fragment","can/es/can-validate-interface","can-cid","can-construct","can/es/can-data-types","can/es/can-namespace","can/es/can-reflect","can/es/can-reflect-dependencies","can/es/can-reflect-promise"],function(e,t,n,r,a,i,o,s,c,u,l,f,d,p,h,v,y,g,m,b,w,x,_,k,O,E,L,q,S,M,P,C,V,j,D,I,T,A,N,K,R,B,H,F,z,U,G,W,Y,$,Q,J,X,Z,ee,te,ne,re){"use strict";function ae(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"define",{enumerable:!0,get:function(){return t.define}}),Object.defineProperty(e,"DefineMap",{enumerable:!0,get:function(){return t.DefineMap}}),Object.defineProperty(e,"DefineList",{enumerable:!0,get:function(){return t.DefineList}}),Object.defineProperty(e,"value",{enumerable:!0,get:function(){return ae(n).default}}),Object.defineProperty(e,"Observation",{enumerable:!0,get:function(){return ae(r).default}}),Object.defineProperty(e,"ObservationRecorder",{enumerable:!0,get:function(){return ae(a).default}}),Object.defineProperty(e,"SimpleMap",{enumerable:!0,get:function(){return ae(i).default}}),Object.defineProperty(e,"bind",{enumerable:!0,get:function(){return ae(o).default}}),Object.defineProperty(e,"mapEventBindings",{enumerable:!0,get:function(){return s.mapEventBindings}}),Object.defineProperty(e,"valueEventBindings",{enumerable:!0,get:function(){return s.valueEventBindings}}),Object.defineProperty(e,"SimpleObservable",{enumerable:!0,get:function(){return ae(c).default}}),Object.defineProperty(e,"Component",{enumerable:!0,get:function(){return ae(u).default}}),Object.defineProperty(e,"stache",{enumerable:!0,get:function(){return ae(l).default}}),Object.defineProperty(e,"stacheBindings",{enumerable:!0,get:function(){return ae(f).default}}),Object.defineProperty(e,"stacheRouteHelpers",{enumerable:!0,get:function(){return ae(d).default}}),Object.defineProperty(e,"viewCallbacks",{enumerable:!0,get:function(){return ae(p).default}}),Object.defineProperty(e,"viewLive",{enumerable:!0,get:function(){return ae(h).default}}),Object.defineProperty(e,"viewModel",{enumerable:!0,get:function(){return ae(v).default}}),Object.defineProperty(e,"nodeList",{enumerable:!0,get:function(){return ae(y).default}}),Object.defineProperty(e,"viewParser",{enumerable:!0,get:function(){return ae(g).default}}),Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return ae(m).default}}),Object.defineProperty(e,"target",{enumerable:!0,get:function(){return ae(b).default}}),Object.defineProperty(e,"fixture",{enumerable:!0,get:function(){return ae(w).default}}),Object.defineProperty(e,"QueryLogic",{enumerable:!0,get:function(){return ae(x).default}}),Object.defineProperty(e,"realtimeRestModel",{enumerable:!0,get:function(){return ae(_).default}}),Object.defineProperty(e,"restModel",{enumerable:!0,get:function(){return ae(k).default}}),Object.defineProperty(e,"connect",{enumerable:!0,get:function(){return ae(O).default}}),Object.defineProperty(e,"localStore",{enumerable:!0,get:function(){return ae(E).default}}),Object.defineProperty(e,"memoryStore",{enumerable:!0,get:function(){return ae(L).default}}),Object.defineProperty(e,"route",{enumerable:!0,get:function(){return ae(q).default}}),Object.defineProperty(e,"RouteHash",{enumerable:!0,get:function(){return ae(S).default}}),Object.defineProperty(e,"RoutePushstate",{enumerable:!0,get:function(){return ae(M).default}}),Object.defineProperty(e,"param",{enumerable:!0,get:function(){return ae(P).default}}),Object.defineProperty(e,"deparam",{enumerable:!0,get:function(){return ae(C).default}}),Object.defineProperty(e,"assign",{enumerable:!0,get:function(){return ae(V).default}}),Object.defineProperty(e,"defineLazyValue",{enumerable:!0,get:function(){return ae(j).default}}),Object.defineProperty(e,"diff",{enumerable:!0,get:function(){return ae(D).default}}),Object.defineProperty(e,"globals",{enumerable:!0,get:function(){return ae(I).default}}),Object.defineProperty(e,"key",{enumerable:!0,get:function(){return ae(T).default}}),Object.defineProperty(e,"KeyTree",{enumerable:!0,get:function(){return ae(A).default}}),Object.defineProperty(e,"makeMap",{enumerable:!0,get:function(){return ae(N).default}}),Object.defineProperty(e,"parseURI",{enumerable:!0,get:function(){return ae(K).default}}),Object.defineProperty(e,"queues",{enumerable:!0,get:function(){return ae(R).default}}),Object.defineProperty(e,"string",{enumerable:!0,get:function(){return ae(B).default}}),Object.defineProperty(e,"stringToAny",{enumerable:!0,get:function(){return ae(H).default}}),Object.defineProperty(e,"ajax",{enumerable:!0,get:function(){return ae(F).default}}),Object.defineProperty(e,"attributeEncoder",{enumerable:!0,get:function(){return ae(z).default}}),Object.defineProperty(e,"childNodes",{enumerable:!0,get:function(){return ae(U).default}}),Object.defineProperty(e,"Control",{enumerable:!0,get:function(){return ae(G).default}}),Object.defineProperty(e,"domEvents",{enumerable:!0,get:function(){return ae(W).default}}),Object.defineProperty(e,"domMutate",{enumerable:!0,get:function(){return ae(Y).default}}),Object.defineProperty(e,"domMutateNode",{enumerable:!0,get:function(){return Y.domMutateNode}}),Object.defineProperty(e,"domMutateDomEvents",{enumerable:!0,get:function(){return Y.domMutateDomEvents}}),Object.defineProperty(e,"fragment",{enumerable:!0,get:function(){return ae($).default}}),Object.defineProperty(e,"makeInterfaceValidator",{enumerable:!0,get:function(){return ae(Q).default}}),Object.defineProperty(e,"cid",{enumerable:!0,get:function(){return ae(J).default}}),Object.defineProperty(e,"Construct",{enumerable:!0,get:function(){return ae(X).default}}),Object.defineProperty(e,"MaybeBoolean",{enumerable:!0,get:function(){return Z.MaybeBoolean}}),Object.defineProperty(e,"MaybeDate",{enumerable:!0,get:function(){return Z.MaybeDate}}),Object.defineProperty(e,"MaybeNumber",{enumerable:!0,get:function(){return Z.MaybeNumber}}),Object.defineProperty(e,"MaybeString",{enumerable:!0,get:function(){return Z.MaybeString}}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return ae(ee).default}}),Object.defineProperty(e,"can",{enumerable:!0,get:function(){return ae(ee).default}}),Object.defineProperty(e,"Reflect",{enumerable:!0,get:function(){return ae(te).default}}),Object.defineProperty(e,"reflectDependencies",{enumerable:!0,get:function(){return ae(ne).default}}),Object.defineProperty(e,"reflectPromise",{enumerable:!0,get:function(){return ae(re).default}})}),define("can-define-backup",["require","exports","module","can-reflect","can-simple-observable","can-diff/deep/deep","can-diff/map/map"],function(e,t,n){"use strict";var i=e("can-reflect"),r=e("can-simple-observable"),o=e("can-diff/deep/deep"),s=e("can-diff/map/map"),a=new WeakMap;function c(e){var t=a.get(e);return t||(t=new r,a.set(e,t)),t}n.exports=function(e){return function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!1,configurable:!0,writable:!0,value:t[n]})}(e.prototype,{backup:function(){var e=c(this);return i.setValue(e,this.serialize()),this},isDirty:function(e){var t=c(this),r=i.getValue(t);if(!r)return!1;var a=this.serialize();return(e?o(a,r):s(a,r).filter(function(e){if("set"!==e.type)return!0;var t=a[e.key],n=r[e.key];return!(t&&n&&"object"==typeof t&&"object"==typeof n)})).length},restore:function(e){var t=c(this),n=i.getValue(t),r=e?n:function(e,t){var n={};for(var r in e)"object"!=typeof e[r]||null===e[r]||e[r]instanceof Date?n[r]=e[r]:n[r]=t[r];return n}(n,this);if(this.isDirty(e))for(var a in r)this[a]=r[a];return this}}),e}}),define("can/es/can-define-backup",["exports","can-define-backup"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-define-stream",["require","exports","module","can-define","can-assign","can-reflect"],function(e,t,n){"use strict";var c=e("can-define"),u=e("can-assign"),r=e("can-reflect");n.exports=function(s){return function(a){["toStream","toStreamFromProperty","toStreamFromEvent"].forEach(function(e){a.prototype[e]=function(){return s[e].apply(s,[this].concat([].slice.call(arguments)))}}),a.prototype.stream=a.prototype.toStream;var e=a.prototype._define.definitions,i=a.prototype._define.dataInitializers,o=a.prototype._define.computedInitializers;r.eachKey(e,function(e,t){var n=e.stream;if(n){var r=u({default:function(){return s.toCompute(n,this)}},c.types.compute);c.property(a.prototype,t,r,i,o)}})}}}),define("can/es/can-define-stream",["exports","can-define-stream"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-kefir",["require","exports","module","kefir","can-symbol","can-reflect","can-event-queue/map/map","can-observation-recorder"],function(e,t,n){!function(e,t,n,r){"use strict";var a=t("kefir"),i=t("can-symbol"),o=t("can-reflect"),s=t("can-event-queue/map/map"),c=t("can-observation-recorder"),u=i.for("can.meta"),l=i.for("can.onKeyValue"),f=i.for("can.offKeyValue"),d={value:{on:"onValue",off:"offValue",handler:"onValueHandler",handlers:"onValueHandlers"},error:{on:"onError",off:"offError",handler:"onErrorHandler",handlers:"onErrorHandlers"}};function p(e){var t=e[u];return t||(t={},o.setKeyValue(e,u,t)),t}a&&(Object.isExtensible&&!Object.isExtensible(a)&&(a=a.Kefir),a.Observable.prototype._eventSetup=function(){var n=this,r=p(n);r.bound=!0,r.onValueHandler=function(e){var t=r.value;(r.value=e)!==t&&s.dispatch.call(n,{type:"value"},[e,t])},r.onErrorHandler=function(e){var t=r.error;r.error=e,s.dispatch.call(n,{type:"error"},[e,t])},n.onValue(r.onValueHandler),n.onError(r.onErrorHandler)},a.Observable.prototype._eventTeardown=function(){var e=p(this);e.bound=!1,this.offValue(e.onValueHandler),this.offError(e.onErrorHandler)},o.assignSymbols(a.Observable.prototype,{"can.onKeyValue":function(){return s[l].apply(this,arguments)},"can.offKeyValue":function(){return s[f].apply(this,arguments)},"can.getKeyValue":function(e){var t=p(this);if(!d[e])return this[e];if(c.add(this,e),t.bound)return t[e];var n=function(e,t){if(e._currentEvent&&e._currentEvent.type===t)return e._currentEvent.value;var n=d[t];if(!n)return e[t];var r,a=function(e){r=e};return e[n.on](a),e[n.off](a),r}(this,e);return t[e]=n},"can.getValueDependencies":function(){var e;if(null!=this._source?e=[this._source]:null!=this._sources&&(e=this._sources),null!=e)return{valueDependencies:new Set(e)}}}),a.emitterProperty=function(){var t,n,r=!1,e=a.stream(function(e){return t=e,r&&t.value(n),function(){t=void 0}}).toProperty(function(){return n});return e.emitter={value:function(e){if(t)return t.emit(e);r=!0,n=e},error:function(e){if(t)return t.error(e);e}},e.emitter.emit=e.emitter.value,o.assignSymbols(e,{"can.setKeyValue":function(e,t){this.emitter[e](t)}}),e}),r.exports=a}(0,e,0,n)}),define("can-compute/proto-compute",["require","exports","module","can-observation","can-observation-recorder","can-event-queue/map/map","can-stache-key","can-key/get/get","can-assign","can-reflect","can-single-reference"],function(e,t,n){"use strict";var i=e("can-observation"),s=e("can-observation-recorder"),o=e("can-event-queue/map/map"),f=e("can-stache-key"),c=e("can-key/get/get"),u=e("can-assign"),d=e("can-reflect"),a=e("can-single-reference"),l=function(e,t,n,r){for(var a=[],i=0,o=arguments.length;i<o;i++)a[i]=arguments[i];var s=typeof a[1];if("function"==typeof a[0])this._setupGetterSetterFn(a[0],a[1],a[2],a[3]);else if(void 0!==a[1])if("string"===s||"number"===s){var c=d.isObservableLike(a[0])&&d.isListLike(a[0]);if(d.isObservableLike(a[0])&&d.isMapLike(a[0])||c){var u=a[0],l=a[1];this._setupGetterSetterFn(function(e){if(!arguments.length)return c&&f.get(u,"length"),f.get(u,""+l);f.set(u,l,e)},a[1],a[2],a[3])}else this._setupProperty(a[0],a[1],a[2])}else"function"===s?this._setupSetter(a[0],a[1],a[2]):a[1]&&a[1].fn?this._setupAsyncCompute(a[0],a[1]):this._setupSettings(a[0],a[1]);else this._setupSimpleValue(a[0]);this._args=a,this._primaryDepth=0,this.isComputed=!0},p=function(e,t,n){var r=new i(t,n,e),a=e.updater.bind(e);return e.observation=r,{_on:function(){d.onValue(r,a,"notify"),r.hasOwnProperty("_value")?e.value=r._value:e.value=r.value},_off:function(){d.offValue(r,a,"notify")},getDepth:function(){return r.getDepth()}}};o(l.prototype),u(l.prototype,{setPrimaryDepth:function(e){this._primaryDepth=e},_setupGetterSetterFn:function(e,t,n){this._set=t?e.bind(t):e,this._get=t?e.bind(t):e,this._canObserve=!1!==n;var r=p(this,e,t||this);u(this,r)},_setupProperty:function(r,a,t){var n,e=this;n=function(){e.updater(e._get(),e.value)},this._get=function(){return c(r,a)},this._set=function(e){var t=a.split("."),n=t.pop();t.length?c(r,t.join("."))[n]=e:r[a]=e},this._on=function(e){o.on.call(r,t||a,n),this.value=this._get()},this._off=function(){return o.off.call(r,t||a,n)}},_setupSetter:function(e,t,n){this.value=e,this._set=t,u(this,n)},_setupSettings:function(e,t){if(this.value=e,this._set=t.set||this._set,this._get=t.get||this._get,!t.__selfUpdater){var n=this,r=this.updater;this.updater=function(){r.call(n,n._get(),n.value)}}this._on=t.on?t.on:this._on,this._off=t.off?t.off:this._off},_setupAsyncCompute:function(e,t){var n,r=this,a=t.fn;if(this.value=e,this._setUpdates=!0,this.lastSetValue=new l(e),this._set=function(e){return e===r.lastSetValue.get()?this.value:r.lastSetValue.set(e)},this._get=function(){return a.call(t.context,r.lastSetValue.get())},0===a.length)n=p(this,a,t.context);else if(1===a.length)n=p(this,function(){return a.call(t.context,r.lastSetValue.get())},t);else{var i=this.updater,o=s.ignore(function(e){i.call(r,e,r.value)});this.updater=function(e){i.call(r,e,r.value)},n=p(this,function(){var e=a.call(t.context,r.lastSetValue.get(),o);return void 0!==e?e:this.value},this)}u(this,n)},_setupSimpleValue:function(e){this.value=e},_eventSetup:s.ignore(function(){this.bound=!0,this._on(this.updater)}),_eventTeardown:function(){this._off(this.updater),this.bound=!1},clone:function(e){return e&&"function"==typeof this._args[0]?this._args[1]=e:e&&(this._args[2]=e),new l(this._args[0],this._args[1],this._args[2],this._args[3])},_on:function(){},_off:function(){},get:function(){return s.isRecording()&&!1!==this._canObserve&&(s.add(this,"change"),this.bound||l.temporarilyBind(this)),this.bound?this.observation?this.observation.get():this.value:this._get()},_get:function(){return this.value},set:function(e){var t=this.value,n=this._set(e,t);return this._setUpdates?this.value:this.hasDependencies?this._get():(this.updater(void 0===n?this._get():n,t),this.value)},_set:function(e){return this.value=e},updater:function(e,t,n){this.value=e;var r,a,i,o,s=this.observation;s&&(s.hasOwnProperty("_value")?s._value=e:s.value=e),r=this,o=n,(a=e)!==(i=t)&&(a==a||i==i)&&r.dispatch({type:"change",batchNum:o},[a,i])},toFunction:function(){return this._computeFn.bind(this)},_computeFn:function(e){return arguments.length?this.set(e):this.get()}}),l.prototype.on=l.prototype.bind=l.prototype.addEventListener,l.prototype.off=l.prototype.unbind=l.prototype.removeEventListener;var r=function(){return this.observation&&this.observation.hasDependencies()};Object.defineProperty(l.prototype,"hasDependencies",{get:r}),l.temporarilyBind=i.temporarilyBind,l.async=function(e,t,n){return new l(e,{fn:t,context:n})},l.truthy=function(t){return new l(function(){var e=t.get();return"function"==typeof e&&(e=e.get()),!!e})},d.assignSymbols(l.prototype,{"can.isValueLike":!0,"can.isMapLike":!1,"can.isListLike":!1,"can.setValue":l.prototype.set,"can.getValue":l.prototype.get,"can.valueHasDependencies":r,"can.onValue":function(r,e){function t(e,t,n){r(t,n)}a.set(r,this,t),this.addEventListener("change",t,e)},"can.offValue":function(e,t){this.removeEventListener("change",a.getAndDelete(e,this),t)},"can.getValueDependencies":function(){var e;return this.observation&&(e={valueDependencies:new Set([this.observation])}),e}}),n.exports=l}),define("can-compute",["require","exports","module","can-compute/proto-compute","can-namespace","can-single-reference","can-reflect/reflections/get-set/get-set","can-symbol"],function(e,t,n){"use strict";var i=e("can-compute/proto-compute"),r=e("can-namespace"),a=e("can-single-reference"),o=e("can-reflect/reflections/get-set/get-set"),s=e("can-symbol"),c=s.for("can.onValue"),u=s.for("can.offValue"),l=s.for("can.getValue"),f=s.for("can.setValue"),d=s.for("can.isValueLike"),p=s.for("can.isMapLike"),h=s.for("can.isListLike"),v=s.for("can.isFunctionLike"),y=s.for("can.valueHasDependencies"),g=s.for("can.getValueDependencies"),m=function(e,t){var n,r=this;return t&&(n=function(){t.apply(r,arguments)},a.set(t,this,n)),r.computeInstance.addEventListener(e,n)},b=function(e,t){var n=[];return void 0!==e&&(n.push(e),void 0!==t&&n.push(a.getAndDelete(t,this))),this.computeInstance.removeEventListener.apply(this.computeInstance,n)},w=function(e,t){return this.computeInstance[c](e,t)},x=function(e,t){return this.computeInstance[u](e,t)},_=function(){return this.computeInstance.get()},k=function(e){return this.computeInstance.set(e)},O=function(){return this.computeInstance.hasDependencies},E=function(){return this.computeInstance[g]()},L=function(t,n,e,r){function a(e){return arguments.length?a.computeInstance.set(e):a.computeInstance.get()}return a.computeInstance=new i(t,n,e,r),a.on=a.bind=a.addEventListener=m,a.off=a.unbind=a.removeEventListener=b,a.isComputed=a.computeInstance.isComputed,a.clone=function(e){return"function"==typeof t&&(n=e),L(t,n,e,r)},o.set(a,c,w),o.set(a,u,x),o.set(a,l,_),o.set(a,f,k),o.set(a,d,!0),o.set(a,p,!1),o.set(a,h,!1),o.set(a,v,!1),o.set(a,y,O),o.set(a,g,E),a};L.truthy=function(e){return L(function(){return!!e()})},L.async=function(e,t,n){return L(e,{fn:t,context:n})},L.temporarilyBind=i.temporarilyBind,n.exports=r.compute=L}),define("can-stream",["require","exports","module","can-assign","can-compute","can-reflect","can-namespace"],function(e,t,n){"use strict";var o=e("can-assign"),u=e("can-compute"),i=e("can-reflect"),r=e("can-namespace"),l=function(t,r){var a,i;return u(void 0,{on:function(n){a=function(e,t){i=o({args:[].slice.call(arguments,1)},e),n()},t.on(r,a)},off:function(e){t.off(r,a),i=void 0},get:function(){return i}})},a=function(r){var a;return((a=function(){if(1===arguments.length)return r.toStream(arguments[0]);if(1<arguments.length){var e=arguments[0],t=arguments[1].trim();if(-1===t.indexOf(" "))return 0===t.indexOf(".")?a.toStreamFromProperty(e,t.slice(1)):a.toStreamFromEvent(e,t);var n=t.split(" ");return a.toStreamFromEvent(e,n[0].slice(1),n[1])}}).toStream=a).toStreamFromProperty=function(e,t){return r.toStream(u(e,t))},a.toStreamFromEvent=function(){var a,e,i,t,n=arguments[0];if(2===arguments.length)return t=l(n,arguments[1]),r.toStream(t);e=arguments[1],a=arguments[2],i=n[e];var o,s,c=u(n,e);return t=u(void 0,{on:function(r){o=function(e,t,n){r(i=t)},s=function(e,t,n){n.off(a,o),t.on(a,o)},c.on("change",s),c().on(a,o)},off:function(){c().off(a,o),c.off("change",s)},get:function(){return i},set:function(e){throw new Error("can-stream: you can't set this type of compute")}}),r.toStream(t)},a.toCompute=function(e,t){var n=i.toArray(arguments);return r.toCompute.apply(this,n)},a};a.toComputeFromEvent=l,n.exports=r.stream=a}),define("can-stream-kefir",["require","exports","module","can-kefir","can-compute","can-stream","can-symbol","can-namespace"],function(e,t,n){"use strict";var u=e("can-kefir"),l=e("can-compute"),r=e("can-stream"),a=e("can-symbol"),i=e("can-namespace"),o=a.for("can.getValueDependencies"),f=a.for("can.getKeyDependencies"),s={toStream:function(r){var e=u.stream(function(n){var e=function(e,t){n.emit(t)};r.on("change",e);var t=r();return void 0!==t&&n.emit(t),function(){r.off("change",e)}});return e[o]=function(){return{valueDependencies:new Set([r])}},e},toCompute:function(e,t){var n,r,a,i,o=u.stream(function(e){n=e,void 0!==i&&n.emit(i)}),s=e.call(t,o),c=l(void 0,{get:function(){return r},set:function(e){return n?n.emit(e):i=e,e},on:function(t){a=function(e){r=e,t()},s.onValue(a)},off:function(){s.offValue(a)}});return c.computeInstance[f]=function(e){if("change"===e)return{valueDependencies:new Set([s])}},c}};i.streamKefir||(n.exports=i.streamKefir=r(s))}),define("can-define-stream-kefir",["require","exports","module","can-namespace","can-define-stream","can-stream-kefir"],function(e,t,n){"use strict";var r=e("can-namespace"),a=e("can-define-stream"),i=e("can-stream-kefir");n.exports=r.defineStreamKefir=a(i)}),define("can/es/can-define-stream-kefir",["exports","can-define-stream-kefir"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-kefir",["exports","can-kefir"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-observe/src/-symbols",["require","exports","module","can-symbol"],function(e,t,n){"use strict";var r=e("can-symbol");n.exports={metaSymbol:r.for("can.meta"),patchesSymbol:"can.patches",keysSymbol:"can.keys"}}),define("can-observe/src/-observable-store",function(e,t,n){"use strict";n.exports={proxiedObjects:new WeakMap,proxies:new WeakSet}}),define("can-observe/src/-helpers",["require","exports","module","can-symbol"],function(require,exports,module){"use strict";var canSymbol=require("can-symbol"),metaSymbol=canSymbol.for("can.meta"),classTest=/^\s*class\s+/,helpers={assignEverything:function(t,n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}),t},isBuiltInButNotArrayOrPlainObject:function(e){if(Array.isArray(e))return!1;if("function"==typeof e)return 0<e.toString().indexOf("[native code]");var t=Object.prototype.toString.call(e);return"[object Object]"!==t&&-1!==t.indexOf("[object ")},inheritsFromArray:function(e){var t=e;do{if(Array.isArray(t))return!0;t=Object.getPrototypeOf(t)}while(t);return!1},isClass:function(e){return"function"==typeof e&&classTest.test(e.toString())},supportsClass:function(){try{return eval('"use strict"; class A{};'),!0}catch(e){return!1}}(),makeSimpleExtender:function(a){return function(e,t,n){var r=function(){var e=a.apply(this,arguments);return this.init&&(e[metaSymbol].preventSideEffects++,this.init.apply(e,arguments),e[metaSymbol].preventSideEffects--),e};return helpers.assignEverything(r,a),helpers.assignEverything(r,t||{}),r.extend=helpers.makeSimpleExtender(r),r.prototype=Object.create(a.prototype),helpers.assignEverything(r.prototype,n||{}),r.prototype.constructor=r}},assignNonEnumerable:function(e,t,n){return Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}};module.exports=helpers}),define("can-observe/src/-computed-helpers",["require","exports","module","can-observation","can-observation-recorder","can-event-queue/map/map","can-reflect","can-symbol"],function(e,t,n){"use strict";var i=e("can-observation"),r=e("can-observation-recorder"),a=e("can-event-queue/map/map"),o=e("can-reflect"),s=e("can-symbol"),c=s.for("can.meta"),u=s.for("can.computedPropertyDefinitions"),l=s.for("can.onKeyValue"),f=s.for("can.offKeyValue");function d(e,t,n){this.instance=e,this.prop=t,this.observation=n,this.forward=this.forward.bind(this)}function p(e,t){var n=e[c],r=n.target[u];if(void 0!==r){var a=r[t];if(void 0!==a)return void 0===n.computedKeys[t]&&(n.computedKeys[t]=new d(e,t,a(e,t))),n.computedKeys[t]}}d.prototype.bind=function(){this.bindingCount++,1===this.bindingCount&&this.observation.on(this.forward,"notify")},d.prototype.unbind=function(){this.bindingCount--,0===this.bindingCount&&this.observation.off(this.forward,"notify")},d.prototype.forward=function(e,t){a.dispatch.call(this.instance,{type:this.prop,target:this.instance},[e,t])},d.prototype.bindingCount=0;var h=n.exports={get:function(e,t){var n=p(e,t);if(void 0!==n)return r.add(e,t.toString()),0===n.bindingCount&&r.isRecording()&&i.temporarilyBind(n.observation),{value:o.getValue(n.observation)}},set:function(e,t,n){var r=p(e,t);return void 0!==r&&(o.setValue(r.observation,n),!0)},bind:function(e,t){var n=p(e,t);void 0!==n&&n.bind()},unbind:function(e,t){var n=p(e,t);void 0!==n&&n.unbind()},addKeyDependencies:function(e){var r=e[l],a=e[f];o.assignSymbols(e,{"can.onKeyValue":function(e,t,n){return h.bind(this,e),r.apply(this,arguments)},"can.offKeyValue":function(e,t,n){return h.unbind(this,e),a.apply(this,arguments)},"can.getKeyDependencies":function(e){var t=p(this,e);if(void 0!==t)return{valueDependencies:new Set([t.observation])}}})},addMethodsAndSymbols:function(e){e.prototype.addEventListener=function(e,t,n){return h.bind(this,e),a.addEventListener.call(this,e,t,n)},e.prototype.removeEventListener=function(e,t,n){return h.unbind(this,e),a.removeEventListener.call(this,e,t,n)}},ensureDefinition:function(r){if(!r.hasOwnProperty(u)){var e=r[u],a=r[u]=Object.create(e||null);Object.getOwnPropertyNames(r).forEach(function(e){if("constructor"!==e){var t=Object.getOwnPropertyDescriptor(r,e);if(void 0!==t.get){var n=t.get;a[e]=function(e,t){return new i(n,e)}}}})}return r[u]}}}),define("can-observe/src/-make-object",["require","exports","module","can-reflect","can-observation-recorder","can-event-queue/map/map","can-observe/src/-symbols","can-observe/src/-observable-store","can-observe/src/-helpers","can-observe/src/-computed-helpers"],function(e,t,n){"use strict";var r=e("can-reflect"),s=e("can-observation-recorder"),o=e("can-event-queue/map/map"),a=e("can-observe/src/-symbols"),c=e("can-observe/src/-observable-store"),i=e("can-observe/src/-helpers"),u=e("can-observe/src/-computed-helpers"),l=Object.prototype.hasOwnProperty,f=r.isSymbolLike,d=Object.create(null);Object.getOwnPropertySymbols(o).forEach(function(e){i.assignNonEnumerable(d,e,o[e])}),u.addKeyDependencies(d);var p={observable:function(e,t){void 0===t.shouldRecordObservation&&(t.shouldRecordObservation=p.shouldRecordObservationOnOwnAndMissingKeys);var n={target:e,proxyKeys:void 0!==t.proxyKeys?t.proxyKeys:Object.create(p.proxyKeys()),computedKeys:Object.create(null),options:t,preventSideEffects:0};i.assignNonEnumerable(n.proxyKeys,a.metaSymbol,n);var r={get:p.get.bind(n),set:p.set.bind(n),ownKeys:p.ownKeys.bind(n),deleteProperty:p.deleteProperty.bind(n),getOwnPropertyDescriptor:p.getOwnPropertyDescriptor.bind(n),meta:n};return t.getPrototypeOf&&(r.getPrototypeOf=t.getPrototypeOf),n.proxy=new Proxy(e,r),o.addHandlers(n.proxy,n),n.proxy},proxyKeys:function(){return d},get:function(e,t,n){var r=this.proxyKeys[t];if(void 0!==r)return r;if(f(t))return e[t];var a=u.get(n,t);if(void 0!==a)return a.value;var i=p.getKeyInfo(e,t,n,this),o=i.targetValue;return i.valueIsInvariant||(o=p.getValueFromStore(t,o,this)),this.options.shouldRecordObservation(i,this)&&s.add(this.proxy,t.toString()),i.parentObservableGetCalledOn&&s.add(i.parentObservableGetCalledOn,t.toString()),o},set:function(e,t,n,r){return r!==this.proxy?p.setKey(r,t,n,this):(!0===u.set(r,t,n)||(n=p.getValueToSet(t,n,this),p.setValueAndOnChange(t,n,this,function(e,t,n,r,a){var i={type:e,patches:[{key:e,type:r?"set":"add",value:t}],keyChanged:r?void 0:e};o.dispatch.call(n.proxy,i,[t,a])})),!0)},deleteProperty:function(e,t){var n=this.target[t],r=delete this.target[t];if(r&&0===this.preventSideEffects&&void 0!==n){var a={type:t,patches:[{key:t,type:"delete"}],keyChanged:t};o.dispatch.call(this.proxy,a,[void 0,n])}return r},ownKeys:function(e,t){return s.add(this.proxy,a.keysSymbol),Object.getOwnPropertyNames(this.target).concat(Object.getOwnPropertySymbols(this.target)).concat(Object.getOwnPropertySymbols(this.proxyKeys))},getOwnPropertyDescriptor:function(e,t){var n=Object.getOwnPropertyDescriptor(e,t);return!n&&t in this.proxyKeys?Object.getOwnPropertyDescriptor(this.proxyKeys,t):n},getKeyInfo:function(e,t,n,r){var a=Object.getOwnPropertyDescriptor(e,t),i={key:t,descriptor:a,targetHasOwnKey:Boolean(a),getCalledOnParent:n!==r.proxy,protoHasKey:!1,valueIsInvariant:!1,targetValue:void 0,isAccessor:!1};return!0===i.getCalledOnParent&&(i.parentObservableGetCalledOn=c.proxiedObjects.get(n)),void 0!==a?(i.valueIsInvariant=!1===a.writable,void 0!==a.get?(i.targetValue=a.get.call(i.parentObservableGetCalledOn||n),i.isAccessor=!0):i.targetValue=a.value):(i.targetValue=r.target[t],i.protoHasKey=void 0!==i.targetValue||t in e),i},shouldRecordObservationOnOwnAndMissingKeys:function(e,t){return 0===t.preventSideEffects&&!e.isAccessor&&(e.targetHasOwnKey||!e.protoHasKey&&!Object.isSealed(t.target))},setKey:function(e,t,n){return Object.defineProperty(e,t,{value:n,configurable:!0,enumerable:!0,writable:!0}),!0},getValueToSet:function(e,t,n){return!r.isSymbolLike(e)&&n.handlers.getNode([e])?p.getValueFromStore(e,t,n):t},getValueFromStore:function(e,t,n){return r.isPrimitive(t)||r.isObservableLike(t)||c.proxies.has(t)||(c.proxiedObjects.has(t)?t=c.proxiedObjects.get(t):i.isBuiltInButNotArrayOrPlainObject(t)||(t=n.options.observe(t))),t},setValueAndOnChange:function(e,t,n,r){var a,i=l.call(n.target,e),o=Object.getOwnPropertyDescriptor(n.target,e);o&&o.set?o.set.call(n.proxy,t):(a=n.target[e])!==t&&(n.target[e]=t,0===n.preventSideEffects&&r(e,t,n,i,a))}};n.exports=p}),define("can-observe/src/-make-array",["require","exports","module","can-observation-recorder","can-event-queue/map/map","can-reflect","can-observe/src/-make-object","can-observe/src/-symbols","can-observe/src/-observable-store","can-observe/src/-helpers","can-observe/src/-computed-helpers"],function(e,t,n){"use strict";var r=e("can-observation-recorder"),d=e("can-event-queue/map/map"),a=e("can-reflect"),i=e("can-observe/src/-make-object"),c=e("can-observe/src/-symbols"),u=e("can-observe/src/-observable-store"),o=e("can-observe/src/-helpers"),s=e("can-observe/src/-computed-helpers"),p=a.isSymbolLike,h=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};var v={push:function(e,t){return[{index:e.length-t.length,deleteCount:0,insert:t,type:"splice"}]},pop:function(e){return[{index:e.length,deleteCount:1,insert:[],type:"splice"}]},shift:function(){return[{index:0,deleteCount:1,insert:[],type:"splice"}]},unshift:function(e,t){return[{index:0,deleteCount:0,insert:t,type:"splice"}]},splice:function(e,t){return[{index:t[0],deleteCount:t[1],insert:t.slice(2),type:"splice"}]},sort:function(e){return[{index:0,deleteCount:e.length,insert:e,type:"splice"}]},reverse:function(e,t,n){return[{index:0,deleteCount:e.length,insert:e,type:"splice"}]}};a.eachKey(v,function(o,e){var s=Array.prototype[e],t=function(){var e=this[c.metaSymbol],t=0===e.preventSideEffects,n=e.target.length;e.preventSideEffects++;var r=s.apply(e.target,arguments),a=o(e.target,Array.from(arguments),n);if(!0===t){var i={type:"length",patches:a};d.dispatch.call(e.proxy,i,[e.target.length,n])}return e.preventSideEffects--,r};u.proxiedObjects.set(s,t),u.proxies.add(t)}),Object.getOwnPropertyNames(Array.prototype).forEach(function(e){var n=Array.prototype[e];if(!u.proxiedObjects.has(n)&&"constructor"!==e&&"function"==typeof n){var t=function(){r.add(this,c.patchesSymbol);var e=this[c.metaSymbol];e.preventSideEffects++;var t=n.apply(this,arguments);return e.preventSideEffects--,e.options.observe(t)};u.proxiedObjects.set(n,t),u.proxies.add(t)}});var l=o.assignEverything(Object.create(null),i.proxyKeys()),f={observable:function(e,t){void 0===t.shouldRecordObservation&&(t.shouldRecordObservation=i.shouldRecordObservationOnOwnAndMissingKeys);var n={target:e,proxyKeys:void 0!==t.proxyKeys?t.proxyKeys:Object.create(f.proxyKeys()),computedKeys:Object.create(null),options:t,preventSideEffects:0};return(n.proxyKeys[c.metaSymbol]=n).proxy=new Proxy(e,{get:i.get.bind(n),set:f.set.bind(n),ownKeys:i.ownKeys.bind(n),deleteProperty:i.deleteProperty.bind(n),meta:n}),d.addHandlers(n.proxy,n),n.proxy},proxyKeys:function(){return l},set:function(l,e,t,n){if(n!==this.proxy)return i.setKey(n,e,t,this);if(!0===s.set(n,e,t))return!0;t=i.getValueToSet(e,t,this);var f=l.length;return i.setValueAndOnChange(e,t,this,function(e,t,n,r,a){var i,o,s=[{key:e,type:r?"set":"add",value:t}],c=!p(e)&&+e;h(c)&&(!r&&f<c?s.push({index:f,deleteCount:0,insert:l.slice(f),type:"splice"}):s.push.apply(s,v.splice(l,[c,1,t]))),i=t,o=a,"length"===e&&i<o&&s.push({index:t,deleteCount:a-t,insert:[],type:"splice"});var u={type:e,patches:s,keyChanged:r?void 0:e};d.dispatch.call(n.proxy,u,[t,a])}),!0}};n.exports=f}),define("can-observe/src/-make-observe",["require","exports","module","can-reflect","can-observe/src/-observable-store","can-observe/src/-helpers"],function(e,t,n){"use strict";var r=e("can-reflect"),a=e("can-observe/src/-observable-store"),i=e("can-observe/src/-helpers"),o={observe:function(e){if(r.isPrimitive(e))return e;var t=a.proxiedObjects.get(e);return t||(a.proxies.has(e)?e:i.isBuiltInButNotArrayOrPlainObject(e)?e:(t="function"==typeof e?o.function(e):i.inheritsFromArray(e)?o.array(e):o.object(e),a.proxiedObjects.set(e,t),a.proxies.add(t),t))},object:null,array:null,function:null};n.exports=o}),define("can-observe/src/-make-function",["require","exports","module","can-reflect","can-observe/src/-make-object","can-observe/src/-make-observe","can-observe/src/-symbols","can-observe/src/-observable-store","can-event-queue/map/map","can-event-queue/type/type","can-observe/src/-helpers"],function(e,t,n){"use strict";var r=e("can-reflect"),i=e("can-observe/src/-make-object"),o=e("can-observe/src/-make-observe"),s=e("can-observe/src/-symbols"),c=e("can-observe/src/-observable-store"),u=e("can-event-queue/map/map"),l=e("can-event-queue/type/type"),f=e("can-observe/src/-helpers"),a=f.assignEverything(Object.create(null),i.proxyKeys());l(a),r.assignSymbols(a,{"can.defineInstanceKey":function(e,t){this[s.metaSymbol].definitions[e]=t}});var d={observable:function(e,t){void 0===t.shouldRecordObservation&&(t.shouldRecordObservation=i.shouldRecordObservationOnOwnAndMissingKeys);var n=Object.create(d.proxyKeys()),r={target:e,proxyKeys:n,computedKeys:Object.create(null),options:t,definitions:{},isClass:f.isClass(e),preventSideEffects:0};if((n[s.metaSymbol]=r).proxy=new Proxy(e,{get:i.get.bind(r),set:i.set.bind(r),ownKeys:i.ownKeys.bind(r),deleteProperty:i.deleteProperty.bind(r),construct:d.construct.bind(r),apply:d.apply.bind(r),meta:r}),u.addHandlers(r.proxy,r),l.addHandlers(r.proxy,r),c.proxiedObjects.set(e,r.proxy),c.proxies.add(r.proxy),r.target.prototype&&r.target.prototype.constructor===r.target){var a=i.observable(r.target.prototype,{getPrototypeOf:function(){return r.target.prototype},observe:o.observe});c.proxiedObjects.set(r.target.prototype,a),c.proxies.add(a),r.proxy.prototype.constructor=r.proxy}return r.proxy},construct:function(e,t,n){var r,a;if(this.isClass){for(a in r=Reflect.construct(e,t,n),this.definitions)Object.defineProperty(r,a,this.definitions[a]);return this.options.observe(r)}for(a in r=Object.create(this.proxy.prototype),this.definitions)Object.defineProperty(r,a,this.definitions[a]);var i=this.options.observe(r);i[s.metaSymbol].preventSideEffects++;var o=e.apply(i,t);return i[s.metaSymbol].preventSideEffects--,o||i},apply:function(e,t,n){var r=this.target.apply(t,n);return this.options.observe(r)},proxyKeys:function(){return a}};n.exports=d}),define("can-observe/src/-type-helpers",["require","exports","module","can-queues","can-reflect","can-symbol"],function(e,t,n){"use strict";var a=e("can-queues"),r=e("can-reflect"),i=e("can-symbol"),o=i.for("can.meta"),s=i.for("can.typeDefinitions"),c=n.exports={ensureDefinition:function(e){var t=e[s];if(!t){var n=e[s];t=e[s]=Object.create(n||null)}return t},addMethodsAndSymbols:function(e){r.assignSymbols(e,{"can.defineInstanceKey":function(e,t){c.ensureDefinition(this.prototype)[e]=t},"can.dispatchInstanceBoundChange":function(e,t){var n=this[o];if(n){var r=n.lifecycleHandlers;r&&a.enqueueByQueue(r.getNode([]),this,[e,t])}}})},shouldRecordObservationOnAllKeysExceptFunctionsOnProto:function(e,t){return 0===t.preventSideEffects&&!e.isAccessor&&(e.targetHasOwnKey||!e.protoHasKey&&!Object.isSealed(t.target)||e.protoHasKey&&"function"!=typeof targetValue)}}}),define("can-observe/object/object",["require","exports","module","can-reflect","can-symbol","can-observe/src/-make-observe","can-event-queue/map/map","can-event-queue/type/type","can-observe/src/-helpers","can-observe/src/-make-object","can-observe/src/-observable-store","can-observe/src/-computed-helpers","can-observe/src/-type-helpers"],function(e,t,n){"use strict";var o=e("can-reflect"),r=e("can-symbol"),s=e("can-observe/src/-make-observe"),a=e("can-event-queue/map/map"),i=e("can-event-queue/type/type"),c=e("can-observe/src/-helpers"),u=e("can-observe/src/-make-object"),l=e("can-observe/src/-observable-store"),f=r.for("can.typeDefinitions"),d=e("can-observe/src/-computed-helpers"),p=e("can-observe/src/-type-helpers"),h=c.assignEverything({},u.proxyKeys());d.addKeyDependencies(h);var v=function(e){var t=Object.getPrototypeOf(this);d.ensureDefinition(t),p.ensureDefinition(t);var n=t[f]||{};for(var r in n)Object.defineProperty(this,r,n[r]);void 0!==e&&o.assign(this,e);var a=Object.create(h);a.constructor=this.constructor;var i=u.observable(this,{observe:s.observe,proxyKeys:a,shouldRecordObservation:p.shouldRecordObservationOnAllKeysExceptFunctionsOnProto});return l.proxiedObjects.set(this,i),l.proxies.add(i),i};a(v.prototype),i(v),d.addMethodsAndSymbols(v),p.addMethodsAndSymbols(v),v.extend=c.makeSimpleExtender(v),n.exports=v}),define("can-observe/array/array",["require","exports","module","can-symbol","can-observe/src/-make-array","can-observe/src/-make-observe","can-event-queue/map/map","can-event-queue/type/type","can-observe/src/-helpers","can-observe/src/-observable-store","can-observe/src/-computed-helpers","can-observe/src/-type-helpers"],function(e,t,n){"use strict";var r,a=e("can-symbol"),o=e("can-observe/src/-make-array"),s=e("can-observe/src/-make-observe"),i=e("can-event-queue/map/map"),c=e("can-event-queue/type/type"),u=e("can-observe/src/-helpers"),l=e("can-observe/src/-observable-store"),f=e("can-observe/src/-computed-helpers"),d=e("can-observe/src/-type-helpers"),p=a.for("can.typeDefinitions"),h=u.assignEverything({},o.proxyKeys());(r=function(e){var t=Object.getPrototypeOf(this);f.ensureDefinition(t),d.ensureDefinition(t);var n=t[p]||{};for(var r in n)Object.defineProperty(this,r,n[r]);this.push.apply(this,e||[]);var a=Object.create(h);a.constructor=this.constructor;var i=o.observable(this,{observe:s.observe,proxyKeys:a,shouldRecordObservation:d.shouldRecordObservationOnAllKeysExceptFunctionsOnProto});return l.proxiedObjects.set(this,i),l.proxies.add(i),i}).prototype=Object.create(Array.prototype),i(r.prototype),c(r),f.addMethodsAndSymbols(r),d.addMethodsAndSymbols(r),r.extend=u.makeSimpleExtender(r),n.exports=r}),define("can-observe/decorators/decorators",["require","exports","module","can-reflect","can-simple-observable/async/async","can-simple-observable/resolver/resolver","can-observe/src/-computed-helpers"],function(e,t,n){"use strict";var o=e("can-reflect"),s=e("can-simple-observable/async/async"),a=e("can-simple-observable/resolver/resolver"),r=e("can-observe/src/-computed-helpers");function c(e,t,n){r.ensureDefinition(e)[t]=n}function i(t){return function(e){return 3===arguments.length?t({}).apply(null,arguments):t(e)}}n.exports={async:i(function(i){return function(e,t,n){if(void 0!==n.get){var r=n.get;return c(e,t,function(e,t){return new s(function(e,t){if(!t)return i.default;var n=r.call(this,!0);return o.isPromise(n)?(n.then(t),i.default):void 0},e,i.default)})}if(void 0!==n.value){var a=n.value;return c(e,t,function(e,t){return new s(function(e,t){return a.call(this,t)},e,i.default)})}}}),resolver:i(function(e){return function(e,t,n){if(void 0!==n.value){var r=n.value;return c(e,t,function(e,t){return new a(r,e)})}}})}}),define("can-observe",["require","exports","module","can-observe/src/-make-object","can-observe/src/-make-array","can-observe/src/-make-function","can-observe/src/-make-observe","can-observe/object/object","can-observe/array/array","can-observe/src/-computed-helpers","can-observe/decorators/decorators"],function(e,t,n){"use strict";var r=e("can-observe/src/-make-object"),a=e("can-observe/src/-make-array"),i=e("can-observe/src/-make-function"),o=e("can-observe/src/-make-observe"),s=e("can-observe/object/object"),c=e("can-observe/array/array"),u=e("can-observe/src/-computed-helpers"),l=e("can-observe/decorators/decorators");for(var f in o.object=function(e){return r.observable(e,o)},o.array=function(e){return a.observable(e,o)},o.function=function(e){return i.observable(e,o)},o.observe.Object=s,o.observe.Array=c,n.exports=o.observe,n.exports.defineProperty=function(e,t,n){u.ensureDefinition(e)[t]=n},l)n.exports[f]=l[f]}),define("can/es/can-observe",["exports","can-observe"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-stream",["exports","can-stream"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-stream-kefir",["exports","can-stream-kefir"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-map-compat",["require","exports","module","can-key","can-reflect","can-log"],function(e,t,n){var i=e("can-key"),o=e("can-reflect"),s=e("can-log");function r(e,t){var n=e.prototype;if("function"==typeof n.attr)return e;var a=!0===t;return n.attr=function(e,t){a&&s.warn("can-map-compat is intended for migrating away from can-map. Remove all uses of .attr() to remove this warning.");var n=typeof e,r=arguments.length;return 0===r?o.unwrap(this):"string"!==n&&"number"!==n?(!0===t?o.updateDeep(this,e):o.assignDeep(this,e),this):1===r?i.get(this,e):(i.set(this,e,t),this)},n.removeAttr=function(e){var t=o.getKeyValue(this,e);return o.deleteKeyValue(this,e),t},e}(n.exports=function(e){return r(e,!0)}).makeCompat=r}),define("can/es/can-map-compat",["exports","can-map-compat"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-stache-converters",["require","exports","module","can-reflect","can-stache","can-string-to-any","can-log/dev/dev","can-stache-bindings","can-stache-helpers"],function(e,t,n){"use strict";var s=e("can-reflect"),r=e("can-stache"),a=e("can-string-to-any");e("can-log/dev/dev");e("can-stache-bindings");var i=e("can-stache-helpers"),o=!1;r("{{echo(args(1))}}")({echo:function(){},args:function(){o=1<arguments.length}}),r.registerConverter("boolean-to-inList",{get:function(e,t){return!!t&&-1!==t.indexOf(e)},set:function(e,t,n){if(n)if(e)n.push(t);else{var r=n.indexOf(t);-1!==r&&n.splice(r,1)}}});var c={"string-to-any":{get:function(e){return""+s.getValue(e)},set:function(e,t){var n=a(e);s.setValue(t,n)}},"index-to-selected":{get:function(e,t){var n=s.getValue(e);return s.getValue(t).indexOf(n)},set:function(e,t,n){var r=s.getValue(n)[e];s.setValue(t,r)}},"selected-to-index":{get:function(e,t){var n=s.getValue(e);return s.getValue(t)[n]},set:function(e,t,n){var r=s.getValue(n).indexOf(e);s.setValue(t,r)}},"either-or":{get:function(e,t,n){var r=s.getValue(e),a=s.getValue(t),i=s.getValue(n),o=a===r;return o||i===r?o:void 0},set:function(e,t,n,r){var a=e?s.getValue(n):s.getValue(r);s.setValue(t,a)}},equal:{get:function(){var e=s.toArray(arguments);if(o&&e.pop(),1<e.length){var t=s.getValue(e.pop());return e.every(function(e){return s.getValue(e)===t})}},set:function(){var e=s.toArray(arguments);if(o&&e.pop(),2<e.length){var t=e.shift(),n=s.getValue(e.pop());if(t)for(var r=0;r<e.length;r++)s.setValue(e[r],n)}}}};r.addConverter(c),i.not||r.addConverter("not",{get:function(e){return!s.getValue(e)},set:function(e,t){s.setValue(t,!e)}}),n.exports=c}),define("can/es/can-stache-converters",["exports","can-stache-converters"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-view-autorender",["require","exports","module","can-namespace","can-view-model","can-reflect","can-string","can-import-module","can-dom-events"],function(e,t,n){var r=e("can-namespace"),a=e("can-view-model"),o=e("can-reflect"),i=e("can-string").camelize,s=e("can-import-module"),c=e("can-dom-events"),u=/^(dataViewId|class|id|type|src|style)$/i,l=/\s*text\/(stache)\s*/;function f(e,t,n){var r=i(t);if(!u.test(r)){var a=e.getAttribute(t);o.hasKey(n,r)||o.defineInstanceKey(n.constructor,r,typeof a),o.setKeyValue(n,r,a)}}function d(e,t){e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t)}function p(e,t,n){var r=e(t);!function(e,t){for(;e.parentNode;)if((e=e.parentNode).nodeName.toLowerCase()===t.toLowerCase())return!0}(n,"head")?"script"===n.nodeName.toLowerCase()?d(n,r):(d(n,r),n.parentNode.removeChild(n)):document.body.appendChild(r)}function h(t){var n=a(t);return o.each(t.attributes||[],function(e){f(t,e.name,n)}),c.addEventListener(t,"attributes",function(e){f(t,e.attributeName,n)}),n}var v=new Promise(function(e,t){function n(){var i=[];o.each(document.querySelectorAll("[can-autorender]"),function(t,e){t.style.display="none";var n=t.innerHTML||t.text,r=t.getAttribute("type").match(l),a="can-"+(r&&r[1]);i.push(s(a).then(function(e){if(e.async)return e.async(n).then(function(e){p(e,h(t),t)});p(e(n),h(t),t)}))}),Promise.all(i).then(e,t)}"complete"===document.readyState?n():c.addEventListener(window,"load",n)});n.exports=r.autorender=function(e,t){return v.then(e,t)}}),define("can/es/can-view-autorender",["exports","can-view-autorender"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-super-model",["require","exports","module","can-connect","can-connect/constructor/constructor","can-connect/can/map/map","can-connect/can/ref/ref","can-connect/constructor/store/store","can-connect/data/callbacks/callbacks","can-connect/data/callbacks-cache/callbacks-cache","can-connect/data/combine-requests/combine-requests","can-connect/data/localstorage-cache/localstorage-cache","can-connect/data/parse/parse","can-connect/data/url/url","can-connect/fall-through-cache/fall-through-cache","can-connect/real-time/real-time","can-connect/constructor/callbacks-once/callbacks-once","can-namespace","can-reflect","can-query-logic"],function(e,t,n){var r=e("can-connect"),a=e("can-connect/constructor/constructor"),i=e("can-connect/can/map/map"),o=e("can-connect/can/ref/ref"),s=e("can-connect/constructor/store/store"),c=e("can-connect/data/callbacks/callbacks"),u=e("can-connect/data/callbacks-cache/callbacks-cache"),l=e("can-connect/data/combine-requests/combine-requests"),f=e("can-connect/data/localstorage-cache/localstorage-cache"),d=e("can-connect/data/parse/parse"),p=e("can-connect/data/url/url"),h=e("can-connect/fall-through-cache/fall-through-cache"),v=e("can-connect/real-time/real-time"),y=e("can-connect/constructor/callbacks-once/callbacks-once"),g=e("can-namespace"),m=e("can-reflect"),b=e("can-query-logic");n.exports=g.superModel=function(e){(e=m.assignDeep({},e)).name||(e.name=m.getName(e.Map)+".connection"),e.queryLogic||(e.queryLogic=new b(e.Map));var t=[a,i,o,s,c,l,d,p,v,y];return"undefined"!=typeof localStorage&&(e.cacheConnection||(e.cacheConnection=r([f],{name:e.name+".cacheConnection",idProp:e.idProp,queryLogic:e.queryLogic})),t.push(u,h)),r(t,e)}}),define("can/es/can-super-model",["exports","can-super-model"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-connect-feathers/service/service",["require","exports","module","can-connect"],function(e,t,n){"use strict";var r=e("can-connect");function a(e){var t,n=e.algebra&&e.algebra.clauses&&e.algebra.clauses.id;if(n&&(t=Object.keys(n)[0]),!t&&!e.idProp)throw new Error("An idProp was not set in the Model for "+e+". Things may not work as expected.");return t||e.idProp}n.exports=r.behavior("data/feathers-service",function(e){if(!this.feathersService)throw new Error("You must provide a feathersService to the feathers-service behavior: https://canjs.com/doc/can-connect-feathers.html");var r=this.feathersService;return{init:function(){e.init.apply(this,arguments);var t=this;r.on("created",function(e){t.createInstance(e)}),r.on("updated",function(e){t.updateInstance(e)}),r.on("patched",function(e){t.updateInstance(e)}),r.on("removed",function(e){t.destroyInstance(e)})},getListData:function(e){return r.find({query:e})},getData:function(e){var t=null,n=a(this);return"string"==typeof e||"number"==typeof e?(t=e,e={}):e&&void 0!==e[n]&&(t=e[n],delete e[n]),r.get(t,{query:e})},createData:function(e){return r.create(e)},updateData:function(e){var t=a(this);return r.update(e[t],e)},destroyData:function(e){var t=a(this);return r.remove(e[t])}}})}),define("ms",function(e,t,n){var r=864e5;function a(e,t,n,r){var a=1.5*n<=t;return Math.round(e/n)+" "+r+(a?"s":"")}n.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&0<e.length)return function(e){if(100<(e=String(e)).length)return;var t=/^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*n;case"weeks":case"week":case"w":return 6048e5*n;case"days":case"day":case"d":return n*r;case"hours":case"hour":case"hrs":case"hr":case"h":return 36e5*n;case"minutes":case"minute":case"mins":case"min":case"m":return 6e4*n;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(e);if("number"===n&&!1===isNaN(e))return t.long?function(e){var t=Math.abs(e);if(r<=t)return a(e,t,r,"day");if(36e5<=t)return a(e,t,36e5,"hour");if(6e4<=t)return a(e,t,6e4,"minute");if(1e3<=t)return a(e,t,1e3,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(r<=t)return Math.round(e/r)+"d";if(36e5<=t)return Math.round(e/36e5)+"h";if(6e4<=t)return Math.round(e/6e4)+"m";if(1e3<=t)return Math.round(e/1e3)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}),define("debug/src/common",["require","exports","module","ms"],function(e,t,n){"use strict";n.exports=function(t){function n(e){for(var t=0,n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return u.colors[Math.abs(t)%u.colors.length]}function u(e){var s;function c(){if(c.enabled){for(var e=arguments.length,a=new Array(e),t=0;t<e;t++)a[t]=arguments[t];var i=c,n=Number(new Date),r=n-(s||n);i.diff=r,i.prev=s,i.curr=n,s=n,a[0]=u.coerce(a[0]),"string"!=typeof a[0]&&a.unshift("%O");var o=0;a[0]=a[0].replace(/%([a-zA-Z%])/g,function(e,t){if("%%"===e)return e;o++;var n=u.formatters[t];if("function"==typeof n){var r=a[o];e=n.call(i,r),a.splice(o,1),o--}return e}),u.formatArgs.call(i,a),(i.log||u.log).apply(i,a)}}return c.namespace=e,c.enabled=u.enabled(e),c.useColors=u.useColors(),c.color=n(e),c.destroy=r,c.extend=a,"function"==typeof u.init&&u.init(c),u.instances.push(c),c}function r(){var e=u.instances.indexOf(this);return-1!==e&&(u.instances.splice(e,1),!0)}function a(e,t){return u(this.namespace+(void 0===t?":":t)+e)}return((u.debug=u).default=u).coerce=function(e){return e instanceof Error?e.stack||e.message:e},u.disable=function(){u.enable("")},u.enable=function(e){var t;u.save(e),u.names=[],u.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),r=n.length;for(t=0;t<r;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?u.skips.push(new RegExp("^"+e.substr(1)+"$")):u.names.push(new RegExp("^"+e+"$")));for(t=0;t<u.instances.length;t++){var a=u.instances[t];a.enabled=u.enabled(a.namespace)}},u.enabled=function(e){if("*"===e[e.length-1])return!0;var t,n;for(t=0,n=u.skips.length;t<n;t++)if(u.skips[t].test(e))return!1;for(t=0,n=u.names.length;t<n;t++)if(u.names[t].test(e))return!0;return!1},u.humanize=e("ms"),Object.keys(t).forEach(function(e){u[e]=t[e]}),u.instances=[],u.names=[],u.skips=[],u.formatters={},u.selectColor=n,u.enable(u.load()),u}}),define("debug",["require","exports","module","debug/src/common"],function(e,t,n){!function(e,t,n,a){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}n.log=function(){var e;return"object"===("undefined"==typeof console?"undefined":r(console))&&console.log&&(e=console).log.apply(e,arguments)},n.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+a.exports.humanize(this.diff),!this.useColors)return;var t="color: "+this.color;e.splice(1,0,t,"color: inherit");var n=0,r=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(n++,"%c"===e&&(r=n))}),e.splice(r,0,t)},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}},n.load=function(){var e;try{e=n.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},n.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},n.storage=function(){try{return localStorage}catch(e){}}(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],a.exports=t("debug/src/common")(n),a.exports.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(0,e,t,n)}),define("feathers-errors",["require","exports","module","debug"],function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u=e("debug")("feathers-errors");function l(e,t,n,r,a){var i=void 0,o=void 0,s=void 0;(e=e||"Error")instanceof Error?(o=e.message||"Error",e.errors&&(i=e.errors)):"object"===(void 0===e?"undefined":c(e))?(o=e.message||"Error",a=e):o=e,a&&((s=JSON.parse(JSON.stringify(a))).errors?(i=s.errors,delete s.errors):a.errors&&(i=JSON.parse(JSON.stringify(a.errors)))),this.type="FeathersError",this.name=t,this.message=o,this.code=n,this.className=r,this.data=s,this.errors=i||{},u(this.name+"("+this.code+"): "+this.message),u(this.errors),Error.captureStackTrace?Error.captureStackTrace(this,l):this.stack=(new Error).stack}function a(e,t){l.call(this,e,"BadRequest",400,"bad-request",t)}function i(e,t){l.call(this,e,"NotAuthenticated",401,"not-authenticated",t)}function o(e,t){l.call(this,e,"PaymentError",402,"payment-error",t)}function s(e,t){l.call(this,e,"Forbidden",403,"forbidden",t)}function f(e,t){l.call(this,e,"NotFound",404,"not-found",t)}function d(e,t){l.call(this,e,"MethodNotAllowed",405,"method-not-allowed",t)}function p(e,t){l.call(this,e,"NotAcceptable",406,"not-acceptable",t)}function h(e,t){l.call(this,e,"Timeout",408,"timeout",t)}function v(e,t){l.call(this,e,"Conflict",409,"conflict",t)}function y(e,t){l.call(this,e,"LengthRequired",411,"length-required",t)}function g(e,t){l.call(this,e,"Unprocessable",422,"unprocessable",t)}function m(e,t){l.call(this,e,"TooManyRequests",429,"too-many-requests",t)}function b(e,t){l.call(this,e,"GeneralError",500,"general-error",t)}function w(e,t){l.call(this,e,"NotImplemented",501,"not-implemented",t)}function x(e,t){l.call(this,e,"BadGateway",502,"bad-gateway",t)}function _(e,t){l.call(this,e,"Unavailable",503,"unavailable",t)}l.prototype=Object.create(Error.prototype),Object.defineProperty(l.prototype,"toJSON",{value:function(){return{name:this.name,message:this.message,code:this.code,className:this.className,data:this.data,errors:this.errors}}}),a.prototype=l.prototype,i.prototype=l.prototype,o.prototype=l.prototype,s.prototype=l.prototype,f.prototype=l.prototype,d.prototype=l.prototype,p.prototype=l.prototype,h.prototype=l.prototype,v.prototype=l.prototype,y.prototype=l.prototype,g.prototype=l.prototype,m.prototype=l.prototype,b.prototype=l.prototype,w.prototype=l.prototype,x.prototype=l.prototype,_.prototype=l.prototype;var k={FeathersError:l,BadRequest:a,NotAuthenticated:i,PaymentError:o,Forbidden:s,NotFound:f,MethodNotAllowed:d,NotAcceptable:p,Timeout:h,Conflict:v,LengthRequired:y,Unprocessable:g,TooManyRequests:m,GeneralError:b,NotImplemented:w,BadGateway:x,Unavailable:_,400:a,401:i,402:o,403:s,404:f,405:d,406:p,408:h,409:v,411:y,422:g,429:m,500:b,501:w,502:x,503:_};t.default=r({convert:function(e){if(!e)return e;var t=k[e.name],n=t?new t(e.message,e.data):new Error(e.message||e);return"object"===(void 0===e?"undefined":c(e))&&r(n,e),n},types:k,errors:k},k),n.exports=t.default}),define("events",function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function c(e){return"function"==typeof e}function u(e){return"object"==typeof e&&null!==e}function l(e){return void 0===e}((n.exports=r).EventEmitter=r).prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,a,i,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||u(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var s=new Error('Uncaught, unspecified "error" event. ('+t+")");throw s.context=t,s}if(l(n=this._events[e]))return!1;if(c(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(u(n))for(a=Array.prototype.slice.call(arguments,1),r=(o=n.slice()).length,i=0;i<r;i++)o[i].apply(this,a);return!0},r.prototype.on=r.prototype.addListener=function(e,t){var n;if(!c(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,c(t.listener)?t.listener:t),this._events[e]?u(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,u(this._events[e])&&!this._events[e].warned&&(n=l(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&0<n&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.once=function(e,t){if(!c(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var n,r,a,i;if(!c(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,r=-1,n===t||c(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(u(n)){for(i=a;0<i--;)if(n[i]===t||n[i].listener&&n[i].listener===t){r=i;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(c(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?c(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(c(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}}),define("feathers-authentication-popups",["require","exports","module","events"],function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.authAgent=void 0,t.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},n=t.width||1024,r=t.height||640,a=c(window,n,r),i=a.top,o=a.left,s="width="+n+", height="+r+", top="+i+", left="+o;return window.open(e,"authWindow",s)},t.getCenterCoordinates=c;var r,a=e("events"),i=(r=a)&&r.__esModule?r:{default:r};window.authAgent=new i.default;t.authAgent=window.authAgent;function c(e,t,n){return{left:e.screenX+(e.outerWidth-t)/2,top:e.screenY+(e.outerHeight-n)/2}}}),define("jwt-decode/lib/atob",function(e,t,n){function s(e){this.message=e}(s.prototype=new Error).name="InvalidCharacterError",n.exports="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new s("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,a=0,i=0,o="";r=t.charAt(i++);~r&&(n=a%4?64*n+r:r,a++%4)?o+=String.fromCharCode(255&n>>(-2*a&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return o}}),define("jwt-decode/lib/base64_url_decode",["require","exports","module","jwt-decode/lib/atob"],function(e,t,n){var r=e("jwt-decode/lib/atob");n.exports=function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return decodeURIComponent(r(t).replace(/(.)/g,function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}catch(e){return r(t)}}}),define("jwt-decode",["require","exports","module","jwt-decode/lib/base64_url_decode"],function(e,t,n){"use strict";var r=e("jwt-decode/lib/base64_url_decode");function a(e){this.message=e}(a.prototype=new Error).name="InvalidTokenError",n.exports=function(e,t){if("string"!=typeof e)throw new a("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(r(e.split(".")[n]))}catch(e){throw new a("Invalid token specified: "+e.message)}},n.exports.InvalidTokenError=a}),define("can-connect-feathers/utils/utils",["require","exports","module","jwt-decode","can-assign"],function(e,t,n){"use strict";var r=e("jwt-decode"),a=e("can-assign");function i(e){for(var t=e+"=",n=document.cookie.split(";"),r=0;r<n.length;r++){for(var a=n[r];" "===a.charAt(0);)a=a.substring(1,a.length);if(0===a.indexOf(t))return a.substring(t.length,a.length)}return null}function o(e){var t=i(e);return!t&&(window&&window.localStorage||window.sessionStorage)&&(t=window.sessionStorage.getItem(e)||window.localStorage.getItem(e)),t}function s(e){return e&&1e3*e.exp>(new Date).getTime()}n.exports={readCookie:i,getStoredToken:o,hasValidToken:function(e){var t=o(e);if(t)try{return s(r(t))}catch(e){return!1}return!1},payloadIsValid:s,convertLocalAuthData:function(e){var t=a({},e);return t&&"local"===t.strategy&&t.user&&(Object.keys(t.user).forEach(function(e){t[e]=t.user[e]}),delete t.user),t}}}),define("can-connect-feathers/session/storage",function(e,t,n){"use strict";n.exports={data:{},getStore:function(){if(window.doneSsr){var e=window.CanZone||void 0;return void 0===e?this.data:e.current.data}return this.data},setItem:function(e,t){this.getStore()[e]=t},getItem:function(e){return this.getStore()[e]},removeItem:function(e){delete this.getStore()[e]}}}),define("can-connect-feathers/session/session",["require","exports","module","can-connect","feathers-errors","feathers-authentication-popups","jwt-decode","can-connect-feathers/utils/utils","can-connect-feathers/utils/utils","can-connect-feathers/utils/utils","can-observation-recorder","can-connect-feathers/session/storage"],function(e,t,n){"use strict";var r=e("can-connect"),i=e("feathers-errors"),o=e("feathers-authentication-popups").authAgent,s=e("jwt-decode"),c=e("can-connect-feathers/utils/utils").payloadIsValid,u=e("can-connect-feathers/utils/utils").hasValidToken,l=e("can-connect-feathers/utils/utils").convertLocalAuthData,f=e("can-observation-recorder"),d=e("can-connect-feathers/session/storage");n.exports=r.behavior("data/feathers-session",function(e){var t="https://canjs.com/doc/can-connect-feathers.html",r=this.feathersClient;if(!r)throw new Error("You must provide a feathersClient instance to the feathers-session behavior. See "+t);if(!this.Map)throw new Error("You must provide a Map instance to the feathers-session behavior. See "+t);if(!r.passport)throw new Error("You must register the feathers-authentication-client plugin before using the feathers-session behavior. See "+t);var a=r.passport.options,n=this.Map;return Object.defineProperty(n,"current",{get:function(){return f.add(n,"current"),void 0===d.getItem("can-connect-feathers-session")&&(d.removeItem("can-connect-feathers-session"),n.get().then(function(e){d.setItem("can-connect-feathers-session",e),n.dispatch("current",[e])}).catch(function(e){if(d.setItem("can-connect-feathers-session",null),n.dispatch("current",[null]),!e.className||e.className.indexOf("not-authenticated")<0)return Promise.reject(e)})),d.getItem("can-connect-feathers-session")}}),n.on("created",function(e,t){d.setItem("can-connect-feathers-session",t),n.dispatch("current",[t])}),n.on("destroyed",function(){d.removeItem("can-connect-feathers-session"),n.dispatch("current",[void 0,d.getItem("can-connect-feathers-session")])}),{init:function(){e.init.apply(this,arguments);var n=this;o.on("login",function(e){try{var t=s(e);if(!c(t))throw new Error("invalid token")}catch(e){throw new Error("An invalid token was received through the feathers-authentication-popups authAgent")}r.authenticate({strategy:"jwt",accessToken:e}).then(function(e){var t=s(e.accessToken);n.createInstance(t)})})},createData:function(e){var t=l(e);return r.authenticate(t).then(function(e){return e.accessToken&&Object.assign(e,s(e.accessToken)),e})},getData:function(){return new Promise(function(n,e){var t=a.tokenKey||a.cookie;u(t)&&!window.doneSsr?r.authenticate().then(function(e){var t=s(e.accessToken);return n(t)}).catch(e):e(new i.NotAuthenticated("Not Authenticated"))})},destroyData:function(e){return r.logout().then(function(){return e})}}})}),define("can-connect-feathers",["require","exports","module","can-connect-feathers/service/service","can-connect-feathers/session/session"],function(e,t,n){"use strict";n.exports={service:e("can-connect-feathers/service/service"),session:e("can-connect-feathers/session/session")}}),define("can/es/can-connect-feathers",["exports","can-connect-feathers"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-connect-tag",["require","exports","module","can-stache-bindings","can-observation","can-stache/src/expression","can-view-callbacks","can-observation-recorder","can-view-nodelist","can-reflect","can-symbol","can-dom-mutate","can-dom-mutate/node","can-reflect","can-namespace"],function(e,t,n){e("can-stache-bindings");var g=e("can-observation"),m=e("can-stache/src/expression"),r=e("can-view-callbacks"),b=e("can-observation-recorder"),w=e("can-view-nodelist"),x=e("can-reflect"),_=e("can-symbol"),k=e("can-dom-mutate"),O=e("can-dom-mutate/node"),E=e("can-reflect").each,a=e("can-namespace"),L=function(e){return"function"==typeof e?L(e()):e};n.exports=a.connectTag=function(e,y){r.tag(e,function(e,r){var t,n,a,i=e.getAttribute("getList")||e.getAttribute("get-list"),o=e.getAttribute("get"),s=i||o,c=i?"getList":"get",u=m.parse("tmp("+(n=n||"{",a=a||"}",(t=s)[0]===n&&t[t.length-1]===a?t.substr(1,t.length-2):t)+")",{baseMethodType:"Call"}),l=!1,f=b.ignore(function(e,t){if(!l){var n=r.scope.peek("%root")||r.scope.peek("@root");n&&n.pageData&&("get"===c&&(e=y.id(e)),n.pageData(y.name,e,t))}l=!0}),d=new g(function(){var n={};if("object"==typeof u.hash)E(u.hash,function(e,t){e&&e.hasOwnProperty("get")?n[t]=r.scope.read(e.get,{}).value:n[t]=e});else if("function"==typeof u.hash){var e=u.hash(r.scope,r.options,{});E(e(),function(e,t){n[t]=L(e)})}else n=u.argExprs.length?x.getValue(u.argExprs[0].value(r.scope,r.options)):{};var t=y[c](n);return f(n,t),t});e[_.for("can.viewModel")]=d;var p=w.register([],void 0,r.parentNodeList||!0),h=r.subtemplate?r.subtemplate(r.scope.add(d),r.options,p):document.createDocumentFragment();O.appendChild.call(e,h),w.update(p,e.childNodes);var v=k.onNodeRemoval(e,function(){e.ownerDocument.contains(e)||(v(),w.unregister(p))})})}}),define("can/es/can-connect-tag",["exports","can-connect-tag"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-fixture-socket/src/store",["require","exports","module","can-fixture/core"],function(e,t,n){var r=e("can-fixture/core").extractResponse;function a(n){return function(e,t){n({data:e},function(){var e=r.apply(null,arguments);200===e[0]?t(null,e[1]):t(e[1])})}}n.exports={requestHandlerToListener:a,storeToListeners:function(n){return["getListData","getData","updateData","createData","destroyData"].reduce(function(e,t){return e[t]=a(n[t]),e},{})}}}),define("can-fixture-socket/src/feathers-client",["require","exports","module","can-fixture-socket/src/store","can-assign"],function(e,t,n){var f=e("can-fixture-socket/src/store").storeToListeners,d=e("can-assign");function p(r,a,i){return function(e){var n,t=Array.prototype.slice.call(arguments);"function"==typeof t[t.length-1]&&(n=t[t.length-1]),e=a?a(e):e,r(e,function(e,t){e?n&&n(e):(t=i?i(t):t,n&&n(null,t))})}}function h(n){return function(e){var t={};return t[n&&n.id||"id"]=e,t}}function v(e){return{total:e.count,limit:e.limit,skip:e.offset,data:e.data}}n.exports={subscribeFeathersStoreToServer:function(e,t,n,r){var i,o,s,a,c,u,l=f(t);n.on(e+"::find",p(l.getListData,null,v)),n.on(e+"::get",p(l.getData,h(r),null)),n.on(e+"::remove",(i=l.getData,o=l.destroyData,s=r,function(e,t,r){var a=h(s)(e);i(a,function(e,n){e?r(e):o(a,function(e,t){e?r(e):r(null,n)})})})),n.on(e+"::create",(a=l.createData,function(n,e,r){a(n,function(e,t){e?r(e):r(null,d(n,t))})})),n.on(e+"::update",(c=l.updateData,u=r,function(e,n,t,r){var a=h(u)(e);c(d(a,n),function(e,t){e?r(e):r(null,d(a,d(n,t)))})}))}}}),define("can-fixture-socket/src/index",["require","exports","module","can-fixture-socket/src/feathers-client"],function(e,t,n){var r=e("can-fixture-socket/src/feathers-client").subscribeFeathersStoreToServer,a=function(e){this.io=e,this.events={},this.subscribers={},l(e.managers),this.origs=c(e.Manager.prototype,this)};a.prototype.on=function(e,t){var n=this,r={};"string"==typeof e&&(r[e]=t),"object"==typeof e&&(r=e),Object.keys(r).forEach(function(e){s(n.events,e,r[e])})},a.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments,1);o(this.subscribers,e,t)},a.prototype.onFeathersService=function(e,t,n){r(e,t,this,n)},a.prototype.restore=function(){u(this.io.Manager.prototype,this.origs),l(this.io.managers)};var i=function(e){this._server=e,this.io={engine:this}};function o(e,t,n){d(" >>> pub "+t),(e[t]||[]).forEach(function(e){e.apply(null,n)})}function s(e,t,n){d(" <<< sub "+t),e[t]||(e[t]=[]),e[t].push(n)}function c(t,n){var e=["open","socket"].map(function(e){return{name:e,method:t[e]}});return t.open=t.connect=function(){d("MockedManager.prototype.open or connect ... arguments:",arguments),setTimeout(function(){o(n.subscribers,"connect"),o(n.events,"connection")},0)},t.socket=function(){d("MockedManager.prototype.socket ...");var e=new i(n);return e.connected=!0,e.disconnected=!1,e},e}function u(t,e){d("Restore."),e.forEach(function(e){t[e.name]=e.method})}function l(e){for(var t in e)e.hasOwnProperty(t)&&delete e[t]}var f=!(i.prototype={on:function(e,t){d("MockedSocket.on ... "+e),s(this._server.subscribers,e,t)},emit:function(e){var t=Array.prototype.slice.call(arguments,1);d("MockedSocket.emit ..."+e),o(this._server.events,e,t)},once:function(){d("MockedSocket.once ...")},off:function(e,t){var n,r,a;d("MockedSocket.off ... "+e),n=this._server.subscribers,a=t,d(" <<< unsub "+(r=e)),n[r].forEach(function(e,t){e===a&&n[r].splice(t,1)})},open:function(){return this.connect()},connect:function(){this.connected=!0,this.disconnected=!1},close:function(){return this.disconnect()},disconnect:function(){this.connected=!1,this.disconnected=!0}});function d(e,t){f&&console.log.apply(console,arguments)}n.exports={Server:a,mockSocketManager:c,restoreManager:u}}),define("can-fixture-socket",["require","exports","module","can-fixture-socket/src/index","can-fixture-socket/src/store"],function(e,t,n){var r=e("can-fixture-socket/src/index"),a=e("can-fixture-socket/src/store");n.exports={Server:r.Server,requestHandlerToListener:a.requestHandlerToListener,storeToListeners:a.storeToListeners}}),define("can/es/can-fixture-socket",["exports","can-fixture-socket"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-ndjson-stream",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace");n.exports=r.ndjsonStream=function(e){var t,d=!1;return new ReadableStream({start:function(c){var u=e.getReader();t=u;var l=new TextDecoder,f="";u.read().then(function e(t){if(!t.done){for(var n=l.decode(t.value,{stream:!0}),r=(f+=n).split("\n"),a=0;a<r.length-1;++a){var i=r[a].trim();if(0<i.length)try{var o=JSON.parse(i);c.enqueue(o)}catch(e){return c.error(e),d=!0,void u.cancel()}}return f=r[r.length-1],u.read().then(e)}if(!d){if(0!==(f=f.trim()).length)try{var s=JSON.parse(f);c.enqueue(s)}catch(e){return void c.error(e)}c.close()}})},cancel:function(e){console.log("Cancel registered due to ",e),d=!0,t.cancel()}})}}),define("can/es/can-ndjson-stream",["exports","can-ndjson-stream"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-connect-ndjson",["require","exports","module","can-connect","can-connect/helpers/sorted-set-json","can-ndjson-stream","can-reflect","can-namespace"],function(e,t,n){var r,a,i,o,s,c,u,l;a=n,i=(r=e)("can-connect"),o=r("can-connect/helpers/sorted-set-json"),s=r("can-ndjson-stream"),c=r("can-reflect"),u=r("can-namespace"),l=i.behavior("data-ndjson",function(a){try{if(new ReadableStream,"function"!=typeof window.fetch)throw new Error("fetch not supported")}catch(e){return{}}return{hydrateList:function(e,t){t=t||this.listSet(e);var n=o(t),r=a.hydrateList.call(this,e,t);return this._getHydrateListCallbacks[n]&&(this._getHydrateListCallbacks[n].shift()(r),this._getHydrateListCallbacks[n].length||delete this._getHydrateListCallbacks[n]),r},_getHydrateListCallbacks:{},_getHydrateList:function(e,t){var n=o(e);this._getHydrateListCallbacks[n]||(this._getHydrateListCallbacks[n]=[]),this._getHydrateListCallbacks[n].push(t)},getListData:function(e){var t=fetch(this.ndjson||this.url);return this._getHydrateList(e,function(r){function a(e){c.setKeyValue(r,"isStreaming",!1),c.setKeyValue(r,"streamError",e)}t.then(function(e){return c.setKeyValue(r,"isStreaming",!0),s(e.body)}).then(function(e){var n=e.getReader();n.read().then(function e(t){t.done?c.setKeyValue(r,"isStreaming",!1):(r.push(t.value),n.read().then(e,a))},a)})}),t.then(function(){return{data:[]}})}}}),a.exports=u.connectNdjson=l}),define("can/es/can-connect-ndjson",["exports","can-connect-ndjson"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-route-mock",["require","exports","module","can-simple-observable","can-reflect"],function(e,t,n){var r=e("can-simple-observable"),a=e("can-reflect");function i(){this.routeValue=new r("")}a.assignMap(i.prototype,{paramsMatcher:/^(?:&[^=]+=[^&]*)+/,querySeparator:"&",matchSlashes:!1,root:"#!",get:function(){return this.value},set:function(e){return this.value=e},on:function(e){a.onValue(this,e)},off:function(e){a.offValue(this,e)}}),Object.defineProperty(i.prototype,"value",{get:function(){return this.routeValue.get().split(/#!?/)[1]||""},set:function(e){return"#"!==e[0]?this.routeValue.set("#"+(e||"")):this.routeValue.set(e||""),e}}),a.assignSymbols(i.prototype,{"can.onValue":function(e){this.routeValue.on(e)},"can.offValue":function(e){this.routeValue.off(e)},"can.getValue":function(){return this.value},"can.setValue":function(e){this.value=e}}),n.exports=i}),define("can/es/can-route-mock",["exports","can-route-mock"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),function(e,t,n){"use strict";var o=function(e,t,n){n=f.extend({},f.options,n);var r,a,i=f.runValidations(e,t,n);for(r in i)for(a in i[r])if(f.isPromise(i[r][a]))throw new Error("Use validate.async if you want support for promises");return o.processValidationResults(i,n)},f=o;f.extend=function(n){return[].slice.call(arguments,1).forEach(function(e){for(var t in e)n[t]=e[t]}),n},f.extend(o,{version:{major:0,minor:11,patch:1,metadata:null,toString:function(){var e=f.format("%{major}.%{minor}.%{patch}",f.version);return f.isEmpty(f.version.metadata)||(e+="+"+f.version.metadata),e}},Promise:"undefined"!=typeof Promise?Promise:null,EMPTY_STRING_REGEXP:/^\s*$/,runValidations:function(e,t,n){var r,a,i,o,s,c,u,l=[];for(r in(f.isDomElement(e)||f.isJqueryElement(e))&&(e=f.collectFormValues(e)),t)for(a in i=f.getDeepObjectValue(e,r),o=f.result(t[r],i,e,r,n,t)){if(!(s=f.validators[a]))throw u=f.format("Unknown validator %{name}",{name:a}),new Error(u);c=o[a],(c=f.result(c,i,e,r,n,t))&&l.push({attribute:r,value:i,validator:a,globalOptions:n,attributes:e,options:c,error:s.call(s,i,c,r,e,n)})}return l},processValidationResults:function(e,t){e=f.pruneEmptyErrors(e,t),e=f.expandMultipleErrors(e,t),e=f.convertErrorMessages(e,t);var n=t.format||"grouped";if("function"!=typeof f.formatters[n])throw new Error(f.format("Unknown format %{format}",t));return e=f.formatters[n](e),f.isEmpty(e)?void 0:e},async:function(r,a,i){var o=(i=f.extend({},f.async.options,i)).wrapErrors||function(e){return e};!1!==i.cleanAttributes&&(r=f.cleanAttributes(r,a));var s=f.runValidations(r,a,i);return new f.Promise(function(t,n){f.waitForResults(s).then(function(){var e=f.processValidationResults(s,i);e?n(new o(e,i,r,a)):t(r)},function(e){n(e)})})},single:function(e,t,n){return n=f.extend({},f.single.options,n,{format:"flat",fullMessages:!1}),f({single:e},{single:t},n)},waitForResults:function(e){return e.reduce(function(e,t){return f.isPromise(t.error)?e.then(function(){return t.error.then(function(e){t.error=e||null})}):e},new f.Promise(function(e){e()}))},result:function(e){var t=[].slice.call(arguments,1);return"function"==typeof e&&(e=e.apply(null,t)),e},isNumber:function(e){return"number"==typeof e&&!isNaN(e)},isFunction:function(e){return"function"==typeof e},isInteger:function(e){return f.isNumber(e)&&e%1==0},isBoolean:function(e){return"boolean"==typeof e},isObject:function(e){return e===Object(e)},isDate:function(e){return e instanceof Date},isDefined:function(e){return null!=e},isPromise:function(e){return!!e&&f.isFunction(e.then)},isJqueryElement:function(e){return e&&f.isString(e.jquery)},isDomElement:function(e){return!!e&&(!(!e.querySelectorAll||!e.querySelector)&&(!(!f.isObject(document)||e!==document)||("object"==typeof HTMLElement?e instanceof HTMLElement:e&&"object"==typeof e&&null!==e&&1===e.nodeType&&"string"==typeof e.nodeName)))},isEmpty:function(e){var t;if(!f.isDefined(e))return!0;if(f.isFunction(e))return!1;if(f.isString(e))return f.EMPTY_STRING_REGEXP.test(e);if(f.isArray(e))return 0===e.length;if(f.isDate(e))return!1;if(f.isObject(e)){for(t in e)return!1;return!0}return!1},format:f.extend(function(e,r){return f.isString(e)?e.replace(f.format.FORMAT_REGEXP,function(e,t,n){return"%"===t?"%{"+n+"}":String(r[n])}):e},{FORMAT_REGEXP:/(%?)%\{([^\}]+)\}/g}),prettify:function(e){return f.isNumber(e)?100*e%1==0?""+e:parseFloat(Math.round(100*e)/100).toFixed(2):f.isArray(e)?e.map(function(e){return f.prettify(e)}).join(", "):f.isObject(e)?e.toString():(e=""+e).replace(/([^\s])\.([^\s])/g,"$1 $2").replace(/\\+/g,"").replace(/[_-]/g," ").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+" "+n.toLowerCase()}).toLowerCase()},stringifyValue:function(e){return f.prettify(e)},isString:function(e){return"string"==typeof e},isArray:function(e){return"[object Array]"==={}.toString.call(e)},isHash:function(e){return f.isObject(e)&&!f.isArray(e)&&!f.isFunction(e)},contains:function(e,t){return!!f.isDefined(e)&&(f.isArray(e)?-1!==e.indexOf(t):t in e)},unique:function(e){return f.isArray(e)?e.filter(function(e,t,n){return n.indexOf(e)==t}):e},forEachKeyInKeypath:function(e,t,n){if(f.isString(t)){var r,a="",i=!1;for(r=0;r<t.length;++r)switch(t[r]){case".":i?(i=!1,a+="."):(e=n(e,a,!1),a="");break;case"\\":i?(i=!1,a+="\\"):i=!0;break;default:i=!1,a+=t[r]}return n(e,a,!0)}},getDeepObjectValue:function(e,t){if(f.isObject(e))return f.forEachKeyInKeypath(e,t,function(e,t){if(f.isObject(e))return e[t]})},collectFormValues:function(e,t){var n,r,a,i,o,s,c={};if(f.isJqueryElement(e)&&(e=e[0]),!e)return c;for(t=t||{},i=e.querySelectorAll("input[name], textarea[name]"),n=0;n<i.length;++n)a=i.item(n),f.isDefined(a.getAttribute("data-ignored"))||(s=f.sanitizeFormValue(a.value,t),"number"===a.type?s=s?+s:null:"checkbox"===a.type?a.attributes.value?a.checked||(s=c[a.name]||null):s=a.checked:"radio"===a.type&&(a.checked||(s=c[a.name]||null)),c[a.name]=s);for(i=e.querySelectorAll("select[name]"),n=0;n<i.length;++n){if((a=i.item(n)).multiple)for(r in s=[],a.options)(o=a.options[r]).selected&&s.push(f.sanitizeFormValue(o.value,t));else s=f.sanitizeFormValue(a.options[a.selectedIndex].value,t);c[a.name]=s}return c},sanitizeFormValue:function(e,t){return t.trim&&f.isString(e)&&(e=e.trim()),!1!==t.nullify&&""===e?null:e},capitalize:function(e){return f.isString(e)?e[0].toUpperCase()+e.slice(1):e},pruneEmptyErrors:function(e){return e.filter(function(e){return!f.isEmpty(e.error)})},expandMultipleErrors:function(e){var n=[];return e.forEach(function(t){f.isArray(t.error)?t.error.forEach(function(e){n.push(f.extend({},t,{error:e}))}):n.push(t)}),n},convertErrorMessages:function(e,n){n=n||{};var r=[];return e.forEach(function(e){var t=f.result(e.error,e.value,e.attribute,e.options,e.attributes,e.globalOptions);f.isString(t)?("^"===t[0]?t=t.slice(1):!1!==n.fullMessages&&(t=f.capitalize(f.prettify(e.attribute))+" "+t),t=t.replace(/\\\^/g,"^"),t=f.format(t,{value:f.stringifyValue(e.value)}),r.push(f.extend({},e,{error:t}))):r.push(e)}),r},groupErrorsByAttribute:function(e){var n={};return e.forEach(function(e){var t=n[e.attribute];t?t.push(e):n[e.attribute]=[e]}),n},flattenErrorsToArray:function(e){return e.map(function(e){return e.error}).filter(function(e,t,n){return n.indexOf(e)===t})},cleanAttributes:function(e,t){function r(e,t,n){return f.isObject(e[t])?e[t]:e[t]=!!n||{}}return f.isObject(t)&&f.isObject(e)?function e(t,n){if(!f.isObject(t))return t;var r,a,i=f.extend({},t);for(a in t)r=n[a],f.isObject(r)?i[a]=e(i[a],r):r||delete i[a];return i}(e,t=function(e){var t,n={};for(t in e)e[t]&&f.forEachKeyInKeypath(n,t,r);return n}(t)):{}},exposeModule:function(e,t,n,r,a){n?(r&&r.exports&&(n=r.exports=e),n.validate=e):(t.validate=e).isFunction(a)&&a.amd&&a("validate.js",[],function(){return e})},warn:function(e){"undefined"!=typeof console&&console.warn&&console.warn("[validate.js] "+e)},error:function(e){"undefined"!=typeof console&&console.error&&console.error("[validate.js] "+e)}}),o.validators={presence:function(e,t){if((t=f.extend({},this.options,t)).allowEmpty?!f.isDefined(e):f.isEmpty(e))return t.message||this.message||"can't be blank"},length:function(e,t,n){if(f.isDefined(e)){var r,a=(t=f.extend({},this.options,t)).is,i=t.maximum,o=t.minimum,s=[],c=(e=(t.tokenizer||function(e){return e})(e)).length;return f.isNumber(c)?(f.isNumber(a)&&c!==a&&(r=t.wrongLength||this.wrongLength||"is the wrong length (should be %{count} characters)",s.push(f.format(r,{count:a}))),f.isNumber(o)&&c<o&&(r=t.tooShort||this.tooShort||"is too short (minimum is %{count} characters)",s.push(f.format(r,{count:o}))),f.isNumber(i)&&i<c&&(r=t.tooLong||this.tooLong||"is too long (maximum is %{count} characters)",s.push(f.format(r,{count:i}))),0<s.length?t.message||s:void 0):(f.error(f.format("Attribute %{attr} has a non numeric value for `length`",{attr:n})),t.message||this.notValid||"has an incorrect length")}},numericality:function(e,t){if(f.isDefined(e)){t=f.extend({},this.options,t);var n,r,a=[],i={greaterThan:function(e,t){return t<e},greaterThanOrEqualTo:function(e,t){return t<=e},equalTo:function(e,t){return e===t},lessThan:function(e,t){return e<t},lessThanOrEqualTo:function(e,t){return e<=t},divisibleBy:function(e,t){return e%t==0}};if(f.isString(e)&&t.strict){var o="^(0|[1-9]\\d*)";if(t.onlyInteger||(o+="(\\.\\d+)?"),o+="$",!new RegExp(o).test(e))return t.message||t.notValid||this.notValid||this.message||"must be a valid number"}if(!0!==t.noStrings&&f.isString(e)&&!f.isEmpty(e)&&(e=+e),!f.isNumber(e))return t.message||t.notValid||this.notValid||this.message||"is not a number";if(t.onlyInteger&&!f.isInteger(e))return t.message||t.notInteger||this.notInteger||this.message||"must be an integer";for(n in i)if(r=t[n],f.isNumber(r)&&!i[n](e,r)){var s="not"+f.capitalize(n),c=t[s]||this[s]||this.message||"must be %{type} %{count}";a.push(f.format(c,{count:r,type:f.prettify(n)}))}return t.odd&&e%2!=1&&a.push(t.notOdd||this.notOdd||this.message||"must be odd"),t.even&&e%2!=0&&a.push(t.notEven||this.notEven||this.message||"must be even"),a.length?t.message||a:void 0}},datetime:f.extend(function(e,t){if(!f.isFunction(this.parse)||!f.isFunction(this.format))throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator");if(f.isDefined(e)){var n,r=[],a=(t=f.extend({},this.options,t)).earliest?this.parse(t.earliest,t):NaN,i=t.latest?this.parse(t.latest,t):NaN;return e=this.parse(e,t),isNaN(e)||t.dateOnly&&e%864e5!=0?(n=t.notValid||t.message||this.notValid||"must be a valid date",f.format(n,{value:arguments[0]})):(!isNaN(a)&&e<a&&(n=t.tooEarly||t.message||this.tooEarly||"must be no earlier than %{date}",n=f.format(n,{value:this.format(e,t),date:this.format(a,t)}),r.push(n)),!isNaN(i)&&i<e&&(n=t.tooLate||t.message||this.tooLate||"must be no later than %{date}",n=f.format(n,{date:this.format(i,t),value:this.format(e,t)}),r.push(n)),r.length?f.unique(r):void 0)}},{parse:null,format:null}),date:function(e,t){return t=f.extend({},t,{dateOnly:!0}),f.validators.datetime.call(f.validators.datetime,e,t)},format:function(e,t){(f.isString(t)||t instanceof RegExp)&&(t={pattern:t});var n,r=(t=f.extend({},this.options,t)).message||this.message||"is invalid",a=t.pattern;if(f.isDefined(e))return f.isString(e)?(f.isString(a)&&(a=new RegExp(t.pattern,t.flags)),(n=a.exec(e))&&n[0].length==e.length?void 0:r):r},inclusion:function(e,t){if(f.isDefined(e)&&(f.isArray(t)&&(t={within:t}),t=f.extend({},this.options,t),!f.contains(t.within,e))){var n=t.message||this.message||"^%{value} is not included in the list";return f.format(n,{value:e})}},exclusion:function(e,t){if(f.isDefined(e)&&(f.isArray(t)&&(t={within:t}),t=f.extend({},this.options,t),f.contains(t.within,e))){var n=t.message||this.message||"^%{value} is restricted";return f.format(n,{value:e})}},email:f.extend(function(e,t){var n=(t=f.extend({},this.options,t)).message||this.message||"is not a valid email";if(f.isDefined(e))return f.isString(e)&&this.PATTERN.exec(e)?void 0:n},{PATTERN:/^[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i}),equality:function(e,t,n,r){if(f.isDefined(e)){f.isString(t)&&(t={attribute:t});var a=(t=f.extend({},this.options,t)).message||this.message||"is not equal to %{attribute}";if(f.isEmpty(t.attribute)||!f.isString(t.attribute))throw new Error("The attribute must be a non empty string");var i=f.getDeepObjectValue(r,t.attribute);return(t.comparator||function(e,t){return e===t})(e,i,t,n,r)?void 0:f.format(a,{attribute:f.prettify(t.attribute)})}},url:function(e,t){if(f.isDefined(e)){var n=(t=f.extend({},this.options,t)).message||this.message||"is not a valid url",r=t.schemes||this.schemes||["http","https"],a=t.allowLocal||this.allowLocal||!1;if(!f.isString(e))return n;var i="^(?:(?:"+r.join("|")+")://)(?:\\S+(?::\\S*)?@)?(?:",o="(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";return a?o+="?":i+="(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})",i+="(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*"+o+")(?::\\d{2,5})?(?:[/?#]\\S*)?$",new RegExp(i,"i").exec(e)?void 0:n}}},o.formatters={detailed:function(e){return e},flat:f.flattenErrorsToArray,grouped:function(e){var t;for(t in e=f.groupErrorsByAttribute(e))e[t]=f.flattenErrorsToArray(e[t]);return e},constraint:function(e){var t;for(t in e=f.groupErrorsByAttribute(e))e[t]=e[t].map(function(e){return e.validator}).sort();return e}},o.exposeModule(o,this,e,t,n)}.call(this,"undefined"!=typeof exports?exports:null,"undefined"!=typeof module?module:null,"undefined"!=typeof define?define:null),define("can-validate-validatejs",["require","exports","module","can-reflect","validate.js"],function(e,t,n){var a=e("can-reflect"),i=e("validate.js"),r=function(t){return function(e){return i.single(e,t)}};r.many=function(r){return function(e){var t,n=i(e,r,{format:"detailed",fullMessages:!1});return n&&(t=[],a.eachIndex(n,function(e){t.push({message:e.options.message||e.error,related:[e.attribute]})})),t}},r.validatejs=i,n.exports=r}),define("can-validate",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var i=e("can-reflect"),r={},o={object:function(e){var n=0<e.length?{}:void 0;return i.eachIndex(e,function(t){i.eachIndex(t.related,function(e){n[e]||(n[e]=[]),n[e].push(t.message)})}),n},flat:function(e){var t=0<e.length?[]:void 0;return i.eachIndex(e,function(e){t.push(e.message)}),t},errors:function(e){return 0<e.length?e:void 0},"errors-object":function(e){var n=0<e.length?{}:void 0;return i.eachIndex(e,function(t){i.eachIndex(t.related,function(e){n[e]||(n[e]=[]),n[e].push(t)})}),n}},s=function(e){var t=[];return"string"==typeof e&&t.push({message:e,related:["*"]}),"object"!=typeof e||Array.isArray(e)||(e.related?Array.isArray(e.related)||(e.related=[e.related]):e.related="*",t.push(e)),Array.isArray(e)&&i.eachIndex(e,function(e){[].push.apply(t,s(e))}),t};r.formatErrors=function(e,t){var n,r,a=(r=[],("string"==typeof(n=e)||"object"==typeof n&&!Array.isArray(n))&&(n=[n]),null!=n&&i.eachIndex(n,function(e){[].push.apply(r,s(e))}),r);return t&&o[t]?o[t](a):a},n.exports=r}),define("can-define-validate-validatejs",["require","exports","module","can-validate-validatejs","can-define","can-assign","can-reflect","can-validate"],function(e,t,n){"use strict";var c=e("can-validate-validatejs"),u=e("can-define"),l=e("can-assign"),f=e("can-reflect"),d=e("can-validate").formatErrors,r=function(e){var t,n,r,a,i,o=(t=e,n={},f.eachKey(t.prototype._define.definitions,function(e,t){e.validate&&0!==f.size(e.validate)&&(n[t]=e.validate)}),n),s=c.many(o);a=function(e){var t=s(e);return d(t,"errors")},i=(r=e).prototype._define,r.prototype.testSet=function(){var e={},t=!1;if(arguments.length){if("object"==typeof arguments[0]&&Boolean(arguments[0])&&(e=arguments[0],t=Boolean(arguments[1])),"string"==typeof arguments[0]&&(e[arguments[0]]=arguments[1]),t)e=new r(e);else{var n=this.serialize();l(n,e),e=n}return a(e)}return this.errors()},r.prototype.errors=function(){var t,e=this._errors;if(arguments.length){var n=d(e,"errors-object");t=[],f.eachIndex(arguments,function(e){[].push.apply(t,n?n[e]:[])}),t=0<t.length?t:void 0}else t=e;return t},u.property(r.prototype,"_errors",{get:function(){return a(this)}},i.dataInitializers,i.computedInitializers)};r.validatejs=c.validatejs,n.exports=r}),define("can/es/can-define-validate-validatejs",["exports","can-define-validate-validatejs"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-validate",["exports","can-validate"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-validate-validatejs",["require","exports","module","can-reflect","validate.js"],function(e,t,n){"use strict";var a=e("can-reflect"),i=e("validate.js"),r=function(t){return function(e){return i.single(e,t)}};r.many=function(r){return function(e){var t,n=i(e,r,{format:"detailed",fullMessages:!1});return n&&(t=[],a.eachIndex(n,function(e){t.push({message:e.options.message||e.error,related:[e.attribute]})})),t}},r.validatejs=i,n.exports=r}),define("can/es/can-validate-validatejs",["exports","can-validate-validatejs"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/es/can-event-dom-radiochange",["exports","can-event-dom-radiochange"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-event-dom-enter",["require","exports","module","can-namespace"],function(e,t,n){"use strict";var r=e("can-namespace");var i={defaultEventType:"enter",addEventListener:function(e,t,a){var n=function(e){if(n="Enter"===(t=e).key,r=13===t.keyCode,n||r)return a.apply(this,arguments);var t,n,r},r=i._eventTypeHandlerMap[t];r||(r=i._eventTypeHandlerMap[t]=new Map),r.set(a,n),this.addEventListener(e,"keyup",n)},removeEventListener:function(e,t,n){var r=i._eventTypeHandlerMap[t];if(r){var a=r.get(n);a&&(r.delete(n),0===r.size&&delete i._eventTypeHandlerMap[t],this.removeEventListener(e,"keyup",a))}},_eventTypeHandlerMap:{}};n.exports=r.domEventEnter=i}),define("can/es/can-event-dom-enter",["exports","can-event-dom-enter"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/ecosystem",["exports","can/es/can-debug","can/es/can-define-backup","can/es/can-define-stream","can/es/can-define-stream-kefir","can/es/can-kefir","can/es/can-observe","can/es/can-stream","can/es/can-stream-kefir","can/es/can-map-compat","can/es/can-stache-converters","can/es/can-view-autorender","can/es/can-super-model","can/es/can-connect-feathers","can/es/can-connect-tag","can/es/can-fixture-socket","can/es/can-ndjson-stream","can/es/can-connect-ndjson","can/es/can-route-mock","can/es/can-define-validate-validatejs","can/es/can-validate","can/es/can-validate-validatejs","can/es/can-event-dom-radiochange","can/es/can-event-dom-enter"],function(e,t,n,r,a,i,o,s,c,u,l,f,d,p,h,v,y,g,m,b,w,x,_,k){"use strict";function O(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"debug",{enumerable:!0,get:function(){return O(t).default}}),Object.defineProperty(e,"defineBackup",{enumerable:!0,get:function(){return O(n).default}}),Object.defineProperty(e,"defineStream",{enumerable:!0,get:function(){return O(r).default}}),Object.defineProperty(e,"defineStreamKefir",{enumerable:!0,get:function(){return O(a).default}}),Object.defineProperty(e,"kefir",{enumerable:!0,get:function(){return O(i).default}}),Object.defineProperty(e,"observe",{enumerable:!0,get:function(){return O(o).default}}),Object.defineProperty(e,"stream",{enumerable:!0,get:function(){return O(s).default}}),Object.defineProperty(e,"streamKefir",{enumerable:!0,get:function(){return O(c).default}}),Object.defineProperty(e,"makeMapCompat",{enumerable:!0,get:function(){return O(u).default}}),Object.defineProperty(e,"stacheConverters",{enumerable:!0,get:function(){return O(l).default}}),Object.defineProperty(e,"viewAutorender",{enumerable:!0,get:function(){return O(f).default}}),Object.defineProperty(e,"superModel",{enumerable:!0,get:function(){return O(d).default}}),Object.defineProperty(e,"connectFeathers",{enumerable:!0,get:function(){return O(p).default}}),Object.defineProperty(e,"connectTag",{enumerable:!0,get:function(){return O(h).default}}),Object.defineProperty(e,"fixtureSocket",{enumerable:!0,get:function(){return O(v).default}}),Object.defineProperty(e,"ndjsonStream",{enumerable:!0,get:function(){return O(y).default}}),Object.defineProperty(e,"connectNDJSON",{enumerable:!0,get:function(){return O(g).default}}),Object.defineProperty(e,"RouteMock",{enumerable:!0,get:function(){return O(m).default}}),Object.defineProperty(e,"defineValidateValidatejs",{enumerable:!0,get:function(){return O(b).default}}),Object.defineProperty(e,"validate",{enumerable:!0,get:function(){return O(w).default}}),Object.defineProperty(e,"validateValidatejs",{enumerable:!0,get:function(){return O(x).default}}),Object.defineProperty(e,"radioChangeEvent",{enumerable:!0,get:function(){return O(_).default}}),Object.defineProperty(e,"enterEvent",{enumerable:!0,get:function(){return O(k).default}})}),define("can/es/can-compute",["exports","can-compute"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-map/bubble",["require","exports","module","can-event-queue/map/map","can-reflect"],function(e,t,n){"use strict";var o=e("can-event-queue/map/map"),s=e("can-reflect"),c={bind:function(e,t){if(!e.__inSetup){var n,r=c.events(e,t),a=r.length;e._bubbleBindings||(e._bubbleBindings={});for(var i=0;i<a;i++)n=r[i],e._bubbleBindings[n]?e._bubbleBindings[n]++:(e._bubbleBindings[n]=1,c.childrenOf(e,n))}},unbind:function(e,t){for(var n,r=c.events(e,t),a=r.length,i=0;i<a;i++)n=r[i],e._bubbleBindings&&e._bubbleBindings[n]--,e._bubbleBindings&&!e._bubbleBindings[n]&&(delete e._bubbleBindings[n],c.teardownChildrenFrom(e,n),0===s.size(e._bubbleBindings)&&delete e._bubbleBindings)},add:function(e,t,n){if(s.isObservableLike(t)&&s.isMapLike(t)&&e._bubbleBindings)for(var r in e._bubbleBindings)e._bubbleBindings[r]&&(c.teardownFromParent(e,t,r),c.toParent(t,e,n,r))},addMany:function(e,t){for(var n=0,r=t.length;n<r;n++)c.add(e,t[n],n)},remove:function(e,t){if(s.isObservableLike(t)&&s.isMapLike(t)&&e._bubbleBindings)for(var n in e._bubbleBindings)e._bubbleBindings[n]&&c.teardownFromParent(e,t,n)},removeMany:function(e,t){for(var n=0,r=t.length;n<r;n++)c.remove(e,t[n])},set:function(e,t,n,r){return s.isObservableLike(n)&&s.isMapLike(n)&&c.add(e,n,t),s.isObservableLike(r)&&s.isMapLike(r)&&c.remove(e,r),n},events:function(e,t){return e.constructor._bubbleRule(t,e)},toParent:function(n,r,a,i){o.listenTo.call(r,n,i,function(){var e=s.toArray(arguments),t=e.shift();e[0]=(s.isObservableLike(r)&&s.isListLike(r)?r.indexOf(n):a)+(e[0]?"."+e[0]:""),t.triggeredNS=t.triggeredNS||{},t.triggeredNS[r._cid]||(t.triggeredNS[r._cid]=!0,o.dispatch.call(r,t,e),"change"===i&&o.dispatch.call(r,e[0],[e[2],e[3]]))})},childrenOf:function(n,r){n._each(function(e,t){e&&e.bind&&c.toParent(e,n,t,r)})},teardownFromParent:function(e,t,n){t&&t.unbind&&o.stopListening.call(e,t,n)},teardownChildrenFrom:function(t,n){t._each(function(e){c.teardownFromParent(t,e,n)})},isBubbling:function(e,t){return e._bubbleBindings&&e._bubbleBindings[t]}};n.exports=c}),define("can-map/map-helpers",["require","exports","module","can-cid","can-assign","can-reflect","can-symbol"],function(e,t,n){"use strict";var s,c=e("can-cid"),r=e("can-assign"),u=e("can-reflect"),a=e("can-symbol"),i=null,o=function(){for(var e in i)i[e].added&&delete i[e].obj._cid;i=null},l={attrParts:function(e,t){return t?[e]:"object"==typeof e?e:(""+e).split(".")},canMakeObserve:function(e){return e&&!u.isPromise(e)&&(Array.isArray(e)||u.isPlainObject(e))},reflectSerialize:function(n){return this.forEach(function(e,t){void 0!==(e=this.___serialize?this.___serialize(t,e):u.serialize(e))&&(n[t]=e)},this),n},reflectUnwrap:function(n){return this.forEach(function(e,t){void 0!==e&&(n[t]=u.unwrap(e))}),n},removeSpecialKeys:function(t){return t&&["_data","constructor","_cid","__bindEvents"].forEach(function(e){delete t[e]}),t},serialize:(s=null,function(a,i,o){var e=c(a),t=!1;return s||(t=!0,s={attr:{},serialize:{}}),s[i][e]=o,a.forEach(function(e,t){var n,r=u.isObservableLike(e)&&s[i][c(e)];void 0!==(n=r||(a["___"+i]?a["___"+i](t,e):l.getValue(a,t,e,i)))&&(o[t]=n)}),t&&(s=null),o}),getValue:function(e,t,n,r){return"attr"===r&&(r=a.for("can.getValue")),u.isObservableLike(n)&&n[r]?n[r]():n},define:null,addComputedAttr:function(n,r,e){n._computedAttrs[r]={compute:e,count:0,handler:function(e,t){n._triggerChange(r,"set",e,t)}}},addToMap:function(e,t){var n;i||(n=o,i={});var r=e._cid,a=c(e);return i[a]||(i[a]={obj:e,instance:t,added:!r}),n},getMapFromObject:function(e){return i&&i[e._cid]&&i[e._cid].instance},twoLevelDeepExtend:function(e,t){for(var n in t)e[n]=e[n]||{},r(e[n],t[n])}};n.exports=l}),define("can-types",["require","exports","module","can-namespace","can-reflect","can-symbol","can-log/dev/dev"],function(e,t,n){"use strict";var r=e("can-namespace"),a=e("can-reflect"),i=e("can-symbol"),o=(e("can-log/dev/dev"),{isMapLike:function(e){return a.isObservableLike(e)&&a.isMapLike(e)},isListLike:function(e){return a.isObservableLike(e)&&a.isListLike(e)},isPromise:function(e){return a.isPromise(e)},isConstructor:function(e){return a.isConstructorLike(e)},isCallableForValue:function(e){return e&&a.isFunctionLike(e)&&!a.isConstructorLike(e)},isCompute:function(e){return e&&e.isComputed},get iterator(){return i.iterator||i.for("iterator")},DefaultMap:null,DefaultList:null,queueTask:function(e){var t=e[2]||[];e[0].apply(e[1],t)},wrapElement:function(e){return e},unwrapElement:function(e){return e}});if(r.types)throw new Error("You can't have two versions of can-types, check your dependencies");n.exports=r.types=o}),define("can-cid/helpers",function(e,t,n){"use strict";n.exports={each:function(e,t,n){for(var r in e)t.call(n,e[r],r);return e}}}),define("can-cid/set/set",["require","exports","module","can-cid","can-cid/helpers"],function(e,t,n){"use strict";var r,a=e("can-cid").get,i=e("can-cid/helpers");"undefined"!=typeof Set?r=Set:((r=function(){this.values={}}).prototype.add=function(e){this.values[a(e)]=e},r.prototype.delete=function(e){var t=a(e)in this.values;return t&&delete this.values[a(e)],t},r.prototype.forEach=function(e,t){i.each(this.values,e,t)},r.prototype.has=function(e){return a(e)in this.values},r.prototype.clear=function(){return this.values={}},Object.defineProperty(r.prototype,"size",{get:function(){var e=0;return i.each(this.values,function(){e++}),e}}));n.exports=r}),define("can-cid/map/map",["require","exports","module","can-cid","can-cid/helpers"],function(e,t,n){"use strict";var r,a=e("can-cid").get,i=e("can-cid/helpers");"undefined"!=typeof Map?r=Map:((r=function(){this.values={}}).prototype.set=function(e,t){this.values[a(e)]={key:e,value:t}},r.prototype.delete=function(e){var t=a(e)in this.values;return t&&delete this.values[a(e)],t},r.prototype.forEach=function(t,n){i.each(this.values,function(e){return t.call(n||this,e.value,e.key,this)},this)},r.prototype.has=function(e){return a(e)in this.values},r.prototype.get=function(e){var t=this.values[a(e)];return t&&t.value},r.prototype.clear=function(){return this.values={}},Object.defineProperty(r.prototype,"size",{get:function(){var e=0;return i.each(this.values,function(){e++}),e}}));n.exports=r}),define("can-map",["require","exports","module","can-map/bubble","can-map/map-helpers","can-event-queue/map/map","can-event-queue/type/type","can-construct","can-observation-recorder","can-stache-key","can-compute","can-single-reference","can-namespace","can-log/dev/dev","can-cid","can-assign","can-types","can-reflect","can-symbol","can-cid/set/set","can-cid/map/map","can-queues"],function(e,t,n){"use strict";var i=e("can-map/bubble"),o=e("can-map/map-helpers"),s=e("can-event-queue/map/map"),r=e("can-event-queue/type/type"),a=e("can-construct"),c=e("can-observation-recorder"),u=e("can-stache-key"),l=e("can-compute"),f=e("can-single-reference"),d=e("can-namespace"),p=(e("can-log/dev/dev"),e("can-cid")),h=e("can-assign"),v=e("can-types"),y=e("can-reflect"),g=e("can-symbol"),m=e("can-cid/set/set"),b=e("can-cid/map/map"),w=e("can-queues"),x={constructor:!0},_={}.hasOwnProperty,k=a.extend({setup:function(e){if(a.setup.apply(this,arguments),this._computedPropertyNames=[],k){for(var t in r(this),this[g.for("can.defineInstanceKey")]=function(e,t){void 0!==t.value&&(this.defaults[e]=t.value),!1===t.enumerable&&(this.enumerable[e]=!1)},this.defaults||(this.defaults={}),this.enumerable||(this.enumerable={}),this.prototype)"define"!==t&&"constructor"!==t&&("function"!=typeof this.prototype[t]||this.prototype[t].prototype instanceof a)?this.defaults[t]=this.prototype[t]:y.isObservableLike(this.prototype[t])&&this._computedPropertyNames.push(t);o.define&&o.define(this,e.prototype.define)}},shortName:"Map",_bubbleRule:function(e){return"change"===e||0<=e.indexOf(".")?["change"]:[]},addEventListener:s.addEventListener,removeEventListener:s.removeEventListener,keys:function(e){return y.getOwnEnumerableKeys(e)}},{setup:function(e){y.isObservableLike(e)&&"function"==typeof e.serialize&&(e=e.serialize()),this._data=Object.create(null),p(this,".map"),this._setupComputedProperties();var t=e&&o.addToMap(e,this),n=this._setupDefaults(e),r=h(y.assignDeep({},n),e);this.attr(r),t&&t()},_setupComputedProperties:function(){this._computedAttrs=Object.create(null);for(var e=this.constructor._computedPropertyNames,t=0,n=e.length;t<n;t++){var r=e[t];o.addComputedAttr(this,r,this[r])}},_setupDefaults:function(){return this.constructor.defaults||{}},attr:function(e,t){var n=typeof e;return void 0===e?this._getAttrs():"string"!==n&&"number"!==n?this._setAttrs(e,t):1===arguments.length?this._get(e):(this._set(e+"",t),this)},_get:function(e){var t=(e+="").indexOf(".");if(0<=t){var n=this.___get(e);if(void 0!==n)return c.add(this,e),n;var r=e.substr(0,t),a=e.substr(t+1),i=this.__get(r);return i&&y.getKeyValue(i,a)}return this.__get(e)},__get:function(e){return x[e]||this._computedAttrs[e]||c.add(this,e),this.___get(e)},___get:function(e){if(void 0===e)return this._data;var t=this._computedAttrs[e];return t?y.getValue(t.compute):_.call(this._data,e)?this._data[e]:void 0},_set:function(e,t,n){var r,a=(e+="").indexOf(".");if(0<=a&&!n){var i=e.substr(0,a),o=e.substr(a+1);r=this.__inSetup?void 0:this.___get(i),y.isMapLike(r)?y.setKeyValue(r,o,t):(r=this.__inSetup?void 0:this.___get(e),this.__convert&&(t=this.__convert(e,t)),this.__set(e,this.__type(t,e),r))}else r=this.__inSetup?void 0:this.___get(e),this.__convert&&(t=this.__convert(e,t)),this.__set(e,this.__type(t,e),r)},__type:function(e,t){if("object"!=typeof e||y.isObservableLike(e)||!o.canMakeObserve(e)||y.isListLike(e))return e;var n=o.getMapFromObject(e);return n||new(this.constructor.Map||k)(e)},__set:function(e,t,n){if(t!==n||!Object.prototype.hasOwnProperty.call(this._data,e)){var r=this._computedAttrs[e],a=r||void 0!==n||_.call(this.___get(),e)?"set":"add";this.___set(e,"object"==typeof t?i.set(this,e,t,n):t),r&&r.count||this._triggerChange(e,a,t,n),"object"==typeof n&&i.teardownFromParent(this,n)}},___set:function(e,t){var n=this._computedAttrs[e];n?y.setValue(n.compute,t):this._data[e]=t,"function"==typeof this.constructor.prototype[e]||n||(this[e]=t)},removeAttr:function(e){return this._remove(e)},_remove:function(e){var t=o.attrParts(e),n=t.shift(),r=this.___get(n);return t.length&&r?y.deleteKeyValue(r,t.join(".")):("string"==typeof e&&~e.indexOf(".")&&(n=e),this.__remove(n,r),r)},__remove:function(e,t){e in this._data&&(this.___remove(e),this._triggerChange(e,"remove",void 0,t))},___remove:function(e){delete this._data[e],e in this.constructor.prototype||delete this[e]},___serialize:function(e,t){return this._legacyAttrBehavior?o.getValue(this,e,t,"serialize"):y.serialize(t,b)},_getAttrs:function(){return this._legacyAttrBehavior?o.serialize(this,"attr",{}):y.unwrap(this,b)},_setAttrs:function(e,t){return this._legacyAttrBehavior?this.__setAttrs(e,t):(!0===t||"true"===t?this[g.for("can.updateDeep")](e):this[g.for("can.assignDeep")](e),this)},__setAttrs:function(n,r){n=h({},n);var e,a,i=this;for(e in w.batch.start(),this._each(function(e,t){"_cid"!==t&&(void 0!==(a=n[t])?(i.__convert&&(a=i.__convert(t,a)),v.isMapLike(e)&&o.canMakeObserve(a)?!0===r?y.updateDeep(e,a):y.assignDeep(e,a):e!==a&&i.__set(t,i.__type(a,t),e),delete n[t]):r&&i.removeAttr(t))}),n)"_cid"!==e&&(a=n[e],this._set(e,a,!0));return w.batch.stop(),this},serialize:function(){return y.serialize(this,b)},_triggerChange:function(e,t,n,r,a){w.batch.start(),i.isBubbling(this,"change")&&s.dispatch.call(this,{type:"change",target:this,batchNum:a},[e,t,n,r]),s.dispatch.call(this,{type:e,target:this,batchNum:a,patches:[{type:"set",key:e,value:n}]},[n,r]),"remove"!==t&&"add"!==t||s.dispatch.call(this,{type:"__keys",target:this,batchNum:a}),w.batch.stop()},compute:function(t){if("function"==typeof this.constructor.prototype[t])return l(this[t],this);var n=u.reads(t),r=n.length-1;return l(function(e){if(!arguments.length)return u.get(this,t);u.write(this,n[r].key,e,{})},this)},forEach:function(e,t){for(var n,r,a=y.getOwnEnumerableKeys(this),i=0,o=a.length;i<o&&(n=a[i],r=this.attr(n),!1!==e.call(t||r,r,n,this));i++);return this},_each:function(e){var t=this.___get();for(var n in t)_.call(t,n)&&e(t[n],n)},dispatch:s.dispatch});s(k.prototype),k.prototype.addEventListener=function(e,t){var n=this._computedAttrs&&this._computedAttrs[e];return n&&n.compute&&(n.count?n.count++:(n.count=1,y.onValue(n.compute,n.handler,"notify"))),i.bind(this,e),s.addEventListener.apply(this,arguments)},k.prototype.removeEventListener=function(e,t){var n=this._computedAttrs&&this._computedAttrs[e];return n&&(1===n.count?(n.count=0,y.offValue(n.compute,n.handler)):n.count--),i.unbind(this,e),s.removeEventListener.apply(this,arguments)},k.prototype.on=k.prototype.bind=k.prototype.addEventListener,k.prototype.off=k.prototype.unbind=k.prototype.removeEventListener,k.on=k.bind=k.addEventListener,k.off=k.unbind=k.removeEventListener,y.assignSymbols(k.prototype,{"can.isMapLike":!0,"can.isListLike":!1,"can.isValueLike":!1,"can.getKeyValue":k.prototype._get,"can.setKeyValue":k.prototype._set,"can.deleteKeyValue":k.prototype._remove,"can.getOwnEnumerableKeys":function(){this.__inSetup||c.add(this,"__keys");var t=this.constructor.enumerable;return t?Object.keys(this._data).filter(function(e){return!1!==t[e]},this):Object.keys(this._data)},"can.assignDeep":function(e){w.batch.start(),y.assignDeepMap(this,o.removeSpecialKeys(y.assignMap({},e))),w.batch.stop()},"can.updateDeep":function(e){w.batch.start(),y.updateDeepMap(this,o.removeSpecialKeys(y.assignMap({},e))),w.batch.stop()},"can.unwrap":o.reflectUnwrap,"can.serialize":o.reflectSerialize,"can.onKeyValue":function(e,r,t){var n=function(e,t,n){r.call(this,t,n)};f.set(r,this,n,e),this.addEventListener(e,n,t)},"can.offKeyValue":function(e,t,n){this.removeEventListener(e,f.getAndDelete(t,this,e),n)},"can.keyHasDependencies":function(e){return!!(this._computedAttrs&&this._computedAttrs[e]&&this._computedAttrs[e].compute)},"can.getKeyDependencies":function(e){var t;return this._computedAttrs&&this._computedAttrs[e]&&this._computedAttrs[e].compute&&((t={}).valueDependencies=new m,t.valueDependencies.add(this._computedAttrs[e].compute)),t}}),v.DefaultMap||(v.DefaultMap=k),n.exports=d.Map=k}),define("can/es/can-map",["exports","can-map"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-list",["require","exports","module","can-namespace","can-map","can-map/bubble","can-map/map-helpers","can-queues","can-event-queue/map/map","can-observation-recorder","can-cid","can-reflect","can-assign","can-types","can-symbol","can-cid/map/map"],function(e,t,n){"use strict";var r,a=e("can-namespace"),o=e("can-map"),u=e("can-map/bubble"),i=e("can-map/map-helpers"),l=e("can-queues"),s=e("can-event-queue/map/map"),c=e("can-observation-recorder"),f=e("can-cid"),d=e("can-reflect"),p=e("can-assign"),h=e("can-types"),v=e("can-symbol"),y=e("can-cid/map/map"),g=[].splice,m=(r={0:"a",length:1},g.call(r,0,1),!r[0]),b=function(e,t,n){!t||!t.serialize||t instanceof e?n.push(t):n.push(new e(t.serialize()))},w=o.extend({Map:o},{setup:function(e,t){var n;this.length=0,f(this,".map"),this._setupComputedProperties(),e=void 0===e?[]:d.toArray(e),d.isPromise(e)?this.replace(e):(n=e.length&&i.addToMap(e,this),this.push.apply(this,e)),n&&n(),p(this,t)},_triggerChange:function(e,t,n,r){l.batch.start();var a,i=+e;~(""+e).indexOf(".")||isNaN(i)?o.prototype._triggerChange.apply(this,arguments):(u.isBubbling(this,"change")&&s.dispatch.call(this,{type:"change",target:this},[e,t,n,r]),"add"===t?(a=[{insert:n,index:i,deleteCount:0,type:"splice"}],s.dispatch.call(this,{type:t,patches:a},[n,i]),s.dispatch.call(this,"length",[this.length])):"remove"===t?(a=[{index:i,deleteCount:r.length,type:"splice"}],s.dispatch.call(this,{type:t,patches:a},[r,i]),s.dispatch.call(this,"length",[this.length])):s.dispatch.call(this,t,[n,i])),l.batch.stop()},___get:function(e){if(e){var t=this._computedAttrs[e];return t&&t.compute?d.getValue(t.compute):this[e]&&this[e].isComputed&&"function"==typeof this.constructor.prototype[e]?d.getValue(this[e]):this[e]}return this},__set:function(e,t,n){if("number"!=typeof(e=isNaN(+e)||e%1?e:+e))return o.prototype.__set.call(this,""+e,t,n);if(e>this.length-1){var r=new Array(e+1-this.length);return r[r.length-1]=t,this.push.apply(this,r),r}return this.splice(e,1,t),this},___set:function(e,t){this[e]=t,+e>=this.length&&(this.length=+e+1)},__remove:function(e,t){isNaN(+e)?(delete this[e],this._triggerChange(e,"remove",void 0,t)):this.splice(e,1)},_each:function(e){for(var t=this.___get(),n=0;n<t.length;n++)e(t[n],n)},serialize:function(){return d.serialize(this,y)},splice:function(e,t){var n,r,a,i=d.toArray(arguments),o=[],s=2<i.length;for(e=e||0,n=0,r=i.length-2;n<r;n++)i[a=n+2]=this.__type(i[a],a),o.push(i[a]),this[n+e]!==i[a]&&(s=!1);if(s&&this.length<=o.length)return o;void 0===t&&(t=i[1]=this.length-e);var c=g.apply(this,i);if(!m)for(n=this.length;n<c.length+this.length;n++)delete this[n];return l.batch.start(),0<t&&(u.removeMany(this,c),this._triggerChange(""+e,"remove",void 0,c)),2<i.length&&(u.addMany(this,o),this._triggerChange(""+e,"add",o,c)),l.batch.stop(),c}});d.eachKey({push:"length",unshift:0},function(i,e){var o=[][e];w.prototype[e]=function(){for(var e,t,n=[],r=i?this.length:0,a=arguments.length;a--;)t=arguments[a],n[a]=u.set(this,a,this.__type(t,a));return e=o.apply(this,n),this.comparator&&!n.length||this._triggerChange(""+r,"add",n,void 0),e}}),d.eachKey({pop:"length",shift:0},function(a,i){w.prototype[i]=function(){if(this.length){var e,t=(e=arguments)[0]&&Array.isArray(e[0])?e[0]:d.toArray(e),n=a&&this.length?this.length-1:0,r=[][i].apply(this,t);return this._triggerChange(""+n,"remove",void 0,[r]),r&&r.removeEventListener&&u.remove(this,r),r}}}),p(w.prototype,{indexOf:function(e,t){c.add(this,"length");for(var n=t||0,r=this.length;n<r;n++)if(this.attr(n)===e)return n;return-1},join:function(){return c.add(this,"length"),[].join.apply(this,arguments)},reverse:function(){var e=[].reverse.call(d.toArray(this));return this.replace(e)},slice:function(){c.add(this,"length");var e=Array.prototype.slice.apply(this,arguments);return new this.constructor(e)},concat:function(){var n=[],r=this.constructor.Map;return d.each(arguments,function(e){if(d.isObservableLike(e)&&d.isListLike(e)||Array.isArray(e)){var t=d.isObservableLike(e)&&d.isListLike(e)?d.toArray(e):e;d.each(t,function(e){b(r,e,n)})}else b(r,e,n)}),new this.constructor(Array.prototype.concat.apply(d.toArray(this),n))},forEach:function(e,t){for(var n,r=0,a=this.attr("length");r<a&&(void 0===(n=this.attr(r))||!1!==e.call(t||n,n,r,this));r++);return this},replace:function(e){if(d.isPromise(e)){this._promise&&(this._promise.__isCurrentPromise=!1);var t=this._promise=e;t.__isCurrentPromise=!0;var n=this;e.then(function(e){t.__isCurrentPromise&&n.replace(e)})}else e=void 0===e?[]:d.toArray(e),this.splice.apply(this,[0,this.length].concat(e));return this},filter:function(r,a){var i=new this.constructor,o=this;return this.forEach(function(e,t,n){r.call(a||o,e,t,o)&&i.push(e)}),i},map:function(a,i){var o=new w,s=this;return this.forEach(function(e,t,n){var r=a.call(i||s,e,t,s);o.push(r)}),o},sort:function(e){var t=Array.prototype.slice.call(this);return Array.prototype.sort.call(t,e),this.splice.apply(this,[0,t.length].concat(t)),this}});var x=o.prototype.__type;o.prototype.__type=function(e,t){if("object"==typeof e&&Array.isArray(e)){var n=i.getMapFromObject(e);return n||new w(e)}return x.apply(this,arguments)};var _=o.setup;o.setup=function(){_.apply(this,arguments),this.prototype instanceof w||(this.List=o.List.extend({Map:this},{}))},h.DefaultList||(h.DefaultList=w),d.assignSymbols(w.prototype,{"can.isMoreListLikeThanMapLike":!0,"can.isListLike":!0,"can.getKeyValue":w.prototype._get,"can.setKeyValue":w.prototype._set,"can.deleteKeyValue":w.prototype._remove,"can.getOwnEnumerableKeys":function(){return Object.keys(this._data||{}).concat(this.map(function(e,t){return t}))},"can.assignDeep":function(e){l.batch.start(),d.assignDeepList(this,e),l.batch.stop()},"can.updateDeep":function(e){l.batch.start(),d.updateDeepList(this,e),l.batch.stop()},"can.unwrap":i.reflectUnwrap,"can.serialize":i.reflectSerialize,"can.onKeysAdded":function(e){this[v.for("can.onKeyValue")]("add",e)},"can.onKeysRemoved":function(e){this[v.for("can.onKeyValue")]("remove",e)},"can.splice":function(e,t,n){this.splice.apply(this,[e,t].concat(n))}}),o.List=w,n.exports=a.List=w}),define("can/es/can-list",["exports","can-list"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-map-define",["require","exports","module","can-log/dev/dev","can-assign","can-event-queue/map/map","can-queues","can-map/map-helpers","can-map","can-compute","can-reflect","can-observation-recorder","can-list"],function(e,t,n){"use strict";e("can-log/dev/dev");var o=e("can-assign"),f=e("can-event-queue/map/map"),d=e("can-queues"),s=e("can-map/map-helpers"),i=e("can-map"),r=e("can-compute"),c=e("can-reflect"),u=e("can-observation-recorder");e("can-list");var l={},p=function(e){return"object"==typeof e&&"serialize"in e},h=function(e){var t=!0;return p(e)&&(t=!!e.serialize),t},v=function(e,t,n){var r,a;if(n){if(r=n[t],a=n["*"],r&&void 0!==r[e])return r[e];if(a&&void 0!==a[e])return a[e]}};s.define=function(t,e){var n=t.prototype.define;if(e){var r={};s.twoLevelDeepExtend(r,e),s.twoLevelDeepExtend(r,n),o(n,r)}for(var a in t.defaultGenerators={},n){var i=n[a].type;"string"==typeof i&&"object"==typeof l.types[i]&&(delete n[a].type,o(n[a],l.types[i])),"value"in n[a]&&("function"==typeof n[a].value?t.defaultGenerators[a]=n[a].value:t.defaults[a]=n[a].value),"function"==typeof n[a].Value&&function(e){t.defaultGenerators[a]=function(){return new e}}(n[a].Value)}};var y=i.prototype._setupDefaults;i.prototype._setupDefaults=function(e){var n=o({},y.call(this)),r={},t=this.constructor,a=this._get;for(var i in this._get=function(e){var t=-1!==e.indexOf(".")?e.substr(0,e.indexOf(".")):e;return t in n&&!(t in r)&&(this.attr(t,n[t]),r[t]=!0),a.apply(this,arguments)},t.defaultGenerators)e&&i in e||(n[i]=t.defaultGenerators[i].call(this));return delete this._get,n};var a=i.prototype,g=a.__set;a.__set=function(t,e,n,r,a){var i=this,o=function(e){return!1!==(a&&a.call(i,e))&&f.dispatch.call(i,"error",[t,e],!0),!1},s=v("set",t,this.define),c=v("get",t,this.define);if(s){d.batch.start();var u=!1,l=s.call(this,e,function(e){c?i[t](e):g.call(i,t,e,n,r,o),u=!0},o,c?this._computedAttrs[t].compute.computeInstance.lastSetValue.get():n);return c?(void 0!==l&&!u&&1<=s.length&&this._computedAttrs[t].compute(l),void d.batch.stop()):void 0===l&&!u&&1<s.length?void d.batch.stop():(u||g.call(i,t,0===s.length&&void 0===l?e:l,n,r,o),d.batch.stop(),this)}return g.call(i,t,e,n,r,o),this},l.types={date:function(e){var t=typeof e;return"string"===t?(e=Date.parse(e),isNaN(e)?null:new Date(e)):"number"===t?new Date(e):e},number:function(e){return null==e?e:+e},boolean:function(e){return null==e?e:!("false"===e||"0"===e||!e)},htmlbool:function(e){return"string"==typeof e||!!e},"*":function(e){return e},string:function(e){return null==e?e:""+e},compute:{set:function(e,t,n,r){return e&&e.isComputed?e:r&&r.isComputed?(r(e),r):e},get:function(e){return e&&e.isComputed?e():e}}};var m=a.__type;a.__type=function(e,t){var n=v("type",t,this.define),r=v("Type",t,this.define),a=e;return"string"==typeof n&&(n=l.types[n]),n||r?(n&&(a=n.call(this,a,t)),!r||null==a||a instanceof r||(a=new r(a)),a):(c.isPlainObject(a)&&a.define&&(a=new(a=i.extend(a))),m.call(this,a,t))};var b=a.__remove;a.__remove=function(e,t){var n,r=v("remove",e,this.define);return r?(d.batch.start(),!1===(n=r.call(this,t))?void d.batch.stop():(n=b.call(this,e,t),d.batch.stop(),n)):b.call(this,e,t)};var w=a._setupComputedProperties;a._setupComputedProperties=function(){for(var e in w.apply(this,arguments),this.define){var t=this.define[e].get;t&&s.addComputedAttr(this,e,r.async(void 0,t,this))}};var x=a.___serialize,_=function(e,t,n){var r="*"!==t&&v("serialize",t,e.define);return void 0===r?x.call(e,t,n):!1!==r?"function"==typeof r?r.call(e,n,t):x.call(e,t,n):void 0};a.___serialize=function(e,t){return _(this,e,t)};var k=a.serialize;a.serialize=function(e){var t,n=k.apply(this,arguments);if(e)return n;for(var r in this.define)r in n||this.define&&(this.define[r]&&this.define[r].serialize||this.define["*"]&&this.define["*"].serialize)&&void 0!==(t=_(this,r,this.attr(r)))&&(n[r]=t);return n},c.assignSymbols(a,{"can.hasKey":function(e){var t=this.define&&e in this.define,n=this._data&&e in this._data;return t||n||e in this},"can.getOwnEnumerableKeys":function(){this.__inSetup||u.add(this,"__keys");var e,t,n=function(e){var t=[],n=e&&e["*"];for(var r in e){var a=e[r],i=h(n);"object"==typeof a&&"serialize"in a?i=!!a.serialize:"object"!=typeof a||p(n)||(i=!a.get),i&&t.push(r)}return t}(this.define),r=Object.keys(this._data),a=h(this.define&&this.define["*"]),i=this.constructor.enumerable;for(r=r.filter(function(e){return i?a&&!1!==i[e]:a}),e=0;e<r.length;e++)t=r[e],!(n.indexOf(t)<0)||this.define&&this.define[t]||n.push(r[e]);return n}}),n.exports=l}),define("can/es/can-map-define",["exports","can-map-define"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can-set-legacy",["require","exports","module","can-query-logic","can-reflect","can-key/transform/transform","can-key/delete/delete","can-key/get/get","can-query-logic/src/helpers","can-query-logic/src/types/make-enum","can-query-logic/src/set"],function(e,t,n){var r,a=e("can-query-logic"),o=e("can-reflect"),i=e("can-key/transform/transform"),s=e("can-key/delete/delete"),c=e("can-key/get/get"),u=e("can-query-logic/src/helpers"),l=e("can-query-logic/src/types/make-enum"),f=e("can-query-logic/src/set"),d=function(){};l(d,[!0,!1],function(e){return"true"===e||"false"!==e&&e});var p={UNIVERSAL:f.UNIVERSAL,EMPTY:f.EMPTY,UNDEFINABLE:f.UNDEFINABLE,UNKNOWABLE:f.UNKNOWABLE,Algebra:function(){var r={schema:[],hydrate:[],serialize:[]};o.eachIndex(arguments,function(e){for(var t in e){if(!r[t])throw new Error("can-query-logic: This type of configuration is not supported. Please use can-query-logic directly.");r[t].push(e[t])}});var e=o.assignSymbols({},{"can.getSchema":function(){var t={kind:"record",identity:[],keys:{}};return r.schema.forEach(function(e){e(t)}),t.identity.length||t.identity.push("id"),t}});return new a(e,{toQuery:function(e){return r.hydrate.reduce(function(e,t){return t(e)},{filter:e})},toParams:function(e){if(f.isSpecial(e))return e;if(Array.isArray(e.filter))return f.UNDEFINABLE;var t=e.filter||{};if(function e(t,n,r,a){if(t&&"object"==typeof t)for(var i in t)if(n[i]){if("function"!=typeof n[i])return!0;r[a]=n[i](t)}else if(e(t[i],n,t,i))return!0;return!1}(t,{$ne:!0,$in:function(e){return e.$in}}))return f.UNDEFINABLE;var n=r.serialize.reduce(function(e,t){return t(e)},e);return t=n.filter||{},delete n.filter,o.assign(n,t)}})},Translate:function(e,r){if("where"!==e)throw new Error("can-query-logic/compat.Translate is only able to translate the where clause");return{hydrate:function(e){var t=o.serialize(e),n=t.filter[r];return delete t.filter[r],n&&o.assign(t.filter,n),t},serialize:function(e){if(e.filter){var t=o.serialize(e),n=e.filter;return t.filter={},t.filter[r]=n,t}return e}}},props:{boolean:function(t){return{schema:function(e){e.keys[t]=d}}},dotNotation:function(){return{}},enum:function(t,e){function n(){}return l(n,e),{schema:function(e){e.keys[t]=n}}},id:function(t){return{schema:function(e){e.identity.push(t)}}},offsetLimit:function(n,r){return n=n||"offset",r=r||"limit",{hydrate:function(e){var t=o.serialize(e);return(n in t.filter||r in t.filter)&&(t.page={}),n in t.filter&&(t.page.start=parseInt(t.filter[n],10),delete t.filter[n]),r in t.filter&&(t.page.end=(t.page.start||0)+parseInt(t.filter[r],10)-1,delete t.filter[r]),t},serialize:function(e){var t=o.serialize(e);return t.page&&(t[n]=t.page.start,t[r]=t.page.end-t.page.start+1,delete t.page),t}}},rangeInclusive:function(e,t){var n={};n["filter."+e]="page.start",n["filter."+t]="page.end";var r={"page.start":e,"page.end":t};return{hydrate:function(e){var t=i(e,n);return t.page&&(t.page.start&&(t.page.start=parseInt(t.page.start,10)),t.page.end&&(t.page.end=parseInt(t.page.end,10))),t},serialize:function(e){return i(e,r)}}},ignore:function(n){return{hydrate:function(e){var t=o.serialize(e);return delete t.filter[n],t}}},sort:function(i,e){if(i||(i="sort"),e)throw new Error("can-query-logic/compat.sort - sortFunc is not supported");return{hydrate:function(e){var t,n=o.serialize(e),r=c(n,"filter."+i);return void 0!==r&&(s(n,"filter."+i),n.sort="desc"===((t=r.split(" "))[1]||"").toLowerCase()?"-"+t[0]:t[0]),n},serialize:function(e){var t,n,r=o.serialize(e),a=r.sort;return void 0!==a&&(delete r.sort,r[i]=(t=a,(n=u.sortData(t)).desc?"-"+n.prop:n.prop)),r}}}}};function h(e){return e?e instanceof a?e:new p.Algebra(e):r}function v(r){p[r]=function(e,t,n){return h(n)[r](e,t)}}v("difference"),v("union"),v("intersection"),v("isSubset"),v("isEqual"),v("isProperSubset"),p.count=function(e,t){return h(t).count(e)},p.comparators=p.props,r=new p.Algebra,n.exports=p}),define("can/es/can-set-legacy",["exports","can-set-legacy"],function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return(e=t,e&&e.__esModule?e:{default:e}).default;var e}})}),define("can/legacy",["exports","can/es/can-compute","can/es/can-map","can/es/can-list","can/es/can-map-define","can/es/can-set-legacy"],function(e,t,n,r,a,i){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"compute",{enumerable:!0,get:function(){return o(t).default}}),Object.defineProperty(e,"CanMap",{enumerable:!0,get:function(){return o(n).default}}),Object.defineProperty(e,"CanList",{enumerable:!0,get:function(){return o(r).default}}),Object.defineProperty(e,"canMapDefine",{enumerable:!0,get:function(){return o(a).default}}),Object.defineProperty(e,"set",{enumerable:!0,get:function(){return o(i).default}})}),define("can",["exports","can/core","can/ecosystem","can/legacy"],function(t,n,r,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return n[e]}})}),Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}),Object.keys(a).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}})})}),function(e){e._define=e.define,e.define=e.define.orig}("object"==typeof self&&self.Object==Object?self:"object"==typeof process&&"[object process]"===Object.prototype.toString.call(process)?global:window);
(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(require,module,exports){require("core-js/shim");require("regenerator/runtime")},{"core-js/shim":2,"regenerator/runtime":3}],2:[function(require,module,exports){!function(returnThis,framework,undefined){"use strict";var global=returnThis(),OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,clearTimeout=global.clearTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var toString=ObjectProto[TO_STRING];var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},TO_STRING_TAG=TO_STRING+"Tag";function setToStringTag(it,tag,stat){if(it)has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG)||hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,REFERENCE_GET;function part(){var length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return partial(this,args,length,holder,_,false)}function partial(fn,argsPart,lengthPart,holder,_,bind,context){assertFunction(fn);return function(){var that=bind?context:this,length=arguments.length,i=0,j=0,args;if(!holder&&!length)return invoke(fn,argsPart,that);args=argsPart.slice();if(holder)for(;lengthPart>i;i++)if(args[i]===_)args[i]=arguments[j++];while(length>j)args.push(arguments[j++]);return invoke(fn,args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&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(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){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]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,ownKeys=function(it){return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)},has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object;function get(object,key){if(has(object,key))return object[key]}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=ES5Object(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn,that){var O=Object(assertDefined(this)),self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el,fromIndex){var O=ES5Object(assertDefined(this)),length=toLength(O.length),index=toIndex(fromIndex,length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function turn(mapfn,target){assertFunction(mapfn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;for(;length>index;index++){if(mapfn(memo,O[index],index,this)===false)break}return memo}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},0,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;var ITERATOR="iterator",SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),FF_ITERATOR="@@"+ITERATOR,SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);defineIterator(Base,NAME,createIter(DEFAULT),DEFAULT==VALUE?"values":"entries");DEFAULT&&$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:createIter(KEY+VALUE),keys:createIter(KEY),values:createIter(VALUE)})}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it);return SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){return assertObject((it[SYMBOL_ITERATOR]||Iterators[classof(it)]).call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var html=document&&document.documentElement;var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(NODE)module.exports=core;if(isFunction(define)&&define.amd)define(function(){return core});if(!NODE||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,"+"species,split,toPrimitive,unscopables"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(GLOBAL,{Reflect:{ownKeys:ownKeys}})}(safeSymbol("tag"),{},true);!function(isFinite,tmp){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(it){return(it=+it)==0||it!=it?it:it<0?-1:1},pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return x<1?NaN:log(x+sqrt(x*x-1))},asinh:asinh,atanh:function(x){return x==0?+x:log((1+ +x)/(1-x))/2},cbrt:function(x){return sign(x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x)+exp(-x))/2},expm1:function(x){return x==0?+x:x>-1e-6&&x<1e-6?+x+x*x/2:exp(x)-1},fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,length=arguments.length,value;while(length--){value=+arguments[length];if(value==Infinity||value==-Infinity)return Infinity;sum+=value*value}return sqrt(sum)},imul:function(x,y){var UInt16=65535,xl=UInt16&x,yl=UInt16&y;return 0|xl*yl+((UInt16&x>>>16)*yl+xl*(UInt16&y>>>16)<<16>>>0)},log1p:function(x){return x>-1e-8&&x<1e-8?x-x*x/2:log(1+ +x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return x==0?+x:(exp(x)-exp(-x))/2},tanh:function(x){return isFinite(x)?x==0?+x:(exp(x)-exp(-x))/(exp(x)+exp(-x)):sign(x)},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(isObject(it)&&it instanceof RegExp)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=ES5Object(assertDefined(callSite.raw)),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString,endPosition){assertNotRegExp(searchString);var len=this.length,end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return String(this).slice(end-searchString.length,end)===searchString},includes:function(searchString,position){return!!~String(assertDefined(this)).indexOf(searchString,position)},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString,position){assertNotRegExp(searchString);var index=toLength(min(position,this.length));searchString+="";return String(this).slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike,mapfn,that){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start,end){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value,start,end){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(start,length),endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:ES5Object(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);switch(iter.k){case KEY:return iterResult(0,index);case VALUE:return iterResult(0,O[index])}return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});if(/./g.flags!="g")defineProperty(RegExp[PROTOTYPE],"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")})}}(isFinite,{});isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(Function()))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new this[CONSTRUCTOR](function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&&notify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=this,values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=this;return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new this(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&getPrototypeOf(x)===this[PROTOTYPE]?x:new this(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var DATA=safeSymbol("data"),UID=safeSymbol("uid"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),WEAKDATA=safeSymbol("weakData"),WEAKID=safeSymbol("weakId"),SIZE=DESC?safeSymbol("size"):"size",uid=0,wid=0;function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];framework&&hidden(proto,key,function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result})}if(BUGGY_ITERATORS||!(isNative(C)&&(isWeak||has(proto,FOR_EACH)&&has(proto,"entries")))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,WEAKID,wid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,DATA,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(!has(it,UID)){if(create)hidden(it,UID,++uid);else return""}return"O"+it[UID]}function def(that,key,value){var index=fastKey(key,true),data=that[DATA],last=that[LAST],entry;if(index in data)data[index].v=value;else{entry=data[index]={k:key,v:value,p:last};if(!that[FIRST])that[FIRST]=entry;if(last)last.n=entry;that[LAST]=entry;that[SIZE]++}return that}function del(that,index){var data=that[DATA],entry=data[index],next=entry.n,prev=entry.p;delete data[index];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}var collectionMethods={clear:function(){for(var index in this[DATA])del(this,index)},"delete":function(key){var index=fastKey(key),contains=index in this[DATA];if(contains)del(this,index);return contains},forEach:function(callbackfn,that){var f=ctx(callbackfn,that,3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return fastKey(key)in this[DATA]}};Map=getCollection(Map,MAP,{get:function(key){var entry=this[DATA][fastKey(key)];return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function getWeakData(it){has(it,WEAKDATA)||hidden(it,WEAKDATA,{});return it[WEAKDATA]}function weakCollectionHas(key){return isObject(key)&&has(key,WEAKDATA)&&has(key[WEAKDATA],this[WEAKID])}var weakCollectionMethods={"delete":function(key){return weakCollectionHas.call(this,key)&&delete key[WEAKDATA][this[WEAKID]]},has:weakCollectionHas};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)&&has(key,WEAKDATA))return key[WEAKDATA][this[WEAKID]]},set:function(key,value){getWeakData(assertObject(key))[this[WEAKID]]=value;return this}},weakCollectionMethods,true,true);WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){getWeakData(assertObject(value))[this[WEAKID]]=true;return this}},weakCollectionMethods,false,true);function defineCollectionIterators(C,NAME,DEFAULT){defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],O=iter.o,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!O||!(iter.l=entry=entry?entry.n:O[FIRST]))return iter.o=undefined,iterResult(1);switch(iter.k){case KEY:return iterResult(0,entry.k);case VALUE:return iterResult(0,entry.v)}return iterResult(0,[entry.k,entry.v])},DEFAULT)}defineCollectionIterators(Map,MAP,KEY+VALUE);defineCollectionIterators(Set,SET,VALUE)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=ES5Object(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(){function setArrayStatics(keys,length){$define(STATIC,ARRAY,turn.call(array(keys),function(memo,key){if(key in ArrayProto)memo[key]=ctx(call,ArrayProto[key],length)},{}))}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn")}();!function(console,apply,enabled){try{delete global.console}catch(e){}$define(GLOBAL+FORCED,{console:turn.call(array("assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,"+"groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,profileEnd,"+"table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn"),function(memo,key){var fn=console[key];memo[key]=function(){if(enabled&&fn)return apply.call(fn,console,arguments)}},{enable:function(){enabled=true},disable:function(){enabled=false}})})}(global.console||{},FunctionProto.apply,true)}(Function("return this"),true)},{}],3:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value; context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}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;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{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},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"){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")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){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"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"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,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{}]},{},[1]);
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Register from './Register'; const title = 'New User Registration'; function action() { return { chunks: ['register'], title, component: ( <Layout> <Register title={title} /> </Layout> ), }; } export default action;
// 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 () { }, 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' && p.then !== Rx.Observable.prototype.then; }, 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 === '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 (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(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * 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 BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; 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) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (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; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(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; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; 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 () { /** * @constructor * @private */ 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; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * 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). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { 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). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * 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); }; /** * 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 }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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'); }); }; /** 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) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; 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; }()); /** * 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), t; 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 === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); 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); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * 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. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @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. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (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)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(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()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * 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 CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); 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)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); 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; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * 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 new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * 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); } }); }); }; /** * 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) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { 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) { 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(); } }); }); }; /** * Converts an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), 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 generator sequence. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); 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) { 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) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(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) { 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.throwException(new Error('Error')); * var res = Rx.Observable.throwException(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) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; 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 = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (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; if (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; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * 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); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * 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.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} 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 = 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 (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, 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. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @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, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @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. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion 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, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).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.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. * @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) { 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); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * 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 selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).mergeAll(); } /** * 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. * @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) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(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)); }); }; /* * 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 (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } 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 GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @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 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 = []; } }, /** * 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) { 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)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(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));
import React from 'react'; import TextField from '@material-ui/core/TextField'; import {Input, Card, CardContent} from '@material-ui/core'; import FormLabel from '@material-ui/core/FormLabel'; import FormGroup from '@material-ui/core/FormGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import IconButton from '@material-ui/core/IconButton'; import DeleteIcon from '@material-ui/icons/Delete'; class LectureSection extends React.Component { constructor(props) { super(props); this.handleProfessorChange = this.handleProfessorChange.bind(this); this.handleStartTimeChange = this.handleStartTimeChange.bind(this); this.handleEndTimeChange = this.handleEndTimeChange.bind(this); this.handleDayChange = this.handleDayChange.bind(this); this.handleDeleteSection = this.handleDeleteSection.bind(this); } handleProfessorChange(event) { this.props.updateLectureSectionProfessor(this.props.id, event.target.value); } handleStartTimeChange(event) { this.props.updateLectureSectionStartTime(this.props.id, event.target.value); } handleEndTimeChange(event) { this.props.updateLectureSectionEndTime(this.props.id, event.target.value); } handleDayChange(day) { this.props.updateLectureSectionDays(this.props.id, day); } handleDeleteSection() { this.props.deleteLectureSection(this.props.id); } render() { return ( <Card> <CardContent> <Input placeholder="Professor" inputProps={{'aria-label': 'description'}} value={this.props.professor} onChange={this.handleProfessorChange} /> <TextField label="Start time: " type="time" onChange={this.handleStartTimeChange} InputLabelProps={{shrink: true}} value={this.props.startTime} inputProps={{step: 300}} /> <TextField label="End time: " type="time" onChange={this.handleEndTimeChange} InputLabelProps={{shrink: true}} value={this.props.endTime} inputProps={{step: 300}} /> <IconButton aria-label="delete" onClick={this.handleDeleteSection}> <DeleteIcon /> </IconButton> <FormLabel component="legend">Days of Week</FormLabel> <FormGroup row> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(0)} />} label="Sun" checked={this.props.sun} /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(1)} />} label="Mon" checked={this.props.mon} /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(2)} />} label="Tues" checked={this.props.tue} /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(3)} />} label="Wed" checked={this.props.wed} /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(4)} />} label="Thurs" checked={this.props.thur} /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(5)} />} label="Fri" checked={this.props.fri} /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(6)} />} label="Sat" checked={this.props.sat} /> </FormGroup> </CardContent> </Card> ); } } export default LectureSection;
import RenderHook from 'react-render-hook'; import ReactElementAdapter from 'unexpected-htmllike-jsx-adapter'; import RawAdapter from 'unexpected-htmllike-raw-adapter'; import React from 'react'; import TestUtils from 'react-dom/test-utils'; import AssertionGenerator from './AssertionGenerator'; import { triggerEvent } from './shallowAssertions'; function getOptions(expect) { return { ActualAdapter: ReactElementAdapter, QueryAdapter: ReactElementAdapter, ExpectedAdapter: RawAdapter, actualTypeName: 'ReactShallowRenderer', queryTypeName: 'ReactElement', expectedTypeName: 'ReactRawObjectElement', getRenderOutput: renderer => renderer.getRenderOutput(), actualRenderOutputType: 'ReactElement', getDiffInputFromRenderOutput: renderOutput => renderOutput, rewrapResult: (renderer, target) => target, triggerEvent: triggerEvent.bind(expect) }; } function installInto(expect) { const assertionGenerator = new AssertionGenerator(getOptions(expect)); assertionGenerator.installInto(expect); return assertionGenerator; } function installAsAlternative(expect, mainAssertionGenerator) { const generatorOptions = getOptions(expect); const assertionGenerator = new AssertionGenerator({ mainAssertionGenerator, ...generatorOptions }); assertionGenerator.installAlternativeExpected(expect); } export { installInto, installAsAlternative};
!function(t,r){"object"==typeof exports&&"object"==typeof module?module.exports=r(require("react"),require("highcharts/highmaps")):"function"==typeof define&&define.amd?define(["react","highcharts/highmaps"],r):"object"==typeof exports?exports.ReactHighmaps=r(require("react"),require("highcharts/highmaps")):t.ReactHighmaps=r(t.React,t.Highcharts)}(this,function(t,r){return function(t){function r(o){if(e[o])return e[o].exports;var n=e[o]={exports:{},id:o,loaded:!1};return t[o].call(n.exports,n,n.exports,r),n.loaded=!0,n.exports}var e={};return r.m=t,r.c=e,r.p="",r(0)}([function(t,r,e){t.exports=e(5)},function(r,e){r.exports=t},function(t,r,e){(function(r){"use strict";var o=Object.assign||function(t){for(var r=1;r<arguments.length;r++){var e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},n=e(1);t.exports=function(t,e){var i="Highcharts"+t,c=n.createClass({displayName:i,propTypes:{config:n.PropTypes.object.isRequired,isPureConfig:n.PropTypes.bool,neverReflow:n.PropTypes.bool,callback:n.PropTypes.func},defaultProps:{callback:function(){}},renderChart:function(n){var c=this;if(!n)throw new Error("Config must be specified for the "+i+" component");var s=n.chart;this.chart=new e[t](o({},n,{chart:o({},s,{renderTo:this.refs.chart})}),this.props.callback),r.requestAnimationFrame&&requestAnimationFrame(function(){c.chart&&c.chart.options&&c.chart.reflow()})},shouldComponentUpdate:function(t){return t.neverReflow||t.isPureConfig&&this.props.config===t.config?!0:(this.renderChart(t.config),!1)},getChart:function(){if(!this.chart)throw new Error("getChart() should not be called before the component is mounted");return this.chart},componentDidMount:function(){this.renderChart(this.props.config)},componentWillUnmount:function(){this.chart.destroy()},render:function(){var t=this.props;return t=o({},t,{ref:"chart"}),n.createElement("div",t)}});return c.Highcharts=e,c}}).call(r,function(){return this}())},,,function(t,r,e){"use strict";t.exports=e(2)("Map",e(8))},,,function(t,e){t.exports=r}])});
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Dexie = factory()); }(this, (function () { 'use strict'; /* * Dexie.js - a minimalistic wrapper for IndexedDB * =============================================== * * By David Fahlander, david.fahlander@gmail.com * * Version 1.5.0, Thu Oct 13 2016 * www.dexie.com * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ */ var keys = Object.keys; var isArray = Array.isArray; var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global; function extend(obj, extension) { if (typeof extension !== 'object') return obj; keys(extension).forEach(function (key) { obj[key] = extension[key]; }); return obj; } var getProto = Object.getPrototypeOf; var _hasOwn = {}.hasOwnProperty; function hasOwn(obj, prop) { return _hasOwn.call(obj, prop); } function props(proto, extension) { if (typeof extension === 'function') extension = extension(getProto(proto)); keys(extension).forEach(function (key) { setProp(proto, key, extension[key]); }); } function setProp(obj, prop, functionOrGetSet, options) { Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options)); } function derive(Child) { return { from: function (Parent) { Child.prototype = Object.create(Parent.prototype); setProp(Child.prototype, "constructor", Child); return { extend: props.bind(null, Child.prototype) }; } }; } var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; function getPropertyDescriptor(obj, prop) { var pd = getOwnPropertyDescriptor(obj, prop), proto; return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); } var _slice = [].slice; function slice(args, start, end) { return _slice.call(args, start, end); } function override(origFunc, overridedFactory) { return overridedFactory(origFunc); } function doFakeAutoComplete(fn) { var to = setTimeout(fn, 1000); clearTimeout(to); } function assert(b) { if (!b) throw new Error("Assertion Failed"); } function asap(fn) { if (_global.setImmediate) setImmediate(fn);else setTimeout(fn, 0); } /** Generate an object (hash map) based on given array. * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to * instert on the resulting object for each item in the array. If this function returns a falsy value, the * current item wont affect the resulting object. */ function arrayToObject(array, extractor) { return array.reduce(function (result, item, i) { var nameAndValue = extractor(item, i); if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1]; return result; }, {}); } function trycatcher(fn, reject) { return function () { try { fn.apply(this, arguments); } catch (e) { reject(e); } }; } function tryCatch(fn, onerror, args) { try { fn.apply(null, args); } catch (ex) { onerror && onerror(ex); } } function getByKeyPath(obj, keyPath) { // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose. if (!keyPath) return obj; if (typeof keyPath !== 'string') { var rv = []; for (var i = 0, l = keyPath.length; i < l; ++i) { var val = getByKeyPath(obj, keyPath[i]); rv.push(val); } return rv; } var period = keyPath.indexOf('.'); if (period !== -1) { var innerObj = obj[keyPath.substr(0, period)]; return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); } return undefined; } function setByKeyPath(obj, keyPath, value) { if (!obj || keyPath === undefined) return; if ('isFrozen' in Object && Object.isFrozen(obj)) return; if (typeof keyPath !== 'string' && 'length' in keyPath) { assert(typeof value !== 'string' && 'length' in value); for (var i = 0, l = keyPath.length; i < l; ++i) { setByKeyPath(obj, keyPath[i], value[i]); } } else { var period = keyPath.indexOf('.'); if (period !== -1) { var currentKeyPath = keyPath.substr(0, period); var remainingKeyPath = keyPath.substr(period + 1); if (remainingKeyPath === "") { if (value === undefined) delete obj[currentKeyPath];else obj[currentKeyPath] = value; } else { var innerObj = obj[currentKeyPath]; if (!innerObj) innerObj = obj[currentKeyPath] = {}; setByKeyPath(innerObj, remainingKeyPath, value); } } else { if (value === undefined) delete obj[keyPath];else obj[keyPath] = value; } } } function delByKeyPath(obj, keyPath) { if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);else if ('length' in keyPath) [].map.call(keyPath, function (kp) { setByKeyPath(obj, kp, undefined); }); } function shallowClone(obj) { var rv = {}; for (var m in obj) { if (hasOwn(obj, m)) rv[m] = obj[m]; } return rv; } function deepClone(any) { if (!any || typeof any !== 'object') return any; var rv; if (isArray(any)) { rv = []; for (var i = 0, l = any.length; i < l; ++i) { rv.push(deepClone(any[i])); } } else if (any instanceof Date) { rv = new Date(); rv.setTime(any.getTime()); } else { rv = any.constructor ? Object.create(any.constructor.prototype) : {}; for (var prop in any) { if (hasOwn(any, prop)) { rv[prop] = deepClone(any[prop]); } } } return rv; } function getObjectDiff(a, b, rv, prfx) { // Compares objects a and b and produces a diff object. rv = rv || {}; prfx = prfx || ''; keys(a).forEach(function (prop) { if (!hasOwn(b, prop)) rv[prfx + prop] = undefined; // Property removed else { var ap = a[prop], bp = b[prop]; if (typeof ap === 'object' && typeof bp === 'object' && ap && bp && ap.constructor === bp.constructor) // Same type of object but its properties may have changed getObjectDiff(ap, bp, rv, prfx + prop + ".");else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed } }); keys(b).forEach(function (prop) { if (!hasOwn(a, prop)) { rv[prfx + prop] = b[prop]; // Property added } }); return rv; } // If first argument is iterable or array-like, return it as an array var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; var getIteratorOf = iteratorSymbol ? function (x) { var i; return x != null && (i = x[iteratorSymbol]) && i.apply(x); } : function () { return null; }; var NO_CHAR_ARRAY = {}; // Takes one or several arguments and returns an array based on the following criteras: // * If several arguments provided, return arguments converted to an array in a way that // still allows javascript engine to optimize the code. // * If single argument is an array, return a clone of it. // * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special // case to the two bullets below. // * If single argument is an iterable, convert it to an array and return the resulting array. // * If single argument is array-like (has length of type number), convert it to an array. function getArrayOf(arrayLike) { var i, a, x, it; if (arguments.length === 1) { if (isArray(arrayLike)) return arrayLike.slice(); if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike]; if (it = getIteratorOf(arrayLike)) { a = []; while (x = it.next(), !x.done) { a.push(x.value); }return a; } if (arrayLike == null) return [arrayLike]; i = arrayLike.length; if (typeof i === 'number') { a = new Array(i); while (i--) { a[i] = arrayLike[i]; }return a; } return [arrayLike]; } i = arguments.length; a = new Array(i); while (i--) { a[i] = arguments[i]; }return a; } var concat = [].concat; function flatten(a) { return concat.apply([], a); } function nop() {} function mirror(val) { return val; } function pureFunctionChain(f1, f2) { // Enables chained events that takes ONE argument and returns it to the next function in chain. // This pattern is used in the hook("reading") event. if (f1 == null || f1 === mirror) return f2; return function (val) { return f2(f1(val)); }; } function callBoth(on1, on2) { return function () { on1.apply(this, arguments); on2.apply(this, arguments); }; } function hookCreatingChain(f1, f2) { // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance. // This pattern is used in the hook("creating") event. if (f1 === nop) return f2; return function () { var res = f1.apply(this, arguments); if (res !== undefined) arguments[0] = res; var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = null; this.onerror = null; var res2 = f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; return res2 !== undefined ? res2 : res; }; } function hookDeletingChain(f1, f2) { if (f1 === nop) return f2; return function () { f1.apply(this, arguments); var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = this.onerror = null; f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; }; } function hookUpdatingChain(f1, f2) { if (f1 === nop) return f2; return function (modifications) { var res = f1.apply(this, arguments); extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain. var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = null; this.onerror = null; var res2 = f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; return res === undefined ? res2 === undefined ? undefined : res2 : extend(res, res2); }; } function reverseStoppableEventChain(f1, f2) { if (f1 === nop) return f2; return function () { if (f2.apply(this, arguments) === false) return false; return f1.apply(this, arguments); }; } function promisableChain(f1, f2) { if (f1 === nop) return f2; return function () { var res = f1.apply(this, arguments); if (res && typeof res.then === 'function') { var thiz = this, i = arguments.length, args = new Array(i); while (i--) { args[i] = arguments[i]; }return res.then(function () { return f2.apply(thiz, args); }); } return f2.apply(this, arguments); }; } // By default, debug will be true only if platform is a web platform and its page is served from localhost. // When debug = true, error's stacks will contain asyncronic long stacks. var debug = typeof location !== 'undefined' && // By default, use debug mode if served from localhost. /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); function setDebug(value, filter) { debug = value; libraryFilter = filter; } var libraryFilter = function () { return true; }; var NEEDS_THROW_FOR_STACK = !new Error("").stack; function getErrorWithStack() { "use strict"; if (NEEDS_THROW_FOR_STACK) try { // Doing something naughty in strict mode here to trigger a specific error // that can be explicitely ignored in debugger's exception settings. // If we'd just throw new Error() here, IE's debugger's exception settings // will just consider it as "exception thrown by javascript code" which is // something you wouldn't want it to ignore. getErrorWithStack.arguments; throw new Error(); // Fallback if above line don't throw. } catch (e) { return e; } return new Error(); } function prettyStack(exception, numIgnoredFrames) { var stack = exception.stack; if (!stack) return ""; numIgnoredFrames = numIgnoredFrames || 0; if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length; return stack.split('\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) { return "\n" + frame; }).join(''); } function deprecated(what, fn) { return function () { console.warn(what + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + prettyStack(getErrorWithStack(), 1)); return fn.apply(this, arguments); }; } var dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise']; var idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone']; var errorList = dexieErrorNames.concat(idbDomErrorNames); var defaultTexts = { VersionChanged: "Database version changed by other database connection", DatabaseClosed: "Database has been closed", Abort: "Transaction aborted", TransactionInactive: "Transaction has already completed or failed" }; // // DexieError - base class of all out exceptions. // function DexieError(name, msg) { // Reason we don't use ES6 classes is because: // 1. It bloats transpiled code and increases size of minified code. // 2. It doesn't give us much in this case. // 3. It would require sub classes to call super(), which // is not needed when deriving from Error. this._e = getErrorWithStack(); this.name = name; this.message = msg; } derive(DexieError).from(Error).extend({ stack: { get: function () { return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); } }, toString: function () { return this.name + ": " + this.message; } }); function getMultiErrorMessage(msg, failures) { return msg + ". Errors: " + failures.map(function (f) { return f.toString(); }).filter(function (v, i, s) { return s.indexOf(v) === i; }) // Only unique error strings .join('\n'); } // // ModifyError - thrown in WriteableCollection.modify() // Specific constructor because it contains members failures and failedKeys. // function ModifyError(msg, failures, successCount, failedKeys) { this._e = getErrorWithStack(); this.failures = failures; this.failedKeys = failedKeys; this.successCount = successCount; } derive(ModifyError).from(DexieError); function BulkError(msg, failures) { this._e = getErrorWithStack(); this.name = "BulkError"; this.failures = failures; this.message = getMultiErrorMessage(msg, failures); } derive(BulkError).from(DexieError); // // // Dynamically generate error names and exception classes based // on the names in errorList. // // // Map of {ErrorName -> ErrorName + "Error"} var errnames = errorList.reduce(function (obj, name) { return obj[name] = name + "Error", obj; }, {}); // Need an alias for DexieError because we're gonna create subclasses with the same name. var BaseException = DexieError; // Map of {ErrorName -> exception constructor} var exceptions = errorList.reduce(function (obj, name) { // Let the name be "DexieError" because this name may // be shown in call stack and when debugging. DexieError is // the most true name because it derives from DexieError, // and we cannot change Function.name programatically without // dynamically create a Function object, which would be considered // 'eval-evil'. var fullName = name + "Error"; function DexieError(msgOrInner, inner) { this._e = getErrorWithStack(); this.name = fullName; if (!msgOrInner) { this.message = defaultTexts[name] || fullName; this.inner = null; } else if (typeof msgOrInner === 'string') { this.message = msgOrInner; this.inner = inner || null; } else if (typeof msgOrInner === 'object') { this.message = msgOrInner.name + ' ' + msgOrInner.message; this.inner = msgOrInner; } } derive(DexieError).from(BaseException); obj[name] = DexieError; return obj; }, {}); // Use ECMASCRIPT standard exceptions where applicable: exceptions.Syntax = SyntaxError; exceptions.Type = TypeError; exceptions.Range = RangeError; var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { obj[name + "Error"] = exceptions[name]; return obj; }, {}); function mapError(domError, message) { if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError; var rv = new exceptionMap[domError.name](message || domError.message, domError); if ("stack" in domError) { // Derive stack from inner exception if it has a stack setProp(rv, "stack", { get: function () { return this.inner.stack; } }); } return rv; } var fullNameExceptions = errorList.reduce(function (obj, name) { if (["Syntax", "Type", "Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name]; return obj; }, {}); fullNameExceptions.ModifyError = ModifyError; fullNameExceptions.DexieError = DexieError; fullNameExceptions.BulkError = BulkError; function Events(ctx) { var evs = {}; var rv = function (eventName, subscriber) { if (subscriber) { // Subscribe. If additional arguments than just the subscriber was provided, forward them as well. var i = arguments.length, args = new Array(i - 1); while (--i) { args[i - 1] = arguments[i]; }evs[eventName].subscribe.apply(null, args); return ctx; } else if (typeof eventName === 'string') { // Return interface allowing to fire or unsubscribe from event return evs[eventName]; } }; rv.addEventType = add; for (var i = 1, l = arguments.length; i < l; ++i) { add(arguments[i]); } return rv; function add(eventName, chainFunction, defaultFunction) { if (typeof eventName === 'object') return addConfiguredEvents(eventName); if (!chainFunction) chainFunction = reverseStoppableEventChain; if (!defaultFunction) defaultFunction = nop; var context = { subscribers: [], fire: defaultFunction, subscribe: function (cb) { if (context.subscribers.indexOf(cb) === -1) { context.subscribers.push(cb); context.fire = chainFunction(context.fire, cb); } }, unsubscribe: function (cb) { context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); context.fire = context.subscribers.reduce(chainFunction, defaultFunction); } }; evs[eventName] = rv[eventName] = context; return context; } function addConfiguredEvents(cfg) { // events(this, {reading: [functionChain, nop]}); keys(cfg).forEach(function (eventName) { var args = cfg[eventName]; if (isArray(args)) { add(eventName, cfg[eventName][0], cfg[eventName][1]); } else if (args === 'asap') { // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten. var context = add(eventName, mirror, function fire() { // Optimazation-safe cloning of arguments into args. var i = arguments.length, args = new Array(i); while (i--) { args[i] = arguments[i]; } // All each subscriber: context.subscribers.forEach(function (fn) { asap(function fireEvent() { fn.apply(null, args); }); }); }); } else throw new exceptions.InvalidArgument("Invalid event config"); }); } } // // Promise Class for Dexie library // // I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by // https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. // // Modifications needed to be done to support indexedDB because it wont accept setTimeout() // (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) . // This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45 // // This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since // the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise. // // In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another // tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use // another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick // engine that is used instead of setImmediate() or setTimeout(). // Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. // Also with inspiration from bluebird, asyncronic stacks in debug mode. // // Specific non-standard features of this Promise class: // * Async static context support (Promise.PSD) // * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame // and below + all promises that those promises creates or awaits. // * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). // // David Fahlander, https://github.com/dfahlander // // Just a pointer that only this module knows about. // Used in Promise constructor to emulate a private constructor. var INTERNAL = {}; // Async stacks (long stacks) must not grow infinitely. var LONG_STACKS_CLIP_LIMIT = 100; var MAX_LONG_STACKS = 20; var stack_being_generated = false; /* The default "nextTick" function used only for the very first promise in a promise chain. As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks emulated in this module. For indexedDB compatibility, this means that every method needs to execute at least one promise before doing an indexedDB operation. Dexie will always call db.ready().then() for every operation to make sure the indexedDB event is started in an emulated micro tick. */ var schedulePhysicalTick = _global.setImmediate ? // setImmediate supported. Those modern platforms also supports Function.bind(). setImmediate.bind(null, physicalTick) : _global.MutationObserver ? // MutationObserver supported function () { var hiddenDiv = document.createElement("div"); new MutationObserver(function () { physicalTick(); hiddenDiv = null; }).observe(hiddenDiv, { attributes: true }); hiddenDiv.setAttribute('i', '1'); } : // No support for setImmediate or MutationObserver. No worry, setTimeout is only called // once time. Every tick that follows will be our emulated micro tick. // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug function () { setTimeout(physicalTick, 0); }; // Confifurable through Promise.scheduler. // Don't export because it would be unsafe to let unknown // code call it unless they do try..catch within their callback. // This function can be retrieved through getter of Promise.scheduler though, // but users must not do Promise.scheduler (myFuncThatThrows exception)! var asap$1 = function (callback, args) { microtickQueue.push([callback, args]); if (needsNewPhysicalTick) { schedulePhysicalTick(); needsNewPhysicalTick = false; } }; var isOutsideMicroTick = true; var needsNewPhysicalTick = true; var unhandledErrors = []; var rejectingErrors = []; var currentFulfiller = null; var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions var globalPSD = { global: true, ref: 0, unhandleds: [], onunhandled: globalError, //env: null, // Will be set whenever leaving a scope using wrappers.snapshot() finalize: function () { this.unhandleds.forEach(function (uh) { try { globalError(uh[0], uh[1]); } catch (e) {} }); } }; var PSD = globalPSD; var microtickQueue = []; // Callbacks to call in this or next physical tick. var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. // Wrappers are not being used yet. Their framework is functioning and can be used // to replace environment during a PSD scope (a.k.a. 'zone'). /* **KEEP** export var wrappers = (() => { var wrappers = []; return { snapshot: () => { var i = wrappers.length, result = new Array(i); while (i--) result[i] = wrappers[i].snapshot(); return result; }, restore: values => { var i = wrappers.length; while (i--) wrappers[i].restore(values[i]); }, wrap: () => wrappers.map(w => w.wrap()), add: wrapper => { wrappers.push(wrapper); } }; })(); */ function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); this._listeners = []; this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() // execute the microtask engine implicitely within the call to resolve() or reject(). // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack // only contains library code when calling resolve() or reject(). // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from // global scope (event handler, timer etc)! this._lib = false; // Current async scope var psd = this._PSD = PSD; if (debug) { this._stackHolder = getErrorWithStack(); this._prev = null; this._numPrev = 0; // Number of previous promises (for long stacks) linkToPreviousPromise(this, currentFulfiller); } if (typeof fn !== 'function') { if (fn !== INTERNAL) throw new TypeError('Not a function'); // Private constructor (INTERNAL, state, value). // Used internally by Promise.resolve() and Promise.reject(). this._state = arguments[1]; this._value = arguments[2]; if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). return; } this._state = null; // null (=pending), false (=rejected) or true (=resolved) this._value = null; // error or result ++psd.ref; // Refcounting current scope executePromiseTask(this, fn); } props(Promise.prototype, { then: function (onFulfilled, onRejected) { var _this = this; var rv = new Promise(function (resolve, reject) { propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject)); }); debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this); return rv; }, _then: function (onFulfilled, onRejected) { // A little tinier version of then() that don't have to create a resulting promise. propagateToListener(this, new Listener(null, null, onFulfilled, onRejected)); }, catch: function (onRejected) { if (arguments.length === 1) return this.then(null, onRejected); // First argument is the Error type to catch var type = arguments[0], handler = arguments[1]; return typeof type === 'function' ? this.then(null, function (err) { return ( // Catching errors by its constructor type (similar to java / c++ / c#) // Sample: promise.catch(TypeError, function (e) { ... }); err instanceof type ? handler(err) : PromiseReject(err) ); }) : this.then(null, function (err) { return ( // Catching errors by the error.name property. Makes sense for indexedDB where error type // is always DOMError but where e.name tells the actual error type. // Sample: promise.catch('ConstraintError', function (e) { ... }); err && err.name === type ? handler(err) : PromiseReject(err) ); }); }, finally: function (onFinally) { return this.then(function (value) { onFinally(); return value; }, function (err) { onFinally(); return PromiseReject(err); }); }, // Deprecate in next major. Needed only for db.on.error. uncaught: function (uncaughtHandler) { var _this2 = this; // Be backward compatible and use "onuncatched" as the event name on this. // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops. this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler); // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not // a previous promise. Reason: the prevous promise may lack onuncatched handler. if (this._state === false && unhandledErrors.indexOf(this) === -1) { // Replace unhandled error's destinaion promise with this one! unhandledErrors.some(function (p, i, l) { return p._value === _this2._value && (l[i] = _this2); }); // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could // take away this piece of code as well as the onuncatched and uncaught() method. } return this; }, stack: { get: function () { if (this._stack) return this._stack; try { stack_being_generated = true; var stacks = getStack(this, [], MAX_LONG_STACKS); var stack = stacks.join("\nFrom previous: "); if (this._state !== null) this._stack = stack; // Stack may be updated on reject. return stack; } finally { stack_being_generated = false; } } } }); function Listener(onFulfilled, onRejected, resolve, reject) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.resolve = resolve; this.reject = reject; this.psd = PSD; } // Promise Static Properties props(Promise, { all: function () { var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like. return new Promise(function (resolve, reject) { if (values.length === 0) resolve([]); var remaining = values.length; values.forEach(function (a, i) { return Promise.resolve(a).then(function (x) { values[i] = x; if (! --remaining) resolve(values); }, reject); }); }); }, resolve: function (value) { if (value instanceof Promise) return value; if (value && typeof value.then === 'function') return new Promise(function (resolve, reject) { value.then(resolve, reject); }); return new Promise(INTERNAL, true, value); }, reject: PromiseReject, race: function () { var values = getArrayOf.apply(null, arguments); return new Promise(function (resolve, reject) { values.map(function (value) { return Promise.resolve(value).then(resolve, reject); }); }); }, PSD: { get: function () { return PSD; }, set: function (value) { return PSD = value; } }, newPSD: newScope, usePSD: usePSD, scheduler: { get: function () { return asap$1; }, set: function (value) { asap$1 = value; } }, rejectionMapper: { get: function () { return rejectionMapper; }, set: function (value) { rejectionMapper = value; } // Map reject failures }, follow: function (fn) { return new Promise(function (resolve, reject) { return newScope(function (resolve, reject) { var psd = PSD; psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. psd.finalize = callBoth(function () { var _this3 = this; // Unhandled standard or 3rd part promises are put in PSD.unhandleds and // examined upon scope completion while unhandled rejections in this Promise // will trigger directly through psd.onunhandled run_at_end_of_this_or_next_physical_tick(function () { _this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]); }); }, psd.finalize); fn(); }, resolve, reject); }); }, on: Events(null, { "error": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler }) }); var PromiseOnError = Promise.on.error; PromiseOnError.subscribe = deprecated("Promise.on('error')", PromiseOnError.subscribe); PromiseOnError.unsubscribe = deprecated("Promise.on('error').unsubscribe", PromiseOnError.unsubscribe); /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function executePromiseTask(promise, fn) { // Promise Resolution Procedure: // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure try { fn(function (value) { if (promise._state !== null) return; if (value === promise) throw new TypeError('A promise cannot be resolved with itself.'); var shouldExecuteTick = promise._lib && beginMicroTickScope(); if (value && typeof value.then === 'function') { executePromiseTask(promise, function (resolve, reject) { value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject); }); } else { promise._state = true; promise._value = value; propagateAllListeners(promise); } if (shouldExecuteTick) endMicroTickScope(); }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below } catch (ex) { handleRejection(promise, ex); } } function handleRejection(promise, reason) { rejectingErrors.push(reason); if (promise._state !== null) return; var shouldExecuteTick = promise._lib && beginMicroTickScope(); reason = rejectionMapper(reason); promise._state = false; promise._value = reason; debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () { var origProp = getPropertyDescriptor(reason, "stack"); reason._promise = promise; setProp(reason, "stack", { get: function () { return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack; } }); }); // Add the failure to a list of possibly uncaught errors addPossiblyUnhandledError(promise); propagateAllListeners(promise); if (shouldExecuteTick) endMicroTickScope(); } function propagateAllListeners(promise) { //debug && linkToPreviousPromise(promise); var listeners = promise._listeners; promise._listeners = []; for (var i = 0, len = listeners.length; i < len; ++i) { propagateToListener(promise, listeners[i]); } var psd = promise._PSD; --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); if (numScheduledCalls === 0) { // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, // and that no deferreds where listening to this rejection or success. // Since there is a risk that our stack can contain application code that may // do stuff after this code is finished that may generate new calls, we cannot // call finalizers here. ++numScheduledCalls; asap$1(function () { if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors }, []); } } function propagateToListener(promise, listener) { if (promise._state === null) { promise._listeners.push(listener); return; } var cb = promise._state ? listener.onFulfilled : listener.onRejected; if (cb === null) { // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() return (promise._state ? listener.resolve : listener.reject)(promise._value); } var psd = listener.psd; ++psd.ref; ++numScheduledCalls; asap$1(callListener, [cb, promise, listener]); } function callListener(cb, promise, listener) { var outerScope = PSD; var psd = listener.psd; try { if (psd !== outerScope) { // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment. PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } // Set static variable currentFulfiller to the promise that is being fullfilled, // so that we connect the chain of promises (for long stacks support) currentFulfiller = promise; // Call callback and resolve our listener with it's return value. var value = promise._value, ret; if (promise._state) { ret = cb(value); } else { if (rejectingErrors.length) rejectingErrors = []; ret = cb(value); if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. } listener.resolve(ret); } catch (e) { // Exception thrown in callback. Reject our listener. listener.reject(e); } finally { // Restore PSD, env and currentFulfiller. if (psd !== outerScope) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment } currentFulfiller = null; if (--numScheduledCalls === 0) finalizePhysicalTick(); --psd.ref || psd.finalize(); } } function getStack(promise, stacks, limit) { if (stacks.length === limit) return stacks; var stack = ""; if (promise._state === false) { var failure = promise._value, errorName, message; if (failure != null) { errorName = failure.name || "Error"; message = failure.message || failure; stack = prettyStack(failure, 0); } else { errorName = failure; // If error is undefined or null, show that. message = ""; } stacks.push(errorName + (message ? ": " + message : "") + stack); } if (debug) { stack = prettyStack(promise._stackHolder, 2); if (stack && stacks.indexOf(stack) === -1) stacks.push(stack); if (promise._prev) getStack(promise._prev, stacks, limit); } return stacks; } function linkToPreviousPromise(promise, prev) { // Support long stacks by linking to previous completed promise. var numPrev = prev ? prev._numPrev + 1 : 0; if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming "tail". promise._prev = prev; promise._numPrev = numPrev; } } /* The callback to schedule with setImmediate() or setTimeout(). It runs a virtual microtick and executes any callback registered in microtickQueue. */ function physicalTick() { beginMicroTickScope() && endMicroTickScope(); } function beginMicroTickScope() { var wasRootExec = isOutsideMicroTick; isOutsideMicroTick = false; needsNewPhysicalTick = false; return wasRootExec; } /* Executes micro-ticks without doing try..catch. This can be possible because we only use this internally and the registered functions are exception-safe (they do try..catch internally before calling any external method). If registering functions in the microtickQueue that are not exception-safe, this would destroy the framework and make it instable. So we don't export our asap method. */ function endMicroTickScope() { var callbacks, i, l; do { while (microtickQueue.length > 0) { callbacks = microtickQueue; microtickQueue = []; l = callbacks.length; for (i = 0; i < l; ++i) { var item = callbacks[i]; item[0].apply(null, item[1]); } } } while (microtickQueue.length > 0); isOutsideMicroTick = true; needsNewPhysicalTick = true; } function finalizePhysicalTick() { var unhandledErrs = unhandledErrors; unhandledErrors = []; unhandledErrs.forEach(function (p) { p._PSD.onunhandled.call(null, p._value, p); }); var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. var i = finalizers.length; while (i) { finalizers[--i](); } } function run_at_end_of_this_or_next_physical_tick(fn) { function finalizer() { fn(); tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); } tickFinalizers.push(finalizer); ++numScheduledCalls; asap$1(function () { if (--numScheduledCalls === 0) finalizePhysicalTick(); }, []); } function addPossiblyUnhandledError(promise) { // Only add to unhandledErrors if not already there. The first one to add to this list // will be upon the first rejection so that the root cause (first promise in the // rejection chain) is the one listed. if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) unhandledErrors.push(promise); } function markErrorAsHandled(promise) { // Called when a reject handled is actually being called. // Search in unhandledErrors for any promise whos _value is this promise_value (list // contains only rejected promises, and only one item per error) var i = unhandledErrors.length; while (i) { if (unhandledErrors[--i]._value === promise._value) { // Found a promise that failed with this same error object pointer, // Remove that since there is a listener that actually takes care of it. unhandledErrors.splice(i, 1); return; } } } // By default, log uncaught errors to the console function defaultErrorHandler(e) { console.warn('Unhandled rejection: ' + (e.stack || e)); } function PromiseReject(reason) { return new Promise(INTERNAL, false, reason); } function wrap(fn, errorCatcher) { var psd = PSD; return function () { var wasRootExec = beginMicroTickScope(), outerScope = PSD; try { if (outerScope !== psd) { // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } return fn.apply(this, arguments); } catch (e) { errorCatcher && errorCatcher(e); } finally { if (outerScope !== psd) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment } if (wasRootExec) endMicroTickScope(); } }; } function newScope(fn, a1, a2, a3) { var parent = PSD, psd = Object.create(parent); psd.parent = parent; psd.ref = 0; psd.global = false; // **KEEP** psd.env = wrappers.wrap(psd); // unhandleds and onunhandled should not be specifically set here. // Leave them on parent prototype. // unhandleds.push(err) will push to parent's prototype // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) ++parent.ref; psd.finalize = function () { --this.parent.ref || this.parent.finalize(); }; var rv = usePSD(psd, fn, a1, a2, a3); if (psd.ref === 0) psd.finalize(); return rv; } function usePSD(psd, fn, a1, a2, a3) { var outerScope = PSD; try { if (psd !== outerScope) { // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment. PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } return fn(a1, a2, a3); } finally { if (psd !== outerScope) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment. } } } var UNHANDLEDREJECTION = "unhandledrejection"; function globalError(err, promise) { var rv; try { rv = promise.onuncatched(err); } catch (e) {} if (rv !== false) try { var event, eventData = { promise: promise, reason: err }; if (_global.document && document.createEvent) { event = document.createEvent('Event'); event.initEvent(UNHANDLEDREJECTION, true, true); extend(event, eventData); } else if (_global.CustomEvent) { event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData }); extend(event, eventData); } if (event && _global.dispatchEvent) { dispatchEvent(event); if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. try { _global.onunhandledrejection(event); } catch (_) {} } if (!event.defaultPrevented) { // Backward compatibility: fire to events registered at Promise.on.error Promise.on.error.fire(err, promise); } } catch (e) {} } /* **KEEP** export function wrapPromise(PromiseClass) { var proto = PromiseClass.prototype; var origThen = proto.then; wrappers.add({ snapshot: () => proto.then, restore: value => {proto.then = value;}, wrap: () => patchedThen }); function patchedThen (onFulfilled, onRejected) { var promise = this; var onFulfilledProxy = wrap(function(value){ var rv = value; if (onFulfilled) { rv = onFulfilled(rv); if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. } --PSD.ref || PSD.finalize(); return rv; }); var onRejectedProxy = wrap(function(err){ promise._$err = err; var unhandleds = PSD.unhandleds; var idx = unhandleds.length, rv; while (idx--) if (unhandleds[idx]._$err === err) break; if (onRejected) { if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled. rv = onRejected(err); if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. } else { if (idx === -1) unhandleds.push(promise); rv = PromiseClass.reject(err); rv._$nointercept = true; // Prohibit eternal loop. } --PSD.ref || PSD.finalize(); return rv; }); if (this._$nointercept) return origThen.apply(this, arguments); ++PSD.ref; return origThen.call(this, onFulfilledProxy, onRejectedProxy); } } // Global Promise wrapper if (_global.Promise) wrapPromise(_global.Promise); */ doFakeAutoComplete(function () { // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie. asap$1 = function (fn, args) { setTimeout(function () { fn.apply(null, args); }, 0); }; }); function rejection(err, uncaughtHandler) { // Get the call stack and return a rejected promise. var rv = Promise.reject(err); return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv; } /* * Dexie.js - a minimalistic wrapper for IndexedDB * =============================================== * * By David Fahlander, david.fahlander@gmail.com * * Version 1.5.0, Thu Oct 13 2016 * * http://dexie.org * * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ */ var DEXIE_VERSION = '1.5.0'; var maxString = String.fromCharCode(65535); var maxKey = function () { try { IDBKeyRange.only([[]]);return [[]]; } catch (e) { return maxString; } }(); var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>."; var STRING_EXPECTED = "String expected."; var connections = []; var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); var hasIEDeleteObjectStoreBug = isIEOrEdge; var hangsOnDeleteLargeKeyRange = isIEOrEdge; var dexieStackFrameFilter = function (frame) { return !/(dexie\.js|dexie\.min\.js)/.test(frame); }; setDebug(debug, dexieStackFrameFilter); function Dexie(dbName, options) { /// <param name="options" type="Object" optional="true">Specify only if you wich to control which addons that should run on this instance</param> var deps = Dexie.dependencies; var opts = extend({ // Default Options addons: Dexie.addons, // Pick statically registered addons by default autoOpen: true, // Don't require db.open() explicitely. indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env. IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env. }, options); var addons = opts.addons, autoOpen = opts.autoOpen, indexedDB = opts.indexedDB, IDBKeyRange = opts.IDBKeyRange; var globalSchema = this._dbSchema = {}; var versions = []; var dbStoreNames = []; var allTables = {}; ///<var type="IDBDatabase" /> var idbdb = null; // Instance of IDBDatabase var dbOpenError = null; var isBeingOpened = false; var openComplete = false; var READONLY = "readonly", READWRITE = "readwrite"; var db = this; var dbReadyResolve, dbReadyPromise = new Promise(function (resolve) { dbReadyResolve = resolve; }), cancelOpen, openCanceller = new Promise(function (_, reject) { cancelOpen = reject; }); var autoSchema = true; var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB), hasGetAll; function init() { // Default subscribers to "versionchange" and "blocked". // Can be overridden by custom handlers. If custom handlers return false, these default // behaviours will be prevented. db.on("versionchange", function (ev) { // Default behavior for versionchange event is to close database connection. // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); // Let's not block the other window from making it's delete() or open() call. // NOTE! This event is never fired in IE,Edge or Safari. if (ev.newVersion > 0) console.warn('Another connection wants to upgrade database \'' + db.name + '\'. Closing db now to resume the upgrade.');else console.warn('Another connection wants to delete database \'' + db.name + '\'. Closing db now to resume the delete request.'); db.close(); // In many web applications, it would be recommended to force window.reload() // when this event occurs. To do that, subscribe to the versionchange event // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) // The reason for this is that your current web app obviously has old schema code that needs // to be updated. Another window got a newer version of the app and needs to upgrade DB but // your window is blocking it unless we close it here. }); db.on("blocked", function (ev) { if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn('Dexie.delete(\'' + db.name + '\') was blocked');else console.warn('Upgrade \'' + db.name + '\' blocked by other connection holding version ' + ev.oldVersion / 10); }); } // // // // ------------------------- Versioning Framework--------------------------- // // // this.version = function (versionNumber) { /// <param name="versionNumber" type="Number"></param> /// <returns type="Version"></returns> if (idbdb || isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open"); this.verno = Math.max(this.verno, versionNumber); var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; if (versionInstance) return versionInstance; versionInstance = new Version(versionNumber); versions.push(versionInstance); versions.sort(lowerVersionFirst); return versionInstance; }; function Version(versionNumber) { this._cfg = { version: versionNumber, storesSource: null, dbschema: {}, tables: {}, contentUpgrade: null }; this.stores({}); // Derive earlier schemas by default. } extend(Version.prototype, { stores: function (stores) { /// <summary> /// Defines the schema for a particular version /// </summary> /// <param name="stores" type="Object"> /// Example: <br/> /// {users: "id++,first,last,&amp;username,*email", <br/> /// passwords: "id++,&amp;username"}<br/> /// <br/> /// Syntax: {Table: "[primaryKey][++],[&amp;][*]index1,[&amp;][*]index2,..."}<br/><br/> /// Special characters:<br/> /// "&amp;" means unique key, <br/> /// "*" means value is multiEntry, <br/> /// "++" means auto-increment and only applicable for primary key <br/> /// </param> this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax. var storesSpec = {}; versions.forEach(function (version) { // 'versions' is always sorted by lowest version first. extend(storesSpec, version._cfg.storesSource); }); var dbschema = this._cfg.dbschema = {}; this._parseStoresSpec(storesSpec, dbschema); // Update the latest schema to this version // Update API globalSchema = db._dbSchema = dbschema; removeTablesApi([allTables, db, Transaction.prototype]); setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema); dbStoreNames = keys(dbschema); return this; }, upgrade: function (upgradeFunction) { /// <param name="upgradeFunction" optional="true">Function that performs upgrading actions.</param> var self = this; fakeAutoComplete(function () { upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear. }); this._cfg.contentUpgrade = upgradeFunction; return this; }, _parseStoresSpec: function (stores, outSchema) { keys(stores).forEach(function (tableName) { if (stores[tableName] !== null) { var instanceTemplate = {}; var indexes = parseIndexSyntax(stores[tableName]); var primKey = indexes.shift(); if (primKey.multi) throw new exceptions.Schema("Primary key cannot be multi-valued"); if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath); indexes.forEach(function (idx) { if (idx.auto) throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); if (!idx.keyPath) throw new exceptions.Schema("Index must have a name and cannot be an empty string"); setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return ""; }) : ""); }); outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate); } }); } }); function runUpgraders(oldVersion, idbtrans, reject) { var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema); trans.create(idbtrans); trans._completion.catch(reject); var rejectTransaction = trans._reject.bind(trans); newScope(function () { PSD.trans = trans; if (oldVersion === 0) { // Create tables: keys(globalSchema).forEach(function (tableName) { createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); }); Promise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); } else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction); }); } function updateTablesAndIndexes(oldVersion, trans, idbtrans) { // Upgrade version to version, step-by-step from oldest to newest version. // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version) var queue = []; var oldVersionStruct = versions.filter(function (version) { return version._cfg.version === oldVersion; })[0]; if (!oldVersionStruct) throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing"); globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema; var anyContentUpgraderHasRun = false; var versToRun = versions.filter(function (v) { return v._cfg.version > oldVersion; }); versToRun.forEach(function (version) { /// <param name="version" type="Version"></param> queue.push(function () { var oldSchema = globalSchema; var newSchema = version._cfg.dbschema; adjustToExistingIndexNames(oldSchema, idbtrans); adjustToExistingIndexNames(newSchema, idbtrans); globalSchema = db._dbSchema = newSchema; var diff = getSchemaDiff(oldSchema, newSchema); // Add tables diff.add.forEach(function (tuple) { createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes); }); // Change tables diff.change.forEach(function (change) { if (change.recreate) { throw new exceptions.Upgrade("Not yet support for changing primary key"); } else { var store = idbtrans.objectStore(change.name); // Add indexes change.add.forEach(function (idx) { addIndex(store, idx); }); // Update indexes change.change.forEach(function (idx) { store.deleteIndex(idx.name); addIndex(store, idx); }); // Delete indexes change.del.forEach(function (idxName) { store.deleteIndex(idxName); }); } }); if (version._cfg.contentUpgrade) { anyContentUpgraderHasRun = true; return Promise.follow(function () { version._cfg.contentUpgrade(trans); }); } }); queue.push(function (idbtrans) { if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of. var newSchema = version._cfg.dbschema; // Delete old tables deleteRemovedTables(newSchema, idbtrans); } }); }); // Now, create a queue execution engine function runQueue() { return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve(); } return runQueue().then(function () { createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version) }); } function getSchemaDiff(oldSchema, newSchema) { var diff = { del: [], // Array of table names add: [], // Array of [tableName, newDefinition] change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs} }; for (var table in oldSchema) { if (!newSchema[table]) diff.del.push(table); } for (table in newSchema) { var oldDef = oldSchema[table], newDef = newSchema[table]; if (!oldDef) { diff.add.push([table, newDef]); } else { var change = { name: table, def: newDef, recreate: false, del: [], add: [], change: [] }; if (oldDef.primKey.src !== newDef.primKey.src) { // Primary key has changed. Remove and re-add table. change.recreate = true; diff.change.push(change); } else { // Same primary key. Just find out what differs: var oldIndexes = oldDef.idxByName; var newIndexes = newDef.idxByName; for (var idxName in oldIndexes) { if (!newIndexes[idxName]) change.del.push(idxName); } for (idxName in newIndexes) { var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; if (!oldIdx) change.add.push(newIdx);else if (oldIdx.src !== newIdx.src) change.change.push(newIdx); } if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { diff.change.push(change); } } } } return diff; } function createTable(idbtrans, tableName, primKey, indexes) { /// <param name="idbtrans" type="IDBTransaction"></param> var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); indexes.forEach(function (idx) { addIndex(store, idx); }); return store; } function createMissingTables(newSchema, idbtrans) { keys(newSchema).forEach(function (tableName) { if (!idbtrans.db.objectStoreNames.contains(tableName)) { createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); } }); } function deleteRemovedTables(newSchema, idbtrans) { for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) { var storeName = idbtrans.db.objectStoreNames[i]; if (newSchema[storeName] == null) { idbtrans.db.deleteObjectStore(storeName); } } } function addIndex(store, idx) { store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); } function dbUncaught(err) { return db.on.error.fire(err); } // // // Dexie Protected API // // this._allTables = allTables; this._tableFactory = function createTable(mode, tableSchema) { /// <param name="tableSchema" type="TableSchema"></param> if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection);else return new WriteableTable(tableSchema.name, tableSchema); }; this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new Transaction(mode, storeNames, dbschema, parentTransaction); }; /* Generate a temporary transaction when db operations are done outside a transactino scope. */ function tempTransaction(mode, storeNames, fn) { // Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it. if (!openComplete && !PSD.letThrough) { if (!isBeingOpened) { if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught); db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. } return dbReadyPromise.then(function () { return tempTransaction(mode, storeNames, fn); }); } else { var trans = db._createTransaction(mode, storeNames, globalSchema); return trans._promise(mode, function (resolve, reject) { newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise. PSD.trans = trans; fn(resolve, reject, trans); }); }).then(function (result) { // Instead of resolving value directly, wait with resolving it until transaction has completed. // Otherwise the data would not be in the DB if requesting it in the then() operation. // Specifically, to ensure that the following expression will work: // // db.friends.put({name: "Arne"}).then(function () { // db.friends.where("name").equals("Arne").count(function(count) { // assert (count === 1); // }); // }); // return trans._completion.then(function () { return result; }); }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major. trans._reject(err); return rejection(err); });*/ } } this._whenReady = function (fn) { return new Promise(fake || openComplete || PSD.letThrough ? fn : function (resolve, reject) { if (!isBeingOpened) { if (!autoOpen) { reject(new exceptions.DatabaseClosed()); return; } db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. } dbReadyPromise.then(function () { fn(resolve, reject); }); }).uncaught(dbUncaught); }; // // // // // Dexie API // // // this.verno = 0; this.open = function () { if (isBeingOpened || idbdb) return dbReadyPromise.then(function () { return dbOpenError ? rejection(dbOpenError, dbUncaught) : db; }); debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called. isBeingOpened = true; dbOpenError = null; openComplete = false; // Function pointers to call when the core opening process completes. var resolveDbReady = dbReadyResolve, // upgradeTransaction to abort on failure. upgradeTransaction = null; return Promise.race([openCanceller, new Promise(function (resolve, reject) { doFakeAutoComplete(function () { return resolve(); }); // Make sure caller has specified at least one version if (versions.length > 0) autoSchema = false; // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE: // IE fails when deleting objectStore after reading from it. // A future version of Dexie.js will stopover an intermediate version to workaround this. // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number. // If no API, throw! if (!indexedDB) throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL " + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill."); var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10)); if (!req) throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134 req.onerror = wrap(eventRejectHandler(reject)); req.onblocked = wrap(fireOnBlocked); req.onupgradeneeded = wrap(function (e) { upgradeTransaction = req.transaction; if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail. // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases. // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we // do not create a new database by accident here. req.onerror = preventDefault; // Prohibit onabort error from firing before we're done! upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.) // Close database and delete it. req.result.close(); var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here! delreq.onsuccess = delreq.onerror = wrap(function () { reject(new exceptions.NoSuchDatabase('Database ' + dbName + ' doesnt exist')); }); } else { upgradeTransaction.onerror = wrap(eventRejectHandler(reject)); var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix. runUpgraders(oldVer / 10, upgradeTransaction, reject, req); } }, reject); req.onsuccess = wrap(function () { // Core opening procedure complete. Now let's just record some stuff. upgradeTransaction = null; idbdb = req.result; connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari. if (autoSchema) readGlobalSchema();else if (idbdb.objectStoreNames.length > 0) { try { adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY)); } catch (e) { // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120. } } idbdb.onversionchange = wrap(function (ev) { db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari) db.on("versionchange").fire(ev); }); if (!hasNativeGetDatabaseNames) { // Update localStorage with list of database names globalDatabaseList(function (databaseNames) { if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName); }); } resolve(); }, reject); })]).then(function () { // Before finally resolving the dbReadyPromise and this promise, // call and await all on('ready') subscribers: // Dexie.vip() makes subscribers able to use the database while being opened. // This is a must since these subscribers take part of the opening procedure. return Dexie.vip(db.on.ready.fire); }).then(function () { // Resolve the db.open() with the db instance. isBeingOpened = false; return db; }).catch(function (err) { try { // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit. upgradeTransaction && upgradeTransaction.abort(); } catch (e) {} isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event). db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh. // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that. dbOpenError = err; // Record the error. It will be used to reject further promises of db operations. return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught(). }).finally(function () { openComplete = true; resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters. }); }; this.close = function () { var idx = connections.indexOf(db); if (idx >= 0) connections.splice(idx, 1); if (idbdb) { try { idbdb.close(); } catch (e) {} idbdb = null; } autoOpen = false; dbOpenError = new exceptions.DatabaseClosed(); if (isBeingOpened) cancelOpen(dbOpenError); // Reset dbReadyPromise promise: dbReadyPromise = new Promise(function (resolve) { dbReadyResolve = resolve; }); openCanceller = new Promise(function (_, reject) { cancelOpen = reject; }); }; this.delete = function () { var hasArguments = arguments.length > 0; return new Promise(function (resolve, reject) { if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); if (isBeingOpened) { dbReadyPromise.then(doDelete); } else { doDelete(); } function doDelete() { db.close(); var req = indexedDB.deleteDatabase(dbName); req.onsuccess = wrap(function () { if (!hasNativeGetDatabaseNames) { globalDatabaseList(function (databaseNames) { var pos = databaseNames.indexOf(dbName); if (pos >= 0) return databaseNames.splice(pos, 1); }); } resolve(); }); req.onerror = wrap(eventRejectHandler(reject)); req.onblocked = fireOnBlocked; } }).uncaught(dbUncaught); }; this.backendDB = function () { return idbdb; }; this.isOpen = function () { return idbdb !== null; }; this.hasFailed = function () { return dbOpenError !== null; }; this.dynamicallyOpened = function () { return autoSchema; }; // // Properties // this.name = dbName; // db.tables - an array of all Table instances. setProp(this, "tables", { get: function () { /// <returns type="Array" elementType="WriteableTable" /> return keys(allTables).map(function (name) { return allTables[name]; }); } }); // // Events // this.on = Events(this, "error", "populate", "blocked", "versionchange", { ready: [promisableChain, nop] }); this.on.error.subscribe = deprecated("Dexie.on.error", this.on.error.subscribe); this.on.error.unsubscribe = deprecated("Dexie.on.error.unsubscribe", this.on.error.unsubscribe); this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { return function (subscriber, bSticky) { Dexie.vip(function () { if (openComplete) { // Database already open. Call subscriber asap. if (!dbOpenError) Promise.resolve().then(subscriber); // bSticky: Also subscribe to future open sucesses (after close / reopen) if (bSticky) subscribe(subscriber); } else { // Database not yet open. Subscribe to it. subscribe(subscriber); // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. if (!bSticky) subscribe(function unsubscribe() { db.on.ready.unsubscribe(subscriber); db.on.ready.unsubscribe(unsubscribe); }); } }); }; }); fakeAutoComplete(function () { db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema)); db.on("error").fire(new Error()); }); this.transaction = function (mode, tableInstances, scopeFunc) { /// <summary> /// /// </summary> /// <param name="mode" type="String">"r" for readonly, or "rw" for readwrite</param> /// <param name="tableInstances">Table instance, Array of Table instances, String or String Array of object stores to include in the transaction</param> /// <param name="scopeFunc" type="Function">Function to execute with transaction</param> // Let table arguments be all arguments between mode and last argument. var i = arguments.length; if (i < 2) throw new exceptions.InvalidArgument("Too few arguments"); // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments) // and clone arguments except the first one into local var 'args'. var args = new Array(i - 1); while (--i) { args[i - 1] = arguments[i]; } // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments. scopeFunc = args.pop(); var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays. var parentTransaction = PSD.trans; // Check if parent transactions is bound to this db instance, and if caller wants to reuse it if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null; var onlyIfCompatible = mode.indexOf('?') !== -1; mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. try { // // Get storeNames from arguments. Either through given table instances, or through given table names. // var storeNames = tables.map(function (table) { var storeName = table instanceof Table ? table.name : table; if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); return storeName; }); // // Resolve mode. Allow shortcuts "r" and "rw". // if (mode == "r" || mode == READONLY) mode = READONLY;else if (mode == "rw" || mode == READWRITE) mode = READWRITE;else throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); if (parentTransaction) { // Basic checks if (parentTransaction.mode === READONLY && mode === READWRITE) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); } if (parentTransaction) { storeNames.forEach(function (storeName) { if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); } }); } } } catch (e) { return parentTransaction ? parentTransaction._promise(null, function (_, reject) { reject(e); }) : rejection(e, dbUncaught); } // If this is a sub-transaction, lock the parent and then launch the sub-transaction. return parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, "lock") : db._whenReady(enterTransactionScope); function enterTransactionScope(resolve) { var parentPSD = PSD; resolve(Promise.resolve().then(function () { return newScope(function () { // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction(). PSD.transless = PSD.transless || parentPSD; // Our transaction. //return new Promise((resolve, reject) => { var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction); // Let the transaction instance be part of a Promise-specific data (PSD) value. PSD.trans = trans; if (parentTransaction) { // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing) trans.idbtrans = parentTransaction.idbtrans; } else { trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it. } // Provide arguments to the scope function (for backward compatibility) var tableArgs = storeNames.map(function (name) { return allTables[name]; }); tableArgs.push(trans); var returnValue; return Promise.follow(function () { // Finally, call the scope function with our table and transaction arguments. returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func. if (returnValue) { if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { // scopeFunc returned an iterator with throw-support. Handle yield as await. returnValue = awaitIterator(returnValue); } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) { throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: " + scopeFunc.toString()); } } }).uncaught(dbUncaught).then(function () { if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion. return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well. }).then(function () { return returnValue; }).catch(function (e) { //reject(e); trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc! return rejection(e); }); //}); }); })); } }; this.table = function (tableName) { /// <returns type="WriteableTable"></returns> if (fake && autoSchema) return new WriteableTable(tableName); if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable('Table ' + tableName + ' does not exist'); } return allTables[tableName]; }; // // // // Table Class // // // function Table(name, tableSchema, collClass) { /// <param name="name" type="String"></param> this.name = name; this.schema = tableSchema; this.hook = allTables[name] ? allTables[name].hook : Events(null, { "creating": [hookCreatingChain, nop], "reading": [pureFunctionChain, mirror], "updating": [hookUpdatingChain, nop], "deleting": [hookDeletingChain, nop] }); this._collClass = collClass || Collection; } props(Table.prototype, { // // Table Protected Methods // _trans: function getTransaction(mode, fn, writeLocked) { var trans = PSD.trans; return trans && trans.db === db ? trans._promise(mode, fn, writeLocked) : tempTransaction(mode, [this.name], fn); }, _idbstore: function getIDBObjectStore(mode, fn, writeLocked) { if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion. var trans = PSD.trans, tableName = this.name; function supplyIdbStore(resolve, reject, trans) { fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans); } return trans && trans.db === db ? trans._promise(mode, supplyIdbStore, writeLocked) : tempTransaction(mode, [this.name], supplyIdbStore); }, // // Table Public Methods // get: function (key, cb) { var self = this; return this._idbstore(READONLY, function (resolve, reject, idbstore) { fake && resolve(self.schema.instanceTemplate); var req = idbstore.get(key); req.onerror = eventRejectHandler(reject); req.onsuccess = wrap(function () { resolve(self.hook.reading.fire(req.result)); }, reject); }).then(cb); }, where: function (indexName) { return new WhereClause(this, indexName); }, count: function (cb) { return this.toCollection().count(cb); }, offset: function (offset) { return this.toCollection().offset(offset); }, limit: function (numRows) { return this.toCollection().limit(numRows); }, reverse: function () { return this.toCollection().reverse(); }, filter: function (filterFunction) { return this.toCollection().and(filterFunction); }, each: function (fn) { return this.toCollection().each(fn); }, toArray: function (cb) { return this.toCollection().toArray(cb); }, orderBy: function (index) { return new this._collClass(new WhereClause(this, index)); }, toCollection: function () { return new this._collClass(new WhereClause(this)); }, mapToClass: function (constructor, structure) { /// <summary> /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}. /// </summary> /// <param name="constructor">Constructor function representing the class.</param> /// <param name="structure" optional="true">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], password}</param> this.schema.mappedClass = constructor; var instanceTemplate = Object.create(constructor.prototype); if (structure) { // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance. applyStructure(instanceTemplate, structure); } this.schema.instanceTemplate = instanceTemplate; // Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class // no matter which method to use for reading (Table.get() or Table.where(...)... ) var readHook = function (obj) { if (!obj) return obj; // No valid object. (Value is null). Return as is. // Create a new object that derives from constructor: var res = Object.create(constructor.prototype); // Clone members: for (var m in obj) { if (hasOwn(obj, m)) try { res[m] = obj[m]; } catch (_) {} }return res; }; if (this.schema.readHook) { this.hook.reading.unsubscribe(this.schema.readHook); } this.schema.readHook = readHook; this.hook("reading", readHook); return constructor; }, defineClass: function (structure) { /// <summary> /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database /// as well as making it possible to extend the prototype of the returned constructor function. /// </summary> /// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param> return this.mapToClass(Dexie.defineClass(structure), structure); } }); // // // // WriteableTable Class (extends Table) // // // function WriteableTable(name, tableSchema, collClass) { Table.call(this, name, tableSchema, collClass || WriteableCollection); } function BulkErrorHandlerCatchAll(errorList, done, supportHooks) { return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) { errorList.push(e); done && done(); }); } function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) { // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...], // else keysOrTuples must be just an array of keys: [key1, key2, ...]. return new Promise(function (resolve, reject) { var len = keysOrTuples.length, lastItem = len - 1; if (len === 0) return resolve(); if (!hasDeleteHook) { for (var i = 0; i < len; ++i) { var req = idbstore.delete(keysOrTuples[i]); req.onerror = wrap(eventRejectHandler(reject)); if (i === lastItem) req.onsuccess = wrap(function () { return resolve(); }); } } else { var hookCtx, errorHandler = hookedEventRejectHandler(reject), successHandler = hookedEventSuccessHandler(null); tryCatch(function () { for (var i = 0; i < len; ++i) { hookCtx = { onsuccess: null, onerror: null }; var tuple = keysOrTuples[i]; deletingHook.call(hookCtx, tuple[0], tuple[1], trans); var req = idbstore.delete(tuple[0]); req._hookCtx = hookCtx; req.onerror = errorHandler; if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve);else req.onsuccess = successHandler; } }, function (err) { hookCtx.onerror && hookCtx.onerror(err); throw err; }); } }).uncaught(dbUncaught); } derive(WriteableTable).from(Table).extend({ bulkDelete: function (keys$$1) { if (this.hook.deleting.fire === nop) { return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { resolve(bulkDelete(idbstore, trans, keys$$1, false, nop)); }); } else { return this.where(':id').anyOf(keys$$1).delete().then(function () {}); // Resolve with undefined. } }, bulkPut: function (objects, keys$$1) { var _this = this; return this._idbstore(READWRITE, function (resolve, reject, idbstore) { if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); if (objects.length === 0) return resolve(); // Caller provided empty list. var done = function (result) { if (errorList.length === 0) resolve(result);else reject(new BulkError(_this.name + '.bulkPut(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList)); }; var req, errorList = [], errorHandler, numObjs = objects.length, table = _this; if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) { // // Standard Bulk (no 'creating' or 'updating' hooks to care about) // errorHandler = BulkErrorHandlerCatchAll(errorList); for (var i = 0, l = objects.length; i < l; ++i) { req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]); req.onerror = errorHandler; } // Only need to catch success or error on the last operation // according to the IDB spec. req.onerror = BulkErrorHandlerCatchAll(errorList, done); req.onsuccess = eventSuccessHandler(done); } else { var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(function (o) { return getByKeyPath(o, idbstore.keyPath); }); // Generate map of {[key]: object} var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) { return key != null && [key, objects[i]]; }); var promise = !effectiveKeys ? // Auto-incremented key-less objects only without any keys argument. table.bulkAdd(objects) : // Keys provided. Either as inbound in provided objects, or as a keys argument. // Begin with updating those that exists in DB: table.where(':id').anyOf(effectiveKeys.filter(function (key) { return key != null; })).modify(function () { this.value = objectLookup[this.primKey]; objectLookup[this.primKey] = null; // Mark as "don't add this" }).catch(ModifyError, function (e) { errorList = e.failures; // No need to concat here. These are the first errors added. }).then(function () { // Now, let's examine which items didnt exist so we can add them: var objsToAdd = [], keysToAdd = keys$$1 && []; // Iterate backwards. Why? Because if same key was used twice, just add the last one. for (var i = effectiveKeys.length - 1; i >= 0; --i) { var key = effectiveKeys[i]; if (key == null || objectLookup[key]) { objsToAdd.push(objects[i]); keys$$1 && keysToAdd.push(key); if (key != null) objectLookup[key] = null; // Mark as "dont add again" } } // The items are in reverse order so reverse them before adding. // Could be important in order to get auto-incremented keys the way the caller // would expect. Could have used unshift instead of push()/reverse(), // but: http://jsperf.com/unshift-vs-reverse objsToAdd.reverse(); keys$$1 && keysToAdd.reverse(); return table.bulkAdd(objsToAdd, keysToAdd); }).then(function (lastAddedKey) { // Resolve with key of the last object in given arguments to bulkPut(): var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided. return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey; }); promise.then(done).catch(BulkError, function (e) { // Concat failure from ModifyError and reject using our 'done' method. errorList = errorList.concat(e.failures); done(); }).catch(reject); } }, "locked"); // If called from transaction scope, lock transaction til all steps are done. }, bulkAdd: function (objects, keys$$1) { var self = this, creatingHook = this.hook.creating.fire; return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); if (objects.length === 0) return resolve(); // Caller provided empty list. function done(result) { if (errorList.length === 0) resolve(result);else reject(new BulkError(self.name + '.bulkAdd(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList)); } var req, errorList = [], errorHandler, successHandler, numObjs = objects.length; if (creatingHook !== nop) { // // There are subscribers to hook('creating') // Must behave as documented. // var keyPath = idbstore.keyPath, hookCtx; errorHandler = BulkErrorHandlerCatchAll(errorList, null, true); successHandler = hookedEventSuccessHandler(null); tryCatch(function () { for (var i = 0, l = objects.length; i < l; ++i) { hookCtx = { onerror: null, onsuccess: null }; var key = keys$$1 && keys$$1[i]; var obj = objects[i], effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined, keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); if (effectiveKey == null && keyToUse != null) { if (keyPath) { obj = deepClone(obj); setByKeyPath(obj, keyPath, keyToUse); } else { key = keyToUse; } } req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); req._hookCtx = hookCtx; if (i < l - 1) { req.onerror = errorHandler; if (hookCtx.onsuccess) req.onsuccess = successHandler; } } }, function (err) { hookCtx.onerror && hookCtx.onerror(err); throw err; }); req.onerror = BulkErrorHandlerCatchAll(errorList, done, true); req.onsuccess = hookedEventSuccessHandler(done); } else { // // Standard Bulk (no 'creating' hook to care about) // errorHandler = BulkErrorHandlerCatchAll(errorList); for (var i = 0, l = objects.length; i < l; ++i) { req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]); req.onerror = errorHandler; } // Only need to catch success or error on the last operation // according to the IDB spec. req.onerror = BulkErrorHandlerCatchAll(errorList, done); req.onsuccess = eventSuccessHandler(done); } }); }, add: function (obj, key) { /// <summary> /// Add an object to the database. In case an object with same primary key already exists, the object will not be added. /// </summary> /// <param name="obj" type="Object">A javascript object to insert</param> /// <param name="key" optional="true">Primary key</param> var creatingHook = this.hook.creating.fire; return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { var hookCtx = { onsuccess: null, onerror: null }; if (creatingHook !== nop) { var effectiveKey = key != null ? key : idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined; var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key. if (effectiveKey == null && keyToUse != null) { // Using "==" and "!=" to check for either null or undefined! if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse);else key = keyToUse; } } try { var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); req._hookCtx = hookCtx; req.onerror = hookedEventRejectHandler(reject); req.onsuccess = hookedEventSuccessHandler(function (result) { // TODO: Remove these two lines in next major release (2.0?) // It's no good practice to have side effects on provided parameters var keyPath = idbstore.keyPath; if (keyPath) setByKeyPath(obj, keyPath, result); resolve(result); }); } catch (e) { if (hookCtx.onerror) hookCtx.onerror(e); throw e; } }); }, put: function (obj, key) { /// <summary> /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated. /// </summary> /// <param name="obj" type="Object">A javascript object to insert or update</param> /// <param name="key" optional="true">Primary key</param> var self = this, creatingHook = this.hook.creating.fire, updatingHook = this.hook.updating.fire; if (creatingHook !== nop || updatingHook !== nop) { // // People listens to when("creating") or when("updating") events! // We must know whether the put operation results in an CREATE or UPDATE. // return this._trans(READWRITE, function (resolve, reject, trans) { // Since key is optional, make sure we get it from obj if not provided var effectiveKey = key !== undefined ? key : self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath); if (effectiveKey == null) { // "== null" means checking for either null or undefined. // No primary key. Must use add(). self.add(obj).then(resolve, reject); } else { // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add(). trans._lock(); // Needed because operation is splitted into modify() and add(). // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation. obj = deepClone(obj); self.where(":id").equals(effectiveKey).modify(function () { // Replace extisting value with our object // CRUD event firing handled in WriteableCollection.modify() this.value = obj; }).then(function (count) { if (count === 0) { // Object's key was not found. Add the object instead. // CRUD event firing will be done in add() return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key. } else { return effectiveKey; // Resolve with the provided key. } }).finally(function () { trans._unlock(); }).then(resolve, reject); } }); } else { // Use the standard IDB put() method. return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj); req.onerror = eventRejectHandler(reject); req.onsuccess = function (ev) { var keyPath = idbstore.keyPath; if (keyPath) setByKeyPath(obj, keyPath, ev.target.result); resolve(req.result); }; }); } }, 'delete': function (key) { /// <param name="key">Primary key of the object to delete</param> if (this.hook.deleting.subscribers.length) { // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted. return this.where(":id").equals(key).delete(); } else { // No one listens. Use standard IDB delete() method. return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = idbstore.delete(key); req.onerror = eventRejectHandler(reject); req.onsuccess = function () { resolve(req.result); }; }); } }, clear: function () { if (this.hook.deleting.subscribers.length) { // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted. return this.toCollection().delete(); } else { return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = idbstore.clear(); req.onerror = eventRejectHandler(reject); req.onsuccess = function () { resolve(req.result); }; }); } }, update: function (keyOrObject, modifications) { if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument("Modifications must be an object."); if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { // object to modify. Also modify given object with the modifications: keys(modifications).forEach(function (keyPath) { setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); }); var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); if (key === undefined) return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key"), dbUncaught); return this.where(":id").equals(key).modify(modifications); } else { // key to modify return this.where(":id").equals(keyOrObject).modify(modifications); } } }); // // // // Transaction Class // // // function Transaction(mode, storeNames, dbschema, parent) { var _this2 = this; /// <summary> /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction. /// </summary> /// <param name="mode" type="String">Any of "readwrite" or "readonly"</param> /// <param name="storeNames" type="Array">Array of table names to operate on</param> this.db = db; this.mode = mode; this.storeNames = storeNames; this.idbtrans = null; this.on = Events(this, "complete", "error", "abort"); this.parent = parent || null; this.active = true; this._tables = null; this._reculock = 0; this._blockedFuncs = []; this._psd = null; this._dbschema = dbschema; this._resolve = null; this._reject = null; this._completion = new Promise(function (resolve, reject) { _this2._resolve = resolve; _this2._reject = reject; }).uncaught(dbUncaught); this._completion.then(function () { _this2.on.complete.fire(); }, function (e) { _this2.on.error.fire(e); _this2.parent ? _this2.parent._reject(e) : _this2.active && _this2.idbtrans && _this2.idbtrans.abort(); _this2.active = false; return rejection(e); // Indicate we actually DO NOT catch this error. }); } props(Transaction.prototype, { // // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions) // _lock: function () { assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. // Temporary set all requests into a pending queue if they are called before database is ready. ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage) if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this; return this; }, _unlock: function () { assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. if (--this._reculock === 0) { if (!PSD.global) PSD.lockOwnerFor = null; while (this._blockedFuncs.length > 0 && !this._locked()) { var fn = this._blockedFuncs.shift(); try { fn(); } catch (e) {} } } return this; }, _locked: function () { // Checks if any write-lock is applied on this transaction. // To simplify the Dexie API for extension implementations, we support recursive locks. // This is accomplished by using "Promise Specific Data" (PSD). // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ). // PSD is local to code executing on top of the call stacks of any of any code executed by Promise(): // * callback given to the Promise() constructor (function (resolve, reject){...}) // * callbacks given to then()/catch()/finally() methods (function (value){...}) // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise. // Derivation is done so that the inner PSD __proto__ points to the outer PSD. // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock. return this._reculock && PSD.lockOwnerFor !== this; }, create: function (idbtrans) { var _this3 = this; assert(!this.idbtrans); if (!idbtrans && !idbdb) { switch (dbOpenError && dbOpenError.name) { case "DatabaseClosedError": // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() throw new exceptions.DatabaseClosed(dbOpenError); case "MissingAPIError": // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); default: // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()! throw new exceptions.OpenFailed(dbOpenError); } } if (!this.active) throw new exceptions.TransactionInactive(); assert(this._completion._state === null); idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode); idbtrans.onerror = wrap(function (ev) { preventDefault(ev); // Prohibit default bubbling to window.error _this3._reject(idbtrans.error); }); idbtrans.onabort = wrap(function (ev) { preventDefault(ev); _this3.active && _this3._reject(new exceptions.Abort()); _this3.active = false; _this3.on("abort").fire(ev); }); idbtrans.oncomplete = wrap(function () { _this3.active = false; _this3._resolve(); }); return this; }, _promise: function (mode, fn, bWriteLock) { var self = this; return newScope(function () { var p; // Read lock always if (!self._locked()) { p = self.active ? new Promise(function (resolve, reject) { if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly("Transaction is readonly"); if (!self.idbtrans && mode) self.create(); if (bWriteLock) self._lock(); // Write lock if write operation is requested fn(resolve, reject, self); }) : rejection(new exceptions.TransactionInactive()); if (self.active && bWriteLock) p.finally(function () { self._unlock(); }); } else { // Transaction is write-locked. Wait for mutex. p = new Promise(function (resolve, reject) { self._blockedFuncs.push(function () { self._promise(mode, fn, bWriteLock).then(resolve, reject); }); }); } p._lib = true; return p.uncaught(dbUncaught); }); }, // // Transaction Public Properties and Methods // abort: function () { this.active && this._reject(new exceptions.Abort()); this.active = false; }, tables: { get: deprecated("Transaction.tables", function () { return arrayToObject(this.storeNames, function (name) { return [name, allTables[name]]; }); }, "Use db.tables()") }, complete: deprecated("Transaction.complete()", function (cb) { return this.on("complete", cb); }), error: deprecated("Transaction.error()", function (cb) { return this.on("error", cb); }), table: deprecated("Transaction.table()", function (name) { if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable("Table " + name + " not in transaction"); return allTables[name]; }) }); // // // // WhereClause // // // function WhereClause(table, index, orCollection) { /// <param name="table" type="Table"></param> /// <param name="index" type="String" optional="true"></param> /// <param name="orCollection" type="Collection" optional="true"></param> this._ctx = { table: table, index: index === ":id" ? null : index, collClass: table._collClass, or: orCollection }; } props(WhereClause.prototype, function () { // WhereClause private methods function fail(collectionOrWhereClause, err, T) { var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause; collection._ctx.error = T ? new T(err) : new TypeError(err); return collection; } function emptyCollection(whereClause) { return new whereClause._ctx.collClass(whereClause, function () { return IDBKeyRange.only(""); }).limit(0); } function upperFactory(dir) { return dir === "next" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); }; } function lowerFactory(dir) { return dir === "next" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); }; } function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { var length = Math.min(key.length, lowerNeedle.length); var llp = -1; for (var i = 0; i < length; ++i) { var lwrKeyChar = lowerKey[i]; if (lwrKeyChar !== lowerNeedle[i]) { if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); return null; } if (cmp(key[i], lwrKeyChar) < 0) llp = i; } if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length); if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length); return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1); } function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { /// <param name="needles" type="Array" elementType="String"></param> var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; if (!needles.every(function (s) { return typeof s === 'string'; })) { return fail(whereClause, STRING_EXPECTED); } function initDirection(dir) { upper = upperFactory(dir); lower = lowerFactory(dir); compare = dir === "next" ? simpleCompare : simpleCompareReverse; var needleBounds = needles.map(function (needle) { return { lower: lower(needle), upper: upper(needle) }; }).sort(function (a, b) { return compare(a.lower, b.lower); }); upperNeedles = needleBounds.map(function (nb) { return nb.upper; }); lowerNeedles = needleBounds.map(function (nb) { return nb.lower; }); direction = dir; nextKeySuffix = dir === "next" ? "" : suffix; } initDirection("next"); var c = new whereClause._ctx.collClass(whereClause, function () { return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); c._ondirectionchange = function (direction) { // This event onlys occur before filter is called the first time. initDirection(direction); }; var firstPossibleNeedle = 0; c._addAlgorithm(function (cursor, advance, resolve) { /// <param name="cursor" type="IDBCursor"></param> /// <param name="advance" type="Function"></param> /// <param name="resolve" type="Function"></param> var key = cursor.key; if (typeof key !== 'string') return false; var lowerKey = lower(key); if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { return true; } else { var lowestPossibleCasing = null; for (var i = firstPossibleNeedle; i < needlesLen; ++i) { var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1;else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { lowestPossibleCasing = casing; } } if (lowestPossibleCasing !== null) { advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); } else { advance(resolve); } return false; } }); return c; } // // WhereClause public methods // return { between: function (lower, upper, includeLower, includeUpper) { /// <summary> /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates. /// </summary> /// <param name="lower"></param> /// <param name="upper"></param> /// <param name="includeLower" optional="true">Whether items that equals lower should be included. Default true.</param> /// <param name="includeUpper" optional="true">Whether items that equals upper should be included. Default false.</param> /// <returns type="Collection"></returns> includeLower = includeLower !== false; // Default to true includeUpper = includeUpper === true; // Default to false try { if (cmp(lower, upper) > 0 || cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection. return new this._ctx.collClass(this, function () { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); }); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); } }, equals: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.only(value); }); }, above: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.lowerBound(value, true); }); }, aboveOrEqual: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.lowerBound(value); }); }, below: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.upperBound(value, true); }); }, belowOrEqual: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.upperBound(value); }); }, startsWith: function (str) { /// <param name="str" type="String"></param> if (typeof str !== 'string') return fail(this, STRING_EXPECTED); return this.between(str, str + maxString, true, true); }, startsWithIgnoreCase: function (str) { /// <param name="str" type="String"></param> if (str === "") return this.startsWith(str); return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); }, equalsIgnoreCase: function (str) { /// <param name="str" type="String"></param> return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); }, anyOfIgnoreCase: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return emptyCollection(this); return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); }, startsWithAnyOfIgnoreCase: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return emptyCollection(this); return addIgnoreCaseAlgorithm(this, function (x, a) { return a.some(function (n) { return x.indexOf(n) === 0; }); }, set, maxString); }, anyOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); var compare = ascending; try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); } if (set.length === 0) return emptyCollection(this); var c = new this._ctx.collClass(this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); }); c._ondirectionchange = function (direction) { compare = direction === "next" ? ascending : descending; set.sort(compare); }; var i = 0; c._addAlgorithm(function (cursor, advance, resolve) { var key = cursor.key; while (compare(key, set[i]) > 0) { // The cursor has passed beyond this key. Check next. ++i; if (i === set.length) { // There is no next. Stop searching. advance(resolve); return false; } } if (compare(key, set[i]) === 0) { // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. return true; } else { // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. advance(function () { cursor.continue(set[i]); }); return false; } }); return c; }, notEqual: function (value) { return this.inAnyRange([[-Infinity, value], [value, maxKey]], { includeLowers: false, includeUppers: false }); }, noneOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection. try { set.sort(ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); } // Transform ["a","b","c"] to a set of ranges for between/above/below: [[-Infinity,"a"], ["a","b"], ["b","c"], ["c",maxKey]] var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]]; }, null); ranges.push([set[set.length - 1], maxKey]); return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); }, /** Filter out values withing given set of ranges. * Example, give children and elders a rebate of 50%: * * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2}); * * @param {(string|number|Date|Array)[][]} ranges * @param {{includeLowers: boolean, includeUppers: boolean}} options */ inAnyRange: function (ranges, options) { var ctx = this._ctx; if (ranges.length === 0) return emptyCollection(this); if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0; })) { return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); } var includeLowers = !options || options.includeLowers !== false; // Default to true var includeUppers = options && options.includeUppers === true; // Default to false function addRange(ranges, newRange) { for (var i = 0, l = ranges.length; i < l; ++i) { var range = ranges[i]; if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { range[0] = min(range[0], newRange[0]); range[1] = max(range[1], newRange[1]); break; } } if (i === l) ranges.push(newRange); return ranges; } var sortDirection = ascending; function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } // Join overlapping ranges var set; try { set = ranges.reduce(addRange, []); set.sort(rangeSorter); } catch (ex) { return fail(this, INVALID_KEY_ARGUMENT); } var i = 0; var keyIsBeyondCurrentEntry = includeUppers ? function (key) { return ascending(key, set[i][1]) > 0; } : function (key) { return ascending(key, set[i][1]) >= 0; }; var keyIsBeforeCurrentEntry = includeLowers ? function (key) { return descending(key, set[i][0]) > 0; } : function (key) { return descending(key, set[i][0]) >= 0; }; function keyWithinCurrentRange(key) { return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); } var checkKey = keyIsBeyondCurrentEntry; var c = new ctx.collClass(this, function () { return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); }); c._ondirectionchange = function (direction) { if (direction === "next") { checkKey = keyIsBeyondCurrentEntry; sortDirection = ascending; } else { checkKey = keyIsBeforeCurrentEntry; sortDirection = descending; } set.sort(rangeSorter); }; c._addAlgorithm(function (cursor, advance, resolve) { var key = cursor.key; while (checkKey(key)) { // The cursor has passed beyond this key. Check next. ++i; if (i === set.length) { // There is no next. Stop searching. advance(resolve); return false; } } if (keyWithinCurrentRange(key)) { // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. return true; } else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) { // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border. // Continue to next key but don't include this one. return false; } else { // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. advance(function () { if (sortDirection === ascending) cursor.continue(set[i][0]);else cursor.continue(set[i][1]); }); return false; } }); return c; }, startsWithAnyOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (!set.every(function (s) { return typeof s === 'string'; })) { return fail(this, "startsWithAnyOf() only works with strings"); } if (set.length === 0) return emptyCollection(this); return this.inAnyRange(set.map(function (str) { return [str, str + maxString]; })); } }; }); // // // // Collection Class // // // function Collection(whereClause, keyRangeGenerator) { /// <summary> /// /// </summary> /// <param name="whereClause" type="WhereClause">Where clause instance</param> /// <param name="keyRangeGenerator" value="function(){ return IDBKeyRange.bound(0,1);}" optional="true"></param> var keyRange = null, error = null; if (keyRangeGenerator) try { keyRange = keyRangeGenerator(); } catch (ex) { error = ex; } var whereCtx = whereClause._ctx, table = whereCtx.table; this._ctx = { table: table, index: whereCtx.index, isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name, range: keyRange, keysOnly: false, dir: "next", unique: "", algorithm: null, filter: null, replayFilter: null, justLimit: true, // True if a replayFilter is just a filter that performs a "limit" operation (or none at all) isMatch: null, offset: 0, limit: Infinity, error: error, // If set, any promise must be rejected with this error or: whereCtx.or, valueMapper: table.hook.reading.fire }; } function isPlainKeyRange(ctx, ignoreLimitFilter) { return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); } props(Collection.prototype, function () { // // Collection Private Functions // function addFilter(ctx, fn) { ctx.filter = combine(ctx.filter, fn); } function addReplayFilter(ctx, factory, isLimitFilter) { var curr = ctx.replayFilter; ctx.replayFilter = curr ? function () { return combine(curr(), factory()); } : factory; ctx.justLimit = isLimitFilter && !curr; } function addMatchFilter(ctx, fn) { ctx.isMatch = combine(ctx.isMatch, fn); } /** @param ctx { * isPrimKey: boolean, * table: Table, * index: string * } * @param store IDBObjectStore **/ function getIndexOrStore(ctx, store) { if (ctx.isPrimKey) return store; var indexSpec = ctx.table.schema.idxByName[ctx.index]; if (!indexSpec) throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed"); return store.index(indexSpec.name); } /** @param ctx { * isPrimKey: boolean, * table: Table, * index: string, * keysOnly: boolean, * range?: IDBKeyRange, * dir: "next" | "prev" * } */ function openCursor(ctx, store) { var idxOrStore = getIndexOrStore(ctx, store); return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique); } function iter(ctx, fn, resolve, reject, idbstore) { var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; if (!ctx.or) { iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper); } else (function () { var set = {}; var resolved = 0; function resolveboth() { if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion. } function union(item, cursor, advance) { if (!filter || filter(cursor, advance, resolveboth, reject)) { var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string if (!hasOwn(set, key)) { set[key] = true; fn(item, cursor, advance); } } } ctx.or._iterate(union, resolveboth, reject, idbstore); iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper); })(); } function getInstanceTemplate(ctx) { return ctx.table.schema.instanceTemplate; } return { // // Collection Protected Functions // _read: function (fn, cb) { var ctx = this._ctx; if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });else return ctx.table._idbstore(READONLY, fn).then(cb); }, _write: function (fn) { var ctx = this._ctx; if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });else return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued. }, _addAlgorithm: function (fn) { var ctx = this._ctx; ctx.algorithm = combine(ctx.algorithm, fn); }, _iterate: function (fn, resolve, reject, idbstore) { return iter(this._ctx, fn, resolve, reject, idbstore); }, clone: function (props$$1) { var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); if (props$$1) extend(ctx, props$$1); rv._ctx = ctx; return rv; }, raw: function () { this._ctx.valueMapper = null; return this; }, // // Collection Public methods // each: function (fn) { var ctx = this._ctx; if (fake) { var item = getInstanceTemplate(ctx), primKeyPath = ctx.table.schema.primKey.keyPath, key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath), primaryKey = getByKeyPath(item, primKeyPath); fn(item, { key: key, primaryKey: primaryKey }); } return this._read(function (resolve, reject, idbstore) { iter(ctx, fn, resolve, reject, idbstore); }); }, count: function (cb) { if (fake) return Promise.resolve(0).then(cb); var ctx = this._ctx; if (isPlainKeyRange(ctx, true)) { // This is a plain key range. We can use the count() method if the index. return this._read(function (resolve, reject, idbstore) { var idx = getIndexOrStore(ctx, idbstore); var req = ctx.range ? idx.count(ctx.range) : idx.count(); req.onerror = eventRejectHandler(reject); req.onsuccess = function (e) { resolve(Math.min(e.target.result, ctx.limit)); }; }, cb); } else { // Algorithms, filters or expressions are applied. Need to count manually. var count = 0; return this._read(function (resolve, reject, idbstore) { iter(ctx, function () { ++count;return false; }, function () { resolve(count); }, reject, idbstore); }, cb); } }, sortBy: function (keyPath, cb) { /// <param name="keyPath" type="String"></param> var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; function getval(obj, i) { if (i) return getval(obj[parts[i]], i - 1); return obj[lastPart]; } var order = this._ctx.dir === "next" ? 1 : -1; function sorter(a, b) { var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); return aVal < bVal ? -order : aVal > bVal ? order : 0; } return this.toArray(function (a) { return a.sort(sorter); }).then(cb); }, toArray: function (cb) { var ctx = this._ctx; return this._read(function (resolve, reject, idbstore) { fake && resolve([getInstanceTemplate(ctx)]); if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { // Special optimation if we could use IDBObjectStore.getAll() or // IDBKeyRange.getAll(): var readingHook = ctx.table.hook.reading.fire; var idxOrStore = getIndexOrStore(ctx, idbstore); var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range); req.onerror = eventRejectHandler(reject); req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(function (res) { try { resolve(res.map(readingHook)); } catch (e) { reject(e); } })); } else { // Getting array through a cursor. var a = []; iter(ctx, function (item) { a.push(item); }, function arrayComplete() { resolve(a); }, reject, idbstore); } }, cb); }, offset: function (offset) { var ctx = this._ctx; if (offset <= 0) return this; ctx.offset += offset; // For count() if (isPlainKeyRange(ctx)) { addReplayFilter(ctx, function () { var offsetLeft = offset; return function (cursor, advance) { if (offsetLeft === 0) return true; if (offsetLeft === 1) { --offsetLeft;return false; } advance(function () { cursor.advance(offsetLeft); offsetLeft = 0; }); return false; }; }); } else { addReplayFilter(ctx, function () { var offsetLeft = offset; return function () { return --offsetLeft < 0; }; }); } return this; }, limit: function (numRows) { this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count() addReplayFilter(this._ctx, function () { var rowsLeft = numRows; return function (cursor, advance, resolve) { if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here. }; }, true); return this; }, until: function (filterFunction, bIncludeStopEntry) { var ctx = this._ctx; fake && filterFunction(getInstanceTemplate(ctx)); addFilter(this._ctx, function (cursor, advance, resolve) { if (filterFunction(cursor.value)) { advance(resolve); return bIncludeStopEntry; } else { return true; } }); return this; }, first: function (cb) { return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); }, last: function (cb) { return this.reverse().first(cb); }, filter: function (filterFunction) { /// <param name="jsFunctionFilter" type="Function">function(val){return true/false}</param> fake && filterFunction(getInstanceTemplate(this._ctx)); addFilter(this._ctx, function (cursor) { return filterFunction(cursor.value); }); // match filters not used in Dexie.js but can be used by 3rd part libraries to test a // collection for a match without querying DB. Used by Dexie.Observable. addMatchFilter(this._ctx, filterFunction); return this; }, and: function (filterFunction) { return this.filter(filterFunction); }, or: function (indexName) { return new WhereClause(this._ctx.table, indexName, this); }, reverse: function () { this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev"; if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir); return this; }, desc: function () { return this.reverse(); }, eachKey: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; return this.each(function (val, cursor) { cb(cursor.key, cursor); }); }, eachUniqueKey: function (cb) { this._ctx.unique = "unique"; return this.eachKey(cb); }, eachPrimaryKey: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); }, keys: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; var a = []; return this.each(function (item, cursor) { a.push(cursor.key); }).then(function () { return a; }).then(cb); }, primaryKeys: function (cb) { var ctx = this._ctx; if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { // Special optimation if we could use IDBObjectStore.getAllKeys() or // IDBKeyRange.getAllKeys(): return this._read(function (resolve, reject, idbstore) { var idxOrStore = getIndexOrStore(ctx, idbstore); var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range); req.onerror = eventRejectHandler(reject); req.onsuccess = eventSuccessHandler(resolve); }).then(cb); } ctx.keysOnly = !ctx.isMatch; var a = []; return this.each(function (item, cursor) { a.push(cursor.primaryKey); }).then(function () { return a; }).then(cb); }, uniqueKeys: function (cb) { this._ctx.unique = "unique"; return this.keys(cb); }, firstKey: function (cb) { return this.limit(1).keys(function (a) { return a[0]; }).then(cb); }, lastKey: function (cb) { return this.reverse().firstKey(cb); }, distinct: function () { var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes. var set = {}; addFilter(this._ctx, function (cursor) { var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string var found = hasOwn(set, strKey); set[strKey] = true; return !found; }); return this; } }; }); // // // WriteableCollection Class // // function WriteableCollection() { Collection.apply(this, arguments); } derive(WriteableCollection).from(Collection).extend({ // // WriteableCollection Public Methods // modify: function (changes) { var self = this, ctx = this._ctx, hook = ctx.table.hook, updatingHook = hook.updating.fire, deletingHook = hook.deleting.fire; fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate); return this._write(function (resolve, reject, idbstore, trans) { var modifyer; if (typeof changes === 'function') { // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item) if (updatingHook === nop && deletingHook === nop) { // Noone cares about what is being changed. Just let the modifier function be the given argument as is. modifyer = changes; } else { // People want to know exactly what is being modified or deleted. // Let modifyer be a proxy function that finds out what changes the caller is actually doing // and call the hooks accordingly! modifyer = function (item) { var origItem = deepClone(item); // Clone the item first so we can compare laters. if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object) if (!hasOwn(this, "value")) { // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place. deletingHook.call(this, this.primKey, item, trans); } else { // No deletion. Check what was changed var objectDiff = getObjectDiff(origItem, this.value); var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans); if (additionalChanges) { // Hook want to apply additional modifications. Make sure to fullfill the will of the hook. item = this.value; keys(additionalChanges).forEach(function (keyPath) { setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath }); } } }; } } else if (updatingHook === nop) { // changes is a set of {keyPath: value} and no one is listening to the updating hook. var keyPaths = keys(changes); var numKeys = keyPaths.length; modifyer = function (item) { var anythingModified = false; for (var i = 0; i < numKeys; ++i) { var keyPath = keyPaths[i], val = changes[keyPath]; if (getByKeyPath(item, keyPath) !== val) { setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath anythingModified = true; } } return anythingModified; }; } else { // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and // allow it to add additional modifications to make. var origChanges = changes; changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it. modifyer = function (item) { var anythingModified = false; var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans); if (additionalChanges) extend(changes, additionalChanges); keys(changes).forEach(function (keyPath) { var val = changes[keyPath]; if (getByKeyPath(item, keyPath) !== val) { setByKeyPath(item, keyPath, val); anythingModified = true; } }); if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration return anythingModified; }; } var count = 0; var successCount = 0; var iterationComplete = false; var failures = []; var failKeys = []; var currentKey = null; function modifyItem(item, cursor) { currentKey = cursor.primaryKey; var thisContext = { primKey: cursor.primaryKey, value: item, onsuccess: null, onerror: null }; function onerror(e) { failures.push(e); failKeys.push(thisContext.primKey); checkFinished(); return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction } if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update! var bDelete = !hasOwn(thisContext, "value"); ++count; tryCatch(function () { var req = bDelete ? cursor.delete() : cursor.update(thisContext.value); req._hookCtx = thisContext; req.onerror = hookedEventRejectHandler(onerror); req.onsuccess = hookedEventSuccessHandler(function () { ++successCount; checkFinished(); }); }, onerror); } else if (thisContext.onsuccess) { // Hook will expect either onerror or onsuccess to always be called! thisContext.onsuccess(thisContext.value); } } function doReject(e) { if (e) { failures.push(e); failKeys.push(currentKey); } return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys)); } function checkFinished() { if (iterationComplete && successCount + failures.length === count) { if (failures.length > 0) doReject();else resolve(successCount); } } self.clone().raw()._iterate(modifyItem, function () { iterationComplete = true; checkFinished(); }, doReject, idbstore); }); }, 'delete': function () { var _this4 = this; var ctx = this._ctx, range = ctx.range, deletingHook = ctx.table.hook.deleting.fire, hasDeleteHook = deletingHook !== nop; if (!hasDeleteHook && isPlainKeyRange(ctx) && (ctx.isPrimKey && !hangsOnDeleteLargeKeyRange || !range)) // if no range, we'll use clear(). { // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208) // For chromium, this is the way most optimized version. // For IE/Edge, this could hang the indexedDB engine and make operating system instable // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7) return this._write(function (resolve, reject, idbstore) { // Our API contract is to return a count of deleted items, so we have to count() before delete(). var onerror = eventRejectHandler(reject), countReq = range ? idbstore.count(range) : idbstore.count(); countReq.onerror = onerror; countReq.onsuccess = function () { var count = countReq.result; tryCatch(function () { var delReq = range ? idbstore.delete(range) : idbstore.clear(); delReq.onerror = onerror; delReq.onsuccess = function () { return resolve(count); }; }, function (err) { return reject(err); }); }; }); } // Default version to use when collection is not a vanilla IDBKeyRange on the primary key. // Divide into chunks to not starve RAM. // If has delete hook, we will have to collect not just keys but also objects, so it will use // more memory and need lower chunk size. var CHUNKSIZE = hasDeleteHook ? 2000 : 10000; return this._write(function (resolve, reject, idbstore, trans) { var totalCount = 0; // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance. var collection = _this4.clone({ keysOnly: !ctx.isMatch && !hasDeleteHook }) // load just keys (unless filter() or and() or deleteHook has subscribers) .distinct() // In case multiEntry is used, never delete same key twice because resulting count // would become larger than actual delete count. .limit(CHUNKSIZE).raw(); // Don't filter through reading-hooks (like mapped classes etc) var keysOrTuples = []; // We're gonna do things on as many chunks that are needed. // Use recursion of nextChunk function: var nextChunk = function () { return collection.each(hasDeleteHook ? function (val, cursor) { // Somebody subscribes to hook('deleting'). Collect all primary keys and their values, // so that the hook can be called with its values in bulkDelete(). keysOrTuples.push([cursor.primaryKey, cursor.value]); } : function (val, cursor) { // No one subscribes to hook('deleting'). Collect only primary keys: keysOrTuples.push(cursor.primaryKey); }).then(function () { // Chromium deletes faster when doing it in sort order. hasDeleteHook ? keysOrTuples.sort(function (a, b) { return ascending(a[0], b[0]); }) : keysOrTuples.sort(ascending); return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook); }).then(function () { var count = keysOrTuples.length; totalCount += count; keysOrTuples = []; return count < CHUNKSIZE ? totalCount : nextChunk(); }); }; resolve(nextChunk()); }); } }); // // // // ------------------------- Help functions --------------------------- // // // function lowerVersionFirst(a, b) { return a._cfg.version - b._cfg.version; } function setApiOnPlace(objs, tableNames, mode, dbschema) { tableNames.forEach(function (tableName) { var tableInstance = db._tableFactory(mode, dbschema[tableName]); objs.forEach(function (obj) { tableName in obj || (obj[tableName] = tableInstance); }); }); } function removeTablesApi(objs) { objs.forEach(function (obj) { for (var key in obj) { if (obj[key] instanceof Table) delete obj[key]; } }); } function iterate(req, filter, fn, resolve, reject, valueMapper) { // Apply valueMapper (hook('reading') or mappped class) var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; // Wrap fn with PSD and microtick stuff from Promise. var wrappedFn = wrap(mappedFn, reject); if (!req.onerror) req.onerror = eventRejectHandler(reject); if (filter) { req.onsuccess = trycatcher(function filter_record() { var cursor = req.result; if (cursor) { var c = function () { cursor.continue(); }; if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); c(); } else { resolve(); } }, reject); } else { req.onsuccess = trycatcher(function filter_record() { var cursor = req.result; if (cursor) { var c = function () { cursor.continue(); }; wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); c(); } else { resolve(); } }, reject); } } function parseIndexSyntax(indexes) { /// <param name="indexes" type="String"></param> /// <returns type="Array" elementType="IndexSpec"></returns> var rv = []; indexes.split(',').forEach(function (index) { index = index.trim(); var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*" // Let keyPath of "[a+b]" be ["a","b"]: var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; rv.push(new IndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index))); }); return rv; } function cmp(key1, key2) { return indexedDB.cmp(key1, key2); } function min(a, b) { return cmp(a, b) < 0 ? a : b; } function max(a, b) { return cmp(a, b) > 0 ? a : b; } function ascending(a, b) { return indexedDB.cmp(a, b); } function descending(a, b) { return indexedDB.cmp(b, a); } function simpleCompare(a, b) { return a < b ? -1 : a === b ? 0 : 1; } function simpleCompareReverse(a, b) { return a > b ? -1 : a === b ? 0 : 1; } function combine(filter1, filter2) { return filter1 ? filter2 ? function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : filter1 : filter2; } function readGlobalSchema() { db.verno = idbdb.version / 10; db._dbSchema = globalSchema = {}; dbStoreNames = slice(idbdb.objectStoreNames, 0); if (dbStoreNames.length === 0) return; // Database contains no stores. var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly'); dbStoreNames.forEach(function (storeName) { var store = trans.objectStore(storeName), keyPath = store.keyPath, dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted); var indexes = []; for (var j = 0; j < store.indexNames.length; ++j) { var idbindex = store.index(store.indexNames[j]); keyPath = idbindex.keyPath; dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted); indexes.push(index); } globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {}); }); setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema); } function adjustToExistingIndexNames(schema, idbtrans) { /// <summary> /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db /// </summary> /// <param name="schema" type="Object">Map between name and TableSchema</param> /// <param name="idbtrans" type="IDBTransaction"></param> var storeNames = idbtrans.db.objectStoreNames; for (var i = 0; i < storeNames.length; ++i) { var storeName = storeNames[i]; var store = idbtrans.objectStore(storeName); hasGetAll = 'getAll' in store; for (var j = 0; j < store.indexNames.length; ++j) { var indexName = store.indexNames[j]; var keyPath = store.index(indexName).keyPath; var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; if (schema[storeName]) { var indexSpec = schema[storeName].idxByName[dexieName]; if (indexSpec) indexSpec.name = indexName; } } } } function fireOnBlocked(ev) { db.on("blocked").fire(ev); // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: connections.filter(function (c) { return c.name === db.name && c !== db && !c._vcFired; }).map(function (c) { return c.on("versionchange").fire(ev); }); } extend(this, { Collection: Collection, Table: Table, Transaction: Transaction, Version: Version, WhereClause: WhereClause, WriteableCollection: WriteableCollection, WriteableTable: WriteableTable }); init(); addons.forEach(function (fn) { fn(db); }); } var fakeAutoComplete = function () {}; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) function parseType(type) { if (typeof type === 'function') { return new type(); } else if (isArray(type)) { return [parseType(type[0])]; } else if (type && typeof type === 'object') { var rv = {}; applyStructure(rv, type); return rv; } else { return type; } } function applyStructure(obj, structure) { keys(structure).forEach(function (member) { var value = parseType(structure[member]); obj[member] = value; }); return obj; } function eventSuccessHandler(done) { return function (ev) { done(ev.target.result); }; } function hookedEventSuccessHandler(resolve) { // wrap() is needed when calling hooks because the rare scenario of: // * hook does a db operation that fails immediately (IDB throws exception) // For calling db operations on correct transaction, wrap makes sure to set PSD correctly. // wrap() will also execute in a virtual tick. // * If not wrapped in a virtual tick, direct exception will launch a new physical tick. // * If this was the last event in the bulk, the promise will resolve after a physical tick // and the transaction will have committed already. // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise, // because it is always marked with _lib = true when created using Transaction._promise(). return wrap(function (event) { var req = event.target, result = req.result, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. hookSuccessHandler = ctx && ctx.onsuccess; hookSuccessHandler && hookSuccessHandler(result); resolve && resolve(result); }, resolve); } function eventRejectHandler(reject) { return function (event) { preventDefault(event); reject(event.target.error); return false; }; } function hookedEventRejectHandler(reject) { return wrap(function (event) { // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks. var req = event.target, err = req.error, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. hookErrorHandler = ctx && ctx.onerror; hookErrorHandler && hookErrorHandler(err); preventDefault(event); reject(err); return false; }); } function preventDefault(event) { if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below. event.stopPropagation(); if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below. event.preventDefault(); } function globalDatabaseList(cb) { var val, localStorage = Dexie.dependencies.localStorage; if (!localStorage) return cb([]); // Envs without localStorage support try { val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]"); } catch (e) { val = []; } if (cb(val)) { localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val)); } } function awaitIterator(iterator) { var callNext = function (result) { return iterator.next(result); }, doThrow = function (error) { return iterator.throw(error); }, onSuccess = step(callNext), onError = step(doThrow); function step(getNext) { return function (val) { var next = getNext(val), value = next.value; return next.done ? value : !value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError); }; } return step(callNext)(); } // // IndexSpec struct // function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) { /// <param name="name" type="String"></param> /// <param name="keyPath" type="String"></param> /// <param name="unique" type="Boolean"></param> /// <param name="multi" type="Boolean"></param> /// <param name="auto" type="Boolean"></param> /// <param name="compound" type="Boolean"></param> /// <param name="dotted" type="Boolean"></param> this.name = name; this.keyPath = keyPath; this.unique = unique; this.multi = multi; this.auto = auto; this.compound = compound; this.dotted = dotted; var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && '[' + [].join.call(keyPath, '+') + ']'; this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc; } // // TableSchema struct // function TableSchema(name, primKey, indexes, instanceTemplate) { /// <param name="name" type="String"></param> /// <param name="primKey" type="IndexSpec"></param> /// <param name="indexes" type="Array" elementType="IndexSpec"></param> /// <param name="instanceTemplate" type="Object"></param> this.name = name; this.primKey = primKey || new IndexSpec(); this.indexes = indexes || [new IndexSpec()]; this.instanceTemplate = instanceTemplate; this.mappedClass = null; this.idxByName = arrayToObject(indexes, function (index) { return [index.name, index]; }); } // Used in when defining dependencies later... // (If IndexedDBShim is loaded, prefer it before standard indexedDB) var idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {}; function safariMultiStoreFix(storeNames) { return storeNames.length === 1 ? storeNames[0] : storeNames; } function getNativeGetDatabaseNamesFn(indexedDB) { var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames); return fn && fn.bind(indexedDB); } // Export Error classes props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...}; // // Static methods and properties // props(Dexie, { // // Static delete() method. // delete: function (databaseName) { var db = new Dexie(databaseName), promise = db.delete(); promise.onblocked = function (fn) { db.on("blocked", fn); return this; }; return promise; }, // // Static exists() method. // exists: function (name) { return new Dexie(name).open().then(function (db) { db.close(); return true; }).catch(Dexie.NoSuchDatabaseError, function () { return false; }); }, // // Static method for retrieving a list of all existing databases at current host. // getDatabaseNames: function (cb) { return new Promise(function (resolve, reject) { var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB); if (getDatabaseNames) { // In case getDatabaseNames() becomes standard, let's prepare to support it: var req = getDatabaseNames(); req.onsuccess = function (event) { resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array<String> }; req.onerror = eventRejectHandler(reject); } else { globalDatabaseList(function (val) { resolve(val); return false; }); } }).then(cb); }, defineClass: function (structure) { /// <summary> /// Create a javascript constructor based on given template for which properties to expect in the class. /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}. /// </summary> /// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param> // Default constructor able to copy given properties into this object. function Class(properties) { /// <param name="properties" type="Object" optional="true">Properties to initialize object with. /// </param> properties ? extend(this, properties) : fake && applyStructure(this, structure); } return Class; }, applyStructure: applyStructure, ignoreTransaction: function (scopeFunc) { // In case caller is within a transaction but needs to create a separate transaction. // Example of usage: // // Let's say we have a logger function in our app. Other application-logic should be unaware of the // logger function and not need to include the 'logentries' table in all transaction it performs. // The logging should always be done in a separate transaction and not be dependant on the current // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction. // // Dexie.ignoreTransaction(function() { // db.logentries.add(newLogEntry); // }); // // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction // in current Promise-scope. // // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an // API for this because // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout(). // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate(). // 3) setImmediate() is not supported in the ES standard. // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough. return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional. scopeFunc(); // No need to change scope because there is no ongoing transaction. }, vip: function (fn) { // To be used by subscribers to the on('ready') event. // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing. // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that. // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip() // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by // the caller will not resolve until database is opened. return newScope(function () { PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing. return fn(); }); }, async: function (generatorFn) { return function () { try { var rv = awaitIterator(generatorFn.apply(this, arguments)); if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); return rv; } catch (e) { return rejection(e); } }; }, spawn: function (generatorFn, args, thiz) { try { var rv = awaitIterator(generatorFn.apply(thiz, args || [])); if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); return rv; } catch (e) { return rejection(e); } }, // Dexie.currentTransaction property currentTransaction: { get: function () { return PSD.trans || null; } }, // Export our Promise implementation since it can be handy as a standalone Promise implementation Promise: Promise, // Dexie.debug proptery: // Dexie.debug = false // Dexie.debug = true // Dexie.debug = "dexie" - don't hide dexie's stack frames. debug: { get: function () { return debug; }, set: function (value) { setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); } }, // Export our derive/extend/override methodology derive: derive, extend: extend, props: props, override: override, // Export our Events() function - can be handy as a toolkit Events: Events, events: { get: deprecated(function () { return Events; }) }, // Backward compatible lowercase version. // Utilities getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, asap: asap, maxKey: maxKey, // Addon registry addons: [], // Global DB connection list connections: connections, MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate. errnames: errnames, // Export other static classes IndexSpec: IndexSpec, TableSchema: TableSchema, // // Dependencies // // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included. // // In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). // For node.js, you need to require indexeddb-js or similar and then set these deps. // dependencies: { // Required: indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange }, // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc. semVer: DEXIE_VERSION, version: DEXIE_VERSION.split('.').map(function (n) { return parseInt(n); }).reduce(function (p, c, i) { return p + c / Math.pow(10, i * 2); }), fakeAutoComplete: fakeAutoComplete, // https://github.com/dfahlander/Dexie.js/issues/186 // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return // x.default. Workaround: Set Dexie.default = Dexie. default: Dexie }); tryCatch(function () { // Optional dependencies // localStorage Dexie.dependencies.localStorage = (typeof chrome !== "undefined" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage; }); // Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0. Promise.rejectionMapper = mapError; // Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015. doFakeAutoComplete(function () { Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete; Dexie.fake = fake = true; }); return Dexie; }))); //# sourceMappingURL=dexie.js.map
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("chart.js"),require("vue")):"function"==typeof define&&define.amd?define("VueChartJs",["chart.js","vue"],e):"object"==typeof exports?exports.VueChartJs=e(require("chart.js"),require("vue")):t.VueChartJs=e(t["chart.js"],t.vue)}(this,function(t,e){return function(t){function e(n){if(r[n])return r[n].exports;var a=r[n]={exports:{},id:n,loaded:!1};return t[n].call(a.exports,a,a.exports,e),a.loaded=!0,a.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.mixins=e.Scatter=e.Bubble=e.Radar=e.PolarArea=e.Pie=e.Line=e.Doughnut=e.HorizontalBar=e.Bar=e.VueCharts=void 0;var a=r(14),i=n(a),s=r(17),u=n(s),o=r(16),c=n(o),l=r(18),f=n(l),d=r(19),h=n(d),p=r(20),y=n(p),v=r(21),b=n(v),g=r(15),_=n(g),m=r(22),j=n(m),w=r(23),x=n(w),O=r(53),P=n(O),k={version:P.default.version,Bar:i.default,HorizontalBar:u.default,Doughnut:c.default,Line:f.default,Pie:h.default,PolarArea:y.default,Radar:b.default,Bubble:_.default,Scatter:j.default,mixins:x.default};e.default=k,e.VueCharts=k,e.Bar=i.default,e.HorizontalBar=u.default,e.Doughnut=c.default,e.Line=f.default,e.Pie=h.default,e.PolarArea=y.default,e.Radar=b.default,e.Bubble=_.default,e.Scatter=j.default,e.mixins=x.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function a(t,e){return(0,s.default)(t,e)}Object.defineProperty(e,"__esModule",{value:!0}),e.mergeOptions=a;var i=r(54),s=n(i)},function(e,r){e.exports=t},function(t,r){t.exports=e},function(t,e){var r=t.exports={version:"2.4.0"};"number"==typeof __e&&(__e=r)},function(t,e,r){t.exports=!r(6)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e){var r=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,r){t.exports={default:r(26),__esModule:!0}},function(t,e,r){t.exports={default:r(27),__esModule:!0}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e){var r=Math.ceil,n=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?n:r)(t)}},function(t,e,r){var n=r(39),a=r(11);t.exports=function(t){return n(a(t))}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"bar-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{scales:{yAxes:[{ticks:{beginAtZero:!0},gridLines:{display:!1}}],xAxes:[{gridLines:{display:!1},categoryPercentage:.5,barPercentage:.2}]}},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"bar",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"bubble-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{scales:{yAxes:[{ticks:{beginAtZero:!0},gridLines:{display:!1}}],xAxes:[{gridLines:{display:!1},categoryPercentage:.5,barPercentage:.2}]}},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"bubble",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"doughnut-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"doughnut",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"horizontalbar-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{scales:{yAxes:[{ticks:{beginAtZero:!0},gridLines:{display:!1}}],xAxes:[{gridLines:{display:!1},categoryPercentage:.5,barPercentage:.2}]}},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e,r){var n=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"horizontalBar",data:t,options:n,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"line-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{scales:{yAxes:[{ticks:{beginAtZero:!0},gridLines:{display:!1}}],xAxes:[{gridLines:{display:!1}}]}},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"line",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"pie-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"pie",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"polar-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"polarArea",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"radar-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"radar",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(3),i=n(a),s=r(2),u=n(s),o=r(1);e.default=i.default.extend({render:function(t){return t("div",{style:this.styles,class:this.cssClasses},[t("canvas",{attrs:{id:this.chartId,width:this.width,height:this.height},ref:"canvas"})])},props:{chartId:{default:"scatter-chart",type:String},width:{default:400,type:Number},height:{default:400,type:Number},cssClasses:{type:String,default:""},styles:{type:Object}},data:function(){return{defaultOptions:{scales:{xAxes:[{type:"linear",position:"bottom"}]}},plugins:[]}},methods:{addPlugin:function(t){this.plugins.push(t)},renderChart:function(t,e){var r=(0,o.mergeOptions)(this.defaultOptions,e);this._chart=new u.default(this.$refs.canvas.getContext("2d"),{type:"scatter",data:t,options:r,plugins:this.plugins})}},beforeDestroy:function(){this._chart&&this._chart.destroy()}})},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var a=r(24),i=n(a),s=r(25),u=n(s);e.default={reactiveData:i.default,reactiveProp:u.default}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var a=r(10),i=n(a),s=r(9),u=n(s);t.exports={data:function(){return{chartData:null}},watch:{chartData:{handler:function(t,e){if(e){var r=this._chart,n=t.datasets.map(function(t){return t.label}),a=e.datasets.map(function(t){return t.label}),s=(0,u.default)(a),o=(0,u.default)(n);o===s&&e.datasets.length===t.datasets.length?(t.datasets.forEach(function(t,n){var a=(0,i.default)(e.datasets[n]),s=(0,i.default)(t),u=a.filter(function(t){return"_meta"!==t&&s.indexOf(t)===-1});u.forEach(function(t){delete r.data.datasets[n][t]});for(var o in t)t.hasOwnProperty(o)&&(r.data.datasets[n][o]=t[o])}),t.hasOwnProperty("labels")&&(r.data.labels=t.labels),t.hasOwnProperty("xLabels")&&(r.data.xLabels=t.xLabels),t.hasOwnProperty("yLabels")&&(r.data.yLabels=t.yLabels),r.update()):(r.destroy(),this.renderChart(this.chartData,this.options))}else this.renderChart(this.chartData,this.options)}}}}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var a=r(10),i=n(a),s=r(9),u=n(s);t.exports={props:{chartData:{required:!0}},watch:{chartData:{handler:function(t,e){if(e){var r=this._chart,n=t.datasets.map(function(t){return t.label}),a=e.datasets.map(function(t){return t.label}),s=(0,u.default)(a),o=(0,u.default)(n);o===s&&e.datasets.length===t.datasets.length?(t.datasets.forEach(function(t,n){var a=(0,i.default)(e.datasets[n]),s=(0,i.default)(t),u=a.filter(function(t){return"_meta"!==t&&s.indexOf(t)===-1});u.forEach(function(t){delete r.data.datasets[n][t]});for(var o in t)t.hasOwnProperty(o)&&(r.data.datasets[n][o]=t[o])}),t.hasOwnProperty("labels")&&(r.data.labels=t.labels),t.hasOwnProperty("xLabels")&&(r.data.xLabels=t.xLabels),t.hasOwnProperty("yLabels")&&(r.data.yLabels=t.yLabels),r.update()):(r.destroy(),this.renderChart(this.chartData,this.options))}else this.renderChart(this.chartData,this.options)}}}}},function(t,e,r){var n=r(4),a=n.JSON||(n.JSON={stringify:JSON.stringify});t.exports=function(t){return a.stringify.apply(a,arguments)}},function(t,e,r){r(52),t.exports=r(4).Object.keys},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,r){var n=r(8);t.exports=function(t){if(!n(t))throw TypeError(t+" is not an object!");return t}},function(t,e,r){var n=r(13),a=r(48),i=r(47);t.exports=function(t){return function(e,r,s){var u,o=n(e),c=a(o.length),l=i(s,c);if(t&&r!=r){for(;c>l;)if(u=o[l++],u!=u)return!0}else for(;c>l;l++)if((t||l in o)&&o[l]===r)return t||l||0;return!t&&-1}}},function(t,e){var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,e,r){var n=r(28);t.exports=function(t,e,r){if(n(t),void 0===e)return t;switch(r){case 1:return function(r){return t.call(e,r)};case 2:return function(r,n){return t.call(e,r,n)};case 3:return function(r,n,a){return t.call(e,r,n,a)}}return function(){return t.apply(e,arguments)}}},function(t,e,r){var n=r(8),a=r(7).document,i=n(a)&&n(a.createElement);t.exports=function(t){return i?a.createElement(t):{}}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,r){var n=r(7),a=r(4),i=r(32),s=r(37),u="prototype",o=function(t,e,r){var c,l,f,d=t&o.F,h=t&o.G,p=t&o.S,y=t&o.P,v=t&o.B,b=t&o.W,g=h?a:a[e]||(a[e]={}),_=g[u],m=h?n:p?n[e]:(n[e]||{})[u];h&&(r=e);for(c in r)l=!d&&m&&void 0!==m[c],l&&c in g||(f=l?m[c]:r[c],g[c]=h&&"function"!=typeof m[c]?r[c]:v&&l?i(f,n):b&&m[c]==f?function(t){var e=function(e,r,n){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,r)}return new t(e,r,n)}return t.apply(this,arguments)};return e[u]=t[u],e}(f):y&&"function"==typeof f?i(Function.call,f):f,y&&((g.virtual||(g.virtual={}))[c]=f,t&o.R&&_&&!_[c]&&s(_,c,f)))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,o.U=64,o.R=128,t.exports=o},function(t,e){var r={}.hasOwnProperty;t.exports=function(t,e){return r.call(t,e)}},function(t,e,r){var n=r(40),a=r(44);t.exports=r(5)?function(t,e,r){return n.f(t,e,a(1,r))}:function(t,e,r){return t[e]=r,t}},function(t,e,r){t.exports=!r(5)&&!r(6)(function(){return 7!=Object.defineProperty(r(33)("div"),"a",{get:function(){return 7}}).a})},function(t,e,r){var n=r(31);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==n(t)?t.split(""):Object(t)}},function(t,e,r){var n=r(29),a=r(38),i=r(50),s=Object.defineProperty;e.f=r(5)?Object.defineProperty:function(t,e,r){if(n(t),e=i(e,!0),n(r),a)try{return s(t,e,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(t[e]=r.value),t}},function(t,e,r){var n=r(36),a=r(13),i=r(30)(!1),s=r(45)("IE_PROTO");t.exports=function(t,e){var r,u=a(t),o=0,c=[];for(r in u)r!=s&&n(u,r)&&c.push(r);for(;e.length>o;)n(u,r=e[o++])&&(~i(c,r)||c.push(r));return c}},function(t,e,r){var n=r(41),a=r(34);t.exports=Object.keys||function(t){return n(t,a)}},function(t,e,r){var n=r(35),a=r(4),i=r(6);t.exports=function(t,e){var r=(a.Object||{})[t]||Object[t],s={};s[t]=e(r),n(n.S+n.F*i(function(){r(1)}),"Object",s)}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,r){var n=r(46)("keys"),a=r(51);t.exports=function(t){return n[t]||(n[t]=a(t))}},function(t,e,r){var n=r(7),a="__core-js_shared__",i=n[a]||(n[a]={});t.exports=function(t){return i[t]||(i[t]={})}},function(t,e,r){var n=r(12),a=Math.max,i=Math.min;t.exports=function(t,e){return t=n(t),t<0?a(t+e,0):i(t,e)}},function(t,e,r){var n=r(12),a=Math.min;t.exports=function(t){return t>0?a(n(t),9007199254740991):0}},function(t,e,r){var n=r(11);t.exports=function(t){return Object(n(t))}},function(t,e,r){var n=r(8);t.exports=function(t,e){if(!n(t))return t;var r,a;if(e&&"function"==typeof(r=t.toString)&&!n(a=r.call(t)))return a;if("function"==typeof(r=t.valueOf)&&!n(a=r.call(t)))return a;if(!e&&"function"==typeof(r=t.toString)&&!n(a=r.call(t)))return a;throw TypeError("Can't convert object to primitive value")}},function(t,e){var r=0,n=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++r+n).toString(36))}},function(t,e,r){var n=r(49),a=r(42);r(43)("keys",function(){return function(t){return a(n(t))}})},function(t,e){t.exports={name:"vue-chartjs",version:"2.8.4",description:"vue.js wrapper for chart.js",author:"Jakub Juszczak <jakub@posteo.de>",homepage:"http://vue-chartjs.org",license:"MIT",contributors:[{name:"Thorsten Lünborg",web:"https://github.com/LinusBorg"},{name:"Juan Carlos Alonso",web:"https://github.com/jcalonso"}],maintainers:[{name:"Jakub Juszczak",email:"jakub@posteo.de",web:"http://www.jakubjuszczak.de"}],repository:{type:"git",url:"git+ssh://git@github.com:apertureless/vue-chartjs.git"},bugs:{url:"https://github.com/apertureless/vue-chartjs/issues"},keywords:["ChartJs","Vue","Visualisation","Wrapper","Charts"],main:"dist/vue-chartjs.js",unpkg:"dist/vue-chartjs.full.min.js",module:"es/index.js","jsnext:main":"es/index.js",files:["src","dist","es"],scripts:{dev:"node build/dev-server.js",build:"yarn run release && yarn run build:es","build:es":"cross-env BABEL_ENV=es babel src --out-dir es",unit:"karma start test/unit/karma.conf.js --single-run",e2e:"node test/e2e/runner.js",test:"npm run unit",lint:"eslint --ext .js,.vue src test/unit/specs test/e2e/specs",release:"webpack --progress --hide-modules --config ./build/webpack.release.js && NODE_ENV=production webpack --progress --hide-modules --config ./build/webpack.release.min.js && webpack --progress --hide-modules --config ./build/webpack.release.full.js && NODE_ENV=production webpack --progress --hide-modules --config ./build/webpack.release.full.min.js",prepublish:"yarn run lint && yarn run test && yarn run build"},dependencies:{"lodash.merge":"^4.6.0"},peerDependencies:{"chart.js":"^2.6.0",vue:"^2.4.2"},devDependencies:{"babel-cli":"^6.24.1","babel-core":"^6.25.0","babel-loader":"^7.0.0","babel-plugin-transform-object-assign":"^6.22.0","babel-plugin-transform-runtime":"^6.23.0","babel-preset-es2015":"^6.24.1","babel-preset-stage-2":"^6.24.1","babel-runtime":"^6.23.0",chai:"^3.5.0","chart.js":"^2.6.0",chromedriver:"^2.28.0","connect-history-api-fallback":"^1.1.0","cross-env":"^3.2.4","cross-spawn":"^5.1.0","css-loader":"^0.28.0",eslint:"^3.19.0","eslint-config-standard":"^10.2.1","eslint-friendly-formatter":"^2.0.7","eslint-loader":"^1.7.1","eslint-plugin-html":"^2.0.1","eslint-plugin-import":"^2.2.0","eslint-plugin-node":"^4.2.2","eslint-plugin-promise":"^3.5.0","eslint-plugin-standard":"^3.0.1","eventsource-polyfill":"^0.9.6",express:"^4.15.2","extract-text-webpack-plugin":"^1.0.1","file-loader":"^0.10.1","function-bind":"^1.0.2","html-webpack-plugin":"^2.28.0","http-proxy-middleware":"^0.17.4","inject-loader":"^3.0.0","isparta-loader":"^2.0.0","jasmine-core":"^2.5.2","json-loader":"^0.5.4",karma:"^1.5.0","karma-coverage":"^1.1.1","karma-jasmine":"^1.0.2","karma-mocha":"^1.2.0","karma-phantomjs-launcher":"^1.0.4","karma-sinon-chai":"^1.2.0","karma-sourcemap-loader":"^0.3.7","karma-spec-reporter":"0.0.30","karma-webpack":"1.8.1",lolex:"^1.6.0",mocha:"^3.1.0",nightwatch:"^0.9.14",ora:"^1.2.0","phantomjs-prebuilt":"^2.1.13","selenium-server":"^3.3.1",shelljs:"^0.7.7",sinon:"^2.1.0","sinon-chai":"^2.9.0","url-loader":"^0.5.8",vue:"^2.4.2","vue-hot-reload-api":"^2.1.0","vue-html-loader":"^1.2.4","vue-loader":"^12.2.2","vue-style-loader":"^3.0.1","vue-template-compiler":"^2.4.2",webpack:"^1.13.2","webpack-dev-middleware":"^1.10.1","webpack-hot-middleware":"^2.17.1","webpack-merge":"1.1.1"},engines:{node:">=6.9.0"},babel:{presets:["es2015"]},browserify:{transform:["babelify"]},greenkeeper:{ignore:["extract-text-webpack-plugin","karma-webpack","webpack","webpack-merge"]}}},function(t,e,r){(function(t,r){function n(t,e){return t.set(e[0],e[1]),t}function a(t,e){return t.add(e),t}function i(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function s(t,e){for(var r=-1,n=t?t.length:0;++r<n&&e(t[r],r,t)!==!1;);return t}function u(t,e){for(var r=-1,n=e.length,a=t.length;++r<n;)t[a+r]=e[r];return t}function o(t,e,r,n){var a=-1,i=t?t.length:0;for(n&&i&&(r=t[++a]);++a<i;)r=e(r,t[a],a,t);return r}function c(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}function l(t){return function(e){return t(e)}}function f(t,e){return null==t?void 0:t[e]}function d(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(t){}return e}function h(t){var e=-1,r=Array(t.size);return t.forEach(function(t,n){r[++e]=[n,t]}),r}function p(t,e){return function(r){return t(e(r))}}function y(t){var e=-1,r=Array(t.size);return t.forEach(function(t){r[++e]=t}),r}function v(t){var e=-1,r=t?t.length:0;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}function b(){this.__data__=ar?ar(null):{}}function g(t){return this.has(t)&&delete this.__data__[t]}function _(t){var e=this.__data__;if(ar){var r=e[t];return r===Ft?void 0:r}return ze.call(e,t)?e[t]:void 0}function m(t){var e=this.__data__;return ar?void 0!==e[t]:ze.call(e,t)}function j(t,e){var r=this.__data__;return r[t]=ar&&void 0===e?Ft:e,this}function w(t){var e=-1,r=t?t.length:0;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}function x(){this.__data__=[]}function O(t){var e=this.__data__,r=R(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():Ge.call(e,r,1),!0}function P(t){var e=this.__data__,r=R(e,t);return r<0?void 0:e[r][1]}function k(t){return R(this.__data__,t)>-1}function C(t,e){var r=this.__data__,n=R(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}function S(t){var e=-1,r=t?t.length:0;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}function A(){this.__data__={hash:new v,map:new(tr||w),string:new v}}function M(t){return yt(this,t).delete(t)}function I(t){return yt(this,t).get(t)}function L(t){return yt(this,t).has(t)}function N(t,e){return yt(this,t).set(t,e),this}function D(t){this.__data__=new w(t)}function E(){this.__data__=new w}function B(t){return this.__data__.delete(t)}function $(t){return this.__data__.get(t)}function z(t){return this.__data__.has(t)}function J(t,e){var r=this.__data__;if(r instanceof w){var n=r.__data__;if(!tr||n.length<Vt-1)return n.push([t,e]),this;r=this.__data__=new S(n)}return r.set(t,e),this}function T(t,e){var r=pr(t)||St(t)?c(t.length,String):[],n=r.length,a=!!n;for(var i in t)!e&&!ze.call(t,i)||a&&("length"==i||mt(i,n))||r.push(i);return r}function V(t,e,r){(void 0===r||Ct(t[e],r))&&("number"!=typeof e||void 0!==r||e in t)||(t[e]=r)}function F(t,e,r){var n=t[e];ze.call(t,e)&&Ct(n,r)&&(void 0!==r||e in t)||(t[e]=r)}function R(t,e){for(var r=t.length;r--;)if(Ct(t[r][0],e))return r;return-1}function U(t,e){return t&&ft(e,$t(e),t)}function q(t,e,r,n,a,i,u){var o;if(n&&(o=i?n(t,a,i,u):n(t)),void 0!==o)return o;if(!Nt(t))return t;var c=pr(t);if(c){if(o=bt(t),!e)return lt(t,o)}else{var l=hr(t),f=l==Ht||l==Kt;if(yr(t))return rt(t,e);if(l==Yt||l==Ut||f&&!i){if(d(t))return i?t:{};if(o=gt(f?{}:t),!e)return dt(t,U(o,t))}else{if(!we[l])return i?t:{};o=_t(t,l,q,e)}}u||(u=new D);var h=u.get(t);if(h)return h;if(u.set(t,o),!c)var p=r?pt(t):$t(t);return s(p||t,function(a,i){p&&(i=a,a=t[i]),F(o,i,q(a,e,r,n,i,t,u))}),o}function W(t){return Nt(t)?We(t):{}}function Z(t,e,r){var n=e(t);return pr(t)?n:u(n,r(t))}function G(t){return Te.call(t)}function H(t){if(!Nt(t)||xt(t))return!1;var e=It(t)||d(t)?Ve:_e;return e.test(kt(t))}function K(t){return Dt(t)&&Lt(t.length)&&!!je[Te.call(t)]}function Q(t){if(!Ot(t))return Qe(t);var e=[];for(var r in Object(t))ze.call(t,r)&&"constructor"!=r&&e.push(r);return e}function X(t){if(!Nt(t))return Pt(t);var e=Ot(t),r=[];for(var n in t)("constructor"!=n||!e&&ze.call(t,n))&&r.push(n);return r}function Y(t,e,r,n,a){if(t!==e){if(!pr(e)&&!vr(e))var i=X(e);s(i||e,function(s,u){if(i&&(u=s,s=e[u]),Nt(s))a||(a=new D),tt(t,e,u,r,Y,n,a);else{var o=n?n(t[u],s,u+"",t,e,a):void 0;void 0===o&&(o=s),V(t,u,o)}})}}function tt(t,e,r,n,a,i,s){var u=t[r],o=e[r],c=s.get(o);if(c)return void V(t,r,c);var l=i?i(u,o,r+"",t,e,s):void 0,f=void 0===l;f&&(l=o,pr(o)||vr(o)?pr(u)?l=u:Mt(u)?l=lt(u):(f=!1,l=q(o,!0)):Et(o)||St(o)?St(u)?l=Bt(u):!Nt(u)||n&&It(u)?(f=!1,l=q(o,!0)):l=u:f=!1),f&&(s.set(o,l),a(l,o,n,i,s),s.delete(o)),V(t,r,l)}function et(t,e){return e=Xe(void 0===e?t.length-1:e,0),function(){for(var r=arguments,n=-1,a=Xe(r.length-e,0),s=Array(a);++n<a;)s[n]=r[e+n];n=-1;for(var u=Array(e+1);++n<e;)u[n]=r[n];return u[e]=s,i(t,this,u)}}function rt(t,e){if(e)return t.slice();var r=new t.constructor(t.length);return t.copy(r),r}function nt(t){var e=new t.constructor(t.byteLength);return new Ue(e).set(new Ue(t)),e}function at(t,e){var r=e?nt(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}function it(t,e,r){var a=e?r(h(t),!0):h(t);return o(a,n,new t.constructor)}function st(t){var e=new t.constructor(t.source,ge.exec(t));return e.lastIndex=t.lastIndex,e}function ut(t,e,r){var n=e?r(y(t),!0):y(t);return o(n,a,new t.constructor)}function ot(t){return fr?Object(fr.call(t)):{}}function ct(t,e){var r=e?nt(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}function lt(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function ft(t,e,r,n){r||(r={});for(var a=-1,i=e.length;++a<i;){var s=e[a],u=n?n(r[s],t[s],s,r,t):void 0;F(r,s,void 0===u?t[s]:u)}return r}function dt(t,e){return ft(t,dr(t),e)}function ht(t){return et(function(e,r){var n=-1,a=r.length,i=a>1?r[a-1]:void 0,s=a>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(a--,i):void 0,s&&jt(r[0],r[1],s)&&(i=a<3?void 0:i,a=1),e=Object(e);++n<a;){var u=r[n];u&&t(e,u,n,i)}return e})}function pt(t){return Z(t,$t,dr)}function yt(t,e){var r=t.__data__;return wt(e)?r["string"==typeof e?"string":"hash"]:r.map}function vt(t,e){var r=f(t,e);return H(r)?r:void 0}function bt(t){var e=t.length,r=t.constructor(e);return e&&"string"==typeof t[0]&&ze.call(t,"index")&&(r.index=t.index,r.input=t.input),r}function gt(t){return"function"!=typeof t.constructor||Ot(t)?{}:W(qe(t))}function _t(t,e,r,n){var a=t.constructor;switch(e){case se:return nt(t);case Wt:case Zt:return new a(+t);case ue:return at(t,n);case oe:case ce:case le:case fe:case de:case he:case pe:case ye:case ve:return ct(t,n);case Qt:return it(t,n,r);case Xt:case ne:return new a(t);case ee:return st(t);case re:return ut(t,n,r);case ae:return ot(t)}}function mt(t,e){return e=null==e?Rt:e,!!e&&("number"==typeof t||me.test(t))&&t>-1&&t%1==0&&t<e}function jt(t,e,r){if(!Nt(r))return!1;var n=typeof e;return!!("number"==n?At(r)&&mt(e,r.length):"string"==n&&e in r)&&Ct(r[e],t)}function wt(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}function xt(t){return!!Be&&Be in t}function Ot(t){var e=t&&t.constructor,r="function"==typeof e&&e.prototype||De;return t===r}function Pt(t){var e=[];if(null!=t)for(var r in Object(t))e.push(r);return e}function kt(t){if(null!=t){try{return $e.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Ct(t,e){return t===e||t!==t&&e!==e}function St(t){return Mt(t)&&ze.call(t,"callee")&&(!Ze.call(t,"callee")||Te.call(t)==Ut)}function At(t){return null!=t&&Lt(t.length)&&!It(t)}function Mt(t){return Dt(t)&&At(t)}function It(t){var e=Nt(t)?Te.call(t):"";return e==Ht||e==Kt}function Lt(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=Rt}function Nt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Dt(t){return!!t&&"object"==typeof t}function Et(t){if(!Dt(t)||Te.call(t)!=Yt||d(t))return!1;var e=qe(t);if(null===e)return!0;var r=ze.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&$e.call(r)==Je}function Bt(t){return ft(t,zt(t))}function $t(t){return At(t)?T(t):Q(t)}function zt(t){return At(t)?T(t,!0):X(t)}function Jt(){return[]}function Tt(){return!1}var Vt=200,Ft="__lodash_hash_undefined__",Rt=9007199254740991,Ut="[object Arguments]",qt="[object Array]",Wt="[object Boolean]",Zt="[object Date]",Gt="[object Error]",Ht="[object Function]",Kt="[object GeneratorFunction]",Qt="[object Map]",Xt="[object Number]",Yt="[object Object]",te="[object Promise]",ee="[object RegExp]",re="[object Set]",ne="[object String]",ae="[object Symbol]",ie="[object WeakMap]",se="[object ArrayBuffer]",ue="[object DataView]",oe="[object Float32Array]",ce="[object Float64Array]",le="[object Int8Array]",fe="[object Int16Array]",de="[object Int32Array]",he="[object Uint8Array]",pe="[object Uint8ClampedArray]",ye="[object Uint16Array]",ve="[object Uint32Array]",be=/[\\^$.*+?()[\]{}|]/g,ge=/\w*$/,_e=/^\[object .+?Constructor\]$/,me=/^(?:0|[1-9]\d*)$/,je={};je[oe]=je[ce]=je[le]=je[fe]=je[de]=je[he]=je[pe]=je[ye]=je[ve]=!0,je[Ut]=je[qt]=je[se]=je[Wt]=je[ue]=je[Zt]=je[Gt]=je[Ht]=je[Qt]=je[Xt]=je[Yt]=je[ee]=je[re]=je[ne]=je[ie]=!1;var we={};we[Ut]=we[qt]=we[se]=we[ue]=we[Wt]=we[Zt]=we[oe]=we[ce]=we[le]=we[fe]=we[de]=we[Qt]=we[Xt]=we[Yt]=we[ee]=we[re]=we[ne]=we[ae]=we[he]=we[pe]=we[ye]=we[ve]=!0,we[Gt]=we[Ht]=we[ie]=!1;var xe="object"==typeof t&&t&&t.Object===Object&&t,Oe="object"==typeof self&&self&&self.Object===Object&&self,Pe=xe||Oe||Function("return this")(),ke="object"==typeof e&&e&&!e.nodeType&&e,Ce=ke&&"object"==typeof r&&r&&!r.nodeType&&r,Se=Ce&&Ce.exports===ke,Ae=Se&&xe.process,Me=function(){try{return Ae&&Ae.binding("util")}catch(t){}}(),Ie=Me&&Me.isTypedArray,Le=Array.prototype,Ne=Function.prototype,De=Object.prototype,Ee=Pe["__core-js_shared__"],Be=function(){var t=/[^.]+$/.exec(Ee&&Ee.keys&&Ee.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),$e=Ne.toString,ze=De.hasOwnProperty,Je=$e.call(Object),Te=De.toString,Ve=RegExp("^"+$e.call(ze).replace(be,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Fe=Se?Pe.Buffer:void 0,Re=Pe.Symbol,Ue=Pe.Uint8Array,qe=p(Object.getPrototypeOf,Object),We=Object.create,Ze=De.propertyIsEnumerable,Ge=Le.splice,He=Object.getOwnPropertySymbols,Ke=Fe?Fe.isBuffer:void 0,Qe=p(Object.keys,Object),Xe=Math.max,Ye=vt(Pe,"DataView"),tr=vt(Pe,"Map"),er=vt(Pe,"Promise"),rr=vt(Pe,"Set"),nr=vt(Pe,"WeakMap"),ar=vt(Object,"create"),ir=kt(Ye),sr=kt(tr),ur=kt(er),or=kt(rr),cr=kt(nr),lr=Re?Re.prototype:void 0,fr=lr?lr.valueOf:void 0;v.prototype.clear=b,v.prototype.delete=g,v.prototype.get=_,v.prototype.has=m,v.prototype.set=j,w.prototype.clear=x,w.prototype.delete=O,w.prototype.get=P,w.prototype.has=k,w.prototype.set=C,S.prototype.clear=A,S.prototype.delete=M,S.prototype.get=I, S.prototype.has=L,S.prototype.set=N,D.prototype.clear=E,D.prototype.delete=B,D.prototype.get=$,D.prototype.has=z,D.prototype.set=J;var dr=He?p(He,Object):Jt,hr=G;(Ye&&hr(new Ye(new ArrayBuffer(1)))!=ue||tr&&hr(new tr)!=Qt||er&&hr(er.resolve())!=te||rr&&hr(new rr)!=re||nr&&hr(new nr)!=ie)&&(hr=function(t){var e=Te.call(t),r=e==Yt?t.constructor:void 0,n=r?kt(r):void 0;if(n)switch(n){case ir:return ue;case sr:return Qt;case ur:return te;case or:return re;case cr:return ie}return e});var pr=Array.isArray,yr=Ke||Tt,vr=Ie?l(Ie):K,br=ht(function(t,e,r){Y(t,e,r)});r.exports=br}).call(e,function(){return this}(),r(55)(t))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children=[],t.webpackPolyfill=1),t}}])});
// ** Handlebars helpers ** Template.registerHelper('eachWithRank', function(items, options) { // not used, forces multiple renders // note: cannot use this because it would delete and recreate all nodes items.rewind(); var out = ''; items.forEach(function(item, i){ var key = 'Branch-' + i; out = out + Spark.labelBranch(key,function(){ return options.fn(_.extend(item, {rank: i})); }); }); return out; }); Template.registerHelper('isLoggedIn', function() { return !!Meteor.user(); }); Template.registerHelper('canView', function() { return Users.can.view(Meteor.user()); }); Template.registerHelper('canPost', function() { return Users.can.post(Meteor.user()); }); Template.registerHelper('canComment', function() { return Users.can.comment(Meteor.user()); }); Template.registerHelper('isAdmin', function(user) { var user = typeof user === "undefined" ? Meteor.user() : user; if (Users.is.admin(Meteor.user())) { return true; } return false; }); Template.registerHelper('canEdit', function(item) { return Users.can.edit(Meteor.user(), item, false); }); Template.registerHelper('log', function(context){ console.log(context); }); Template.registerHelper('formatDate', function(datetime, format) { Session.get('momentLocale'); // depend on session variable to reactively rerun the helper return moment(datetime).format(format); }); Template.registerHelper('timeAgo', function(datetime) { Session.get('momentLocale'); // depend on session variable to reactively rerun the helper return moment(datetime).fromNow(); }); Template.registerHelper('sanitize', function(content) { console.log('cleaning up…'); console.log(content); return Telescope.utils.cleanUp(content); }); Template.registerHelper('pluralize', function(count, string) { string = count === 1 ? string : string + 's'; return i18n.t(string); }); Template.registerHelper('getProfileUrl', function(userOrUserId) { var user = (typeof userOrUserId === 'string') ? Meteor.users.findOne(userOrUserId) : userOrUserId; if (!!user) { return Users.getProfileUrl(user); } }); Template.registerHelper('getUsername', function(userOrUserId) { var user = (typeof userOrUserId === 'string') ? Meteor.users.findOne(userOrUserId) : userOrUserId; if (!!user) { return Users.getUserName(user); } }); Template.registerHelper('getDisplayName', function(userOrUserId) { var user = (typeof userOrUserId === 'string') ? Meteor.users.findOne(userOrUserId) : userOrUserId; if (!!user) { return Users.getDisplayName(user); } }); Template.registerHelper('icon', function(iconName, iconClass) { return Telescope.utils.getIcon(iconName, iconClass); }); Template.registerHelper('moduleClass', function() { // to get the module class from within a module, we go back up // four steps to access the zone data var zoneData = Template.parentData(4); if (zoneData) { // node: modules may not always be included from within a zone var moduleClass = zoneData.zone + "-module "; if (zoneData.moduleClass) { moduleClass += zoneData.moduleClass; } return moduleClass; } });
import React from 'react' import { Container } from 'shared' const Customize = () => <Container> <h1>Customize</h1> </Container> export default Customize
/** @jsx React.DOM */ Reactable = (function() { "use strict"; // Array.prototype.map polyfill - see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisArg */) { "use strict"; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } var res = new Array(len); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { // NOTE: Absolute correctness would demand Object.defineProperty // be used. But this method is fairly new, and failure is // possible only if Object.prototype or Array.prototype // has a property |i| (very unlikely), so use a less-correct // but more portable alternative. if (i in t) { res[i] = fun.call(thisArg, t[i], i, t); } } return res; }; } // Array.prototype.indexOf polyfill for IE8 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) { from += len; } for (; from < len; from++) { if (from in this && this[from] === elt) { return from; } } return -1; }; } // Array.prototype.find polyfill - see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find if (!Array.prototype.find) { Object.defineProperty(Array.prototype, 'find', { enumerable: false, configurable: true, writable: true, value: function(predicate) { if (this == null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { if (i in list) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } } return undefined; } }); } if (!Array.isArray) { Array.isArray = function (value) { return Object.prototype.toString.call(value) === '[object Array]'; }; } var Reactable = {}; function Unsafe(content) { this.content = content; } Unsafe.prototype.toString = function() { return this.content; } Reactable.unsafe = function(str) { return new Unsafe(str); } Reactable.Sort = { Numeric: function(a, b) { var valA = parseFloat(a.toString().replace(',', '')); var valB = parseFloat(b.toString().replace(',', '')); // Sort non-numeric values alphabetically at the bottom of the list if (isNaN(valA) && isNaN(valB)) { valA = a; valB = b; } else { if (isNaN(valA)) { return 1; } if (isNaN(valB)) { return -1; } } if (valA < valB) { return -1; } if (valA > valB) { return 1; } return 0; }, Currency: function(a, b) { // Parse out dollar signs, then do a regular numeric sort // TODO: handle non-American currency if (a[0] === '$') { a = a.substring(1); } if (b[0] === '$') { b = b.substring(1); } return Reactable.Sort.Numeric(a, b); }, Date: function(a, b) { // Note: this function tries to do a standard javascript string -> date conversion // If you need more control over the date string format, consider using a different // date library and writing your own function var valA = Date.parse(a); var valB = Date.parse(b); // Handle non-date values with numeric sort // Sort non-numeric values alphabetically at the bottom of the list if (isNaN(valA) || isNaN(valB)) { return Reactable.Sort.Numeric(a, b); } if (valA > valB) { return 1; } if (valB > valA) { return -1; } return 0; }, CaseInsensitive: function(a, b) { var valA = a.toLowerCase(); var valB = b.toLowerCase(); if(valA > valB) { return 1; } if(valB > valA) { return -1; } return 0; }, }; var Td = Reactable.Td = React.createClass({displayName: 'Td', handleClick: function(e){ if (typeof this.props.handleClick !== 'undefined') { return this.props.handleClick(e, this); } }, getDefaultProps: function() { var props = this.props; if ( typeof(props.data) === 'undefined' && typeof(this.props.children) === 'string' ) { props.data = this.props.children; } // Attach any properties on the column to this Td object to allow things like custom event handlers for (var key in this.props.column) { if (key !== 'key' && key !== 'name') { props[key] = this.props.column[key]; } } return props; }, render: function() { if (typeof(this.props.children) !== 'undefined') { if (this.props.children instanceof Unsafe) { return this.transferPropsTo( React.DOM.td( {'data-column':this.props.column.key, className:this.props.className, onClick:this.handleClick, dangerouslySetInnerHTML:{ __html: this.props.children.toString() } } ) ); } else { return this.transferPropsTo( React.DOM.td( {'data-column':this.props.column.key, className:this.props.className, onClick:this.handleClick}, this.props.children ) ); } } else { return this.transferPropsTo(React.DOM.td(null)); } } }); var Tr = Reactable.Tr = React.createClass({displayName: 'Tr', statics: { childNode: Td, dataType: 'object' }, getDefaultProps: function() { var defaultProps = { childNode: Td, columns: [], data: {} } return defaultProps; }, render: function() { var children = this.props.children || []; if ( this.props.data && this.props.columns && typeof this.props.columns.map === 'function' ) { children = children.concat(this.props.columns.map(function(column, i) { if (this.props.data.hasOwnProperty(column.key)) { return Td( {column:column, key:column.key}, this.props.data[column.key]); } else { return Td( {column:column, key:column.key} ); } }.bind(this))); } return this.transferPropsTo( React.DOM.tr(null, children) ); } }); var Thead = Reactable.Thead = React.createClass({displayName: 'Thead', getColumns: function() { return React.Children.map(this.props.children, function(th) { if (typeof th.props.children === 'string') { return th.props.children; } else { throw new TypeError('<th> must have a string child'); } }); }, render: function() { return this.transferPropsTo( React.DOM.thead(null, this.props.filtering === true ? Filterer( {colSpan:this.props.columns.length, onFilter:this.props.onFilter}) : '', React.DOM.tr( {className:"reactable-column-header"}, this.props.columns.map(function(column, index) { var sortClass = ''; if (this.props.sort.column === column.key) { sortClass = 'reactable-header-sort'; if (this.props.sort.direction === 1) { sortClass += '-asc'; } else { sortClass += '-desc'; } } return ( React.DOM.th( {className:sortClass, key:index, onClick:function(){ this.props.onSort(column.key) }.bind(this)}, column.label) ); }.bind(this)) ) ) ); } }); var Th = Reactable.Th = React.createClass({displayName: 'Th', render: function() { return this.transferPropsTo(React.DOM.th(null, this.props.children)); } }); var FiltererInput = React.createClass({displayName: 'FiltererInput', render: function() { return ( React.DOM.input( {type:"text", className:"reactable-filter-input", onKeyUp:function(){ this.props.onFilter(this.getDOMNode().value); }.bind(this)} ) ); }, }); var Filterer = React.createClass({displayName: 'Filterer', render: function() { if (typeof this.props.colSpan === 'undefined') { throw new TypeError('Must pass a colSpan argument to Filterer'); } return ( React.DOM.tr( {className:"reactable-filterer"}, React.DOM.td( {colSpan:this.props.colSpan}, FiltererInput( {onFilter:this.props.onFilter}) ) ) ); }, }); var Paginator = React.createClass({displayName: 'Paginator', render: function() { if (typeof this.props.colSpan === 'undefined') { throw new TypeError('Must pass a colSpan argument to Paginator'); } if (typeof this.props.numPages === 'undefined') { throw new TypeError('Must pass a non-zero numPages argument to Paginator'); } if (typeof this.props.currentPage === 'undefined') { throw new TypeError('Must pass a currentPage argument to Paginator'); } var pageButtons = []; for (var i = 0; i < this.props.numPages; i++) { var pageNum = i; var className = "reactable-page-button"; if (this.props.currentPage === i) { className += " reactable-current-page"; } pageButtons.push( React.DOM.a( {className:className, key:i, // create function to get around for-loop closure issue onClick:(function(pageNum) { return function() { this.props.onPageChange(pageNum); }.bind(this) }.bind(this))(i)}, i + 1) ); } return ( React.DOM.tbody( {className:"reactable-pagination"}, React.DOM.tr(null, React.DOM.td( {colSpan:this.props.colSpan}, pageButtons ) ) ) ); } }); var Table = Reactable.Table = React.createClass({displayName: 'Table', // Translate a user defined column array to hold column objects if strings are specified // (e.g. ['column1'] => [{key: 'column1', label: 'column1'}]) translateColumnsArray: function(columns) { return columns.map(function(column, i) { if (typeof(column) === 'string') { return { key: column, label: column }; } else { return column; } }); }, parseChildData: function() { var data = []; // Transform any children back to a data array if (typeof(this.props.children) !== 'undefined') { React.Children.forEach(this.props.children, function(child) { if (child.type.ConvenienceConstructor !== Tr) { return; // (continue) } var childData = child.props.data || {}; // Given our modification of Array.prototype, this is the // best way to check if child.props.children is an array if ( typeof(child.props.children) !== 'undefined' && typeof(child.props.children.map) === 'function' ) { var childChildren = child.props.children; for (var i = 0; i < childChildren.length; i++) { var descendant = childChildren[i]; if (descendant.type.ConvenienceConstructor === Td) { if (typeof(descendant.props.column) !== 'undefined') { if (typeof(descendant.props.data) !== 'undefined') { childData[descendant.props.column] = descendant.props.data; } else if ( typeof(descendant.props.children) !== 'undefined' ) { childData[descendant.props.column] = descendant.props.children; } else { console.warn('Reactable.Td specified without ' + 'a `data` property or children, ' + 'ignoring'); } } else { console.warn('Reactable.Td specified without a ' + '`column` property, ignoring'); } } } } data.push(childData); }.bind(this)); } return data; }, getDefaultProps: function() { var data = this.props.data || []; var defaultProps = { data: data.concat(this.parseChildData()), columns: [], sortable: [], filterable: [], defaultSort: false, itemsPerPage: 0, _sortable: [], } // Transform sortable properties into a more friendly list for (var i in this.props.sortable) { var column = this.props.sortable[i]; var columnName, sortFunction; if (column instanceof Object) { if (typeof(column.column) !== 'undefined') { columnName = column.column; } else { console.warn('Sortable column specified without column name'); return; } if (typeof(column.sortFunction) !== 'undefined' && column.sortFunction instanceof Function) { sortFunction = column.sortFunction; } else { sortFunction = 'default'; } } else { columnName = column; sortFunction = 'default'; } defaultProps._sortable[columnName] = sortFunction; } return defaultProps; }, getInitialState: function() { var initialState = { currentPage: 0, currentSort: { column: null, direction: 1, }, filter: '', } // Set the state of the current sort to the default sort if (this.props.defaultSort !== false) { var column = this.props.defaultSort; var currentSort = {}; if (column instanceof Object) { var columnName, sortDirection; if (typeof(column.column) !== 'undefined') { columnName = column.column; } else { console.warn('Default column specified without column name'); return; } if (typeof(column.direction) !== 'undefined') { if (column.direction === 1 || column.direction === 'asc') { sortDirection = 1; } else if (column.direction === -1 || column.direction === 'desc') { sortDirection = -1; } else { console.warn('Invalid default sort specified. Defaulting to ascending'); sortDirection = 1; } } else { sortFunction = 1; } } else { columnName = column; sortDirection = 1; } initialState.currentSort = { column: columnName, direction: sortDirection }; } return initialState; }, componentWillMount: function(){ this.sortByCurrentSort(); }, onPageChange: function(page) { this.setState({ currentPage: page }); }, onFilter: function(filter) { this.setState({ filter: filter }); }, applyFilter: function(filter, children) { // Helper function to apply filter text to a list of table rows var filter = filter.toLowerCase(); var matchedChildren = []; for (var i = 0; i < children.length; i++) { var data = children[i].props.data; for (var j = 0; j < this.props.filterable.length; j++) { var filterColumn = this.props.filterable[j]; if (data[filterColumn].toString().toLowerCase().indexOf(filter) > -1) { matchedChildren.push(children[i]); break; } } } return matchedChildren; }, sortByCurrentSort: function(){ // Apply a sort function according to the current sort in the state. // This allows us to perform a default sort even on a non sortable column. var currentSort = this.state.currentSort; if (currentSort.column === null) { return; } this.props.data.sort(function(a, b){ var keyA = a[currentSort.column]; var keyB = b[currentSort.column]; // Default sort if (this.props._sortable[currentSort.column] === 'default') { // Reverse direction if we're doing a reverse sort if (keyA < keyB) { return -1 * currentSort.direction; } if (keyA > keyB) { return 1 * currentSort.direction; } return 0; } else{ // Reverse columns if we're doing a reverse sort if (currentSort.direction === 1) { return this.props._sortable[currentSort.column](keyA, keyB); } else { return this.props._sortable[currentSort.column](keyB, keyA); } } }.bind(this)); }, onSort: function(column){ // Don't perform sort on unsortable columns if (typeof(this.props._sortable[column]) === 'undefined') { return; } var currentSort = this.state.currentSort; if (currentSort.column === column) { currentSort.direction *= -1; } else { currentSort.column = column; currentSort.direction = 1; } // Set the current sort and pass it to the sort function this.setState({ currentSort: currentSort }); this.sortByCurrentSort(); }, render: function() { // Test if the caller passed in data var children = []; var columns; var userColumnsSpecified = false; if ( this.props.children && this.props.children.length > 0 && this.props.children[0].type.ConvenienceConstructor === Thead ) { columns = this.props.children[0].getColumns(); } else { columns = this.props.columns || []; } if (columns.length > 0) { userColumnsSpecified = true; columns = this.translateColumnsArray(columns); } // Build up table rows if (this.props.data && typeof this.props.data.map === 'function') { // Build up the columns array children = children.concat(this.props.data.map(function(data, i) { // Loop through the keys in each data row and build a td for it for (var k in data) { if (data.hasOwnProperty(k)) { // Update the columns array with the data's keys if columns were not already specified if (userColumnsSpecified === false) { var column = { key: k, label: k }; // Only add a new column if it doesn't already exist in the columns array if (columns.find(function(element){return element.key === column.key}) === undefined) { columns.push(column); } } } } return ( Tr( {columns:columns, key:i, data:data} ) ); }.bind(this))); } if (this.props.sortable === true) { for (var i = 0; i < columns.length; i++) { this.props._sortable[columns[i].key] = 'default'; } } // Determine if we render the filter box var filtering = false; if (this.props.filterable && Array.isArray(this.props.filterable) && this.props.filterable.length > 0) { filtering = true; } // Apply filters var filteredChildren = children; if (this.state.filter !== '') { filteredChildren = this.applyFilter(this.state.filter, filteredChildren); } // Determine pagination properties and which columns to display var itemsPerPage = 0; var pagination = false; var currentChildren = filteredChildren; if (this.props.itemsPerPage > 0) { itemsPerPage = this.props.itemsPerPage; pagination = true; currentChildren = filteredChildren.slice( this.state.currentPage * itemsPerPage, (this.state.currentPage + 1) * itemsPerPage); } return this.transferPropsTo( React.DOM.table(null, columns && columns.length > 0 ? Thead( {columns:columns, filtering:filtering, onFilter:this.onFilter, sort:this.state.currentSort, onSort:this.onSort} ) : '', React.DOM.tbody( {className:"reactable-data"}, currentChildren ), pagination === true ? Paginator( {colSpan:columns.length, numPages:Math.ceil(filteredChildren.length / itemsPerPage), currentPage:this.state.currentPage, onPageChange:this.onPageChange}) : '' ) ); } }); return Reactable; }());
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = remove; // weak function isInside(scope, regex) { if (!scope.hub.file.opts) { return true; } var filename = scope.hub.file.opts.filename; if (!filename) { return true; } return filename.match(regex) !== null; } // Remove a specific path. function remove(path, globalOptions, options) { var visitedKey = globalOptions.visitedKey, wrapperIfTemplate = globalOptions.wrapperIfTemplate, mode = globalOptions.mode, ignoreFilenames = globalOptions.ignoreFilenames, types = globalOptions.types; if (ignoreFilenames && isInside(path.scope, ignoreFilenames)) { return; } if (mode === 'remove') { // remove() crash in some conditions. if (path.parentPath.type === 'ConditionalExpression') { path.replaceWith(types.unaryExpression('void', types.numericLiteral(0))); } else { path.remove(); } } else if (mode === 'wrap') { // Prevent infinity loop. if (path.node[visitedKey]) { return; } path.node[visitedKey] = true; switch (options.type) { // This is legacy, we do not optimize it. case 'createClass': break; // Inspired from babel-plugin-transform-class-properties. case 'class static': { var ref = void 0; var pathClassDeclaration = options.pathClassDeclaration; if (!pathClassDeclaration.isClassExpression() && pathClassDeclaration.node.id) { ref = pathClassDeclaration.node.id; } else { // Class without name not supported return; } var node = types.expressionStatement(types.assignmentExpression('=', types.memberExpression(ref, path.node.key), path.node.value)); // We need to append the node at the parent level in this case. if (pathClassDeclaration.parentPath.isExportDeclaration()) { pathClassDeclaration = pathClassDeclaration.parentPath; } pathClassDeclaration.insertAfter(node); path.remove(); break; } case 'class assign': case 'stateless': path.replaceWith(wrapperIfTemplate({ NODE: path.node })); break; default: break; } } else { throw new Error('transform-react-remove-prop-type: unsupported mode ' + mode + '.'); } }
(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":4,"../lib/Shim.IE8":25}],2:[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":24}],3:[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.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } 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()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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.isDropped()) { throw(this.logIdentifier() + ' 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.isDropped()) { throw(this.logIdentifier() + ' 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.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } 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, oldDoc, 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(this.logIdentifier() + ' 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], options, '', {})) { 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(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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], options, '', {})) { 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(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' 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], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' 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(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; 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.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } 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(self.logIdentifier() + ' 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); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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 this._subsetOf === collection; }; /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } 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.isDropped()) { throw(this.logIdentifier() + ' 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, options, '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) { // Don't 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); } op.time('tableScan: ' + scanLength); } // 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'); } 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(this.logIdentifier() + ' 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], options, '', {})) { // 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], options, '', {})) { // 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') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value return new Path(query.substr(3, query.length - 3)).value(item)[0]; } 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 = String(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, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } 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(this.logIdentifier() + ' $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, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * 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.isDropped()) { throw(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' 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":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":21,"./Path":22,"./ReactorIO":23,"./Shared":24}],4:[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'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // 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":6,"./Metrics.js":10,"./Overload":21,"./Shared":24}],5:[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 }; },{}],6:[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 = {}; }; Shared.addModule('Db', Db); 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'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * 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.isDropped()) { 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.isDropped()) { 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.isDropped()) { 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.isDropped()) { 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); this._db[name].mongoEmulation(this.mongoEmulation()); 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; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":21,"./Shared":24}],7:[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":2,"./Path":22,"./Shared":24}],8:[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":22,"./Shared":24}],9:[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":24}],10:[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":20,"./Shared":24}],11:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],12:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } 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.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } 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 }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // 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; },{}],13:[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; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":21}],14:[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; },{}],15:[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; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), 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, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.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 listenerIdArr = this._listeners[event]; 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++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; } }; module.exports = Events; },{"./Overload":21}],16:[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 {Object} queryOptions The options the query was passed 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, queryOptions, 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 || {}; queryOptions = queryOptions || {}; // 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 // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 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], queryOptions, 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], queryOptions, 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], queryOptions, 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], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, 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], queryOptions, 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], queryOptions, 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, queryOptions, 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], queryOptions, '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], queryOptions, '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(this.logIdentifier() + ' 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(this.logIdentifier() + ' 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; },{}],17:[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; },{}],18:[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":21}],19:[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(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * 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(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * 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 or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],20:[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":22,"./Shared":24}],21:[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; },{}],22:[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":24}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactoreOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur * @constructor */ 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); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { 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.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":24}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.300', modules: {}, plugins: {}, _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) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this 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]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } 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: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * 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: 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":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Triggers":18,"./Mixin.Updating":19,"./Overload":21}],25:[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 = {}; },{}]},{},[1]);
/*! instantsearch.js 1.2.1 | © Algolia Inc. and other contributors; Licensed MIT | github.com/algolia/instantsearch.js */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.instantsearch=t():e.instantsearch=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),i=r(o);e.exports=i["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),n(2);var o=n(3),i=r(o),a=n(4),s=r(a),u=n(96),l=r(u),c=(0,i["default"])(s["default"]);c.widgets={clearAll:n(217),currentRefinedValues:n(388),hierarchicalMenu:n(392),hits:n(395),hitsPerPageSelector:n(398),menu:n(403),refinementList:n(405),numericRefinementList:n(408),numericSelector:n(410),pagination:n(411),priceRanges:n(418),searchBox:n(423),rangeSlider:n(425),sortBySelector:n(429),starRating:n(430),stats:n(433),toggle:n(436)},c.version=n(215),c.createQueryString=l["default"].url.getQueryStringFromState,t["default"]=c,e.exports=t["default"]},function(e,t){"use strict";Object.freeze||(Object.freeze=function(e){if(Object(e)!==e)throw new TypeError("Object.freeze can only be called on Objects.");return e})},function(e,t){"use strict";function n(e){var t=function(){for(var t=arguments.length,n=Array(t),o=0;t>o;o++)n[o]=arguments[o];return new(r.apply(e,[null].concat(n)))};return t.__proto__=e,t.prototype=e.prototype,t}var r=Function.prototype.bind;e.exports=n},function(e,t,n){"use strict";function r(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 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 a(){return"#"}function s(e,t){if(!t.getConfiguration)return e;var n=t.getConfiguration(e);return(0,y["default"])({},e,n,function(e,t){return Array.isArray(e)?(0,_["default"])(e,t):void 0})}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},p=n(5),f=r(p),d=n(96),h=r(d),m=n(14),v=r(m),g=n(78),y=r(g),b=n(211),_=r(b),x=n(87),P=n(213),C=r(P),w=n(215),R=r(w),E=function(e){function t(e){var r=e.appId,i=void 0===r?null:r,a=e.apiKey,s=void 0===a?null:a,l=e.indexName,p=void 0===l?null:l,d=e.numberLocale,h=void 0===d?"en-EN":d,m=e.searchParameters,v=void 0===m?{}:m,g=e.urlSync,y=void 0===g?null:g;if(o(this,t),c(Object.getPrototypeOf(t.prototype),"constructor",this).call(this),null===i||null===s||null===p){var b="\nUsage: instantsearch({\n appId: 'my_application_id',\n apiKey: 'my_search_api_key',\n indexName: 'my_index_name'\n});";throw new Error(b)}var _=(0,f["default"])(i,s);_.addAlgoliaAgent("instantsearch.js "+R["default"]),this.client=_,this.helper=null,this.indexName=p,this.searchParameters=u({},v,{index:p}),this.widgets=[],this.templatesConfig={helpers:n(216)({numberLocale:h}),compileOptions:{}},this.urlSync=y===!0?{}:y}return i(t,e),l(t,[{key:"addWidget",value:function(e){if(void 0===e.render&&void 0===e.init)throw new Error("Widget definition missing render or init method");this.widgets.push(e)}},{key:"start",value:function(){if(!this.widgets)throw new Error("No widgets were added to instantsearch.js");if(this.urlSync){var e=(0,C["default"])(this.urlSync);this._createURL=e.createURL.bind(e),this._onHistoryChange=e.onHistoryChange.bind(e),this.widgets.push(e)}else this._createURL=a,this._onHistoryChange=function(){};this.searchParameters=this.widgets.reduce(s,this.searchParameters);var t=(0,h["default"])(this.client,this.searchParameters.index||this.indexName,this.searchParameters);this.helper=t,this._init(t.state,t),t.on("result",this._render.bind(this,t)),t.search()}},{key:"createURL",value:function(e){if(!this._createURL)throw new Error("You need to call start() before calling createURL()");return this._createURL(this.helper.state.setQueryParameters(e))}},{key:"_render",value:function(e,t,n){(0,v["default"])(this.widgets,function(r){r.render&&r.render({templatesConfig:this.templatesConfig,results:t,state:n,helper:e,createURL:this._createURL})},this),this.emit("render")}},{key:"_init",value:function(e,t){var n=this._onHistoryChange,r=this.templatesConfig;(0,v["default"])(this.widgets,function(o){o.init&&o.init({state:e,helper:t,templatesConfig:r,onHistoryChange:n})},this)}}]),t}(x.EventEmitter);t["default"]=E,e.exports=t["default"]},function(e,t,n){"use strict";function r(e,t,i){var a=n(93),s=n(94);return i=a(i||{}),void 0===i.protocol&&(i.protocol=s()),i._ua=i._ua||r.ua,new o(e,t,i)}function o(){s.apply(this,arguments)}e.exports=r;var i=n(6),a=window.Promise||n(7).Promise,s=n(12),u=n(13),l=n(88),c=n(92);"development"==={NODE_ENV:"production"}.APP_ENV&&n(40).enable("algoliasearch*"),r.version=n(95),r.ua="Algolia for vanilla JavaScript "+r.version,window.__algolia={debug:n(40),algoliasearch:r};var p={hasXMLHttpRequest:"XMLHttpRequest"in window,hasXDomainRequest:"XDomainRequest"in window,cors:"withCredentials"in new XMLHttpRequest,timeout:"timeout"in new XMLHttpRequest};i(o,s),o.prototype._request=function(e,t){return new a(function(n,r){function o(){if(!c){p.timeout||clearTimeout(s);var e;try{e={body:JSON.parse(d.responseText),responseText:d.responseText,statusCode:d.status,headers:d.getAllResponseHeaders&&d.getAllResponseHeaders()||{}}}catch(t){e=new u.UnparsableJSON({more:d.responseText})}e instanceof u.UnparsableJSON?r(e):n(e)}}function i(e){c||(p.timeout||clearTimeout(s),r(new u.Network({more:e})))}function a(){p.timeout||(c=!0,d.abort()),r(new u.RequestTimeout)}if(!p.cors&&!p.hasXDomainRequest)return void r(new u.Network("CORS not supported"));e=l(e,t.headers);var s,c,f=t.body,d=p.cors?new XMLHttpRequest:new XDomainRequest;d instanceof XMLHttpRequest?d.open(t.method,e,!0):d.open(t.method,e),p.cors&&(f&&("POST"===t.method?d.setRequestHeader("content-type","application/x-www-form-urlencoded"):d.setRequestHeader("content-type","application/json")),d.setRequestHeader("accept","application/json")),d.onprogress=function(){},d.onload=o,d.onerror=i,p.timeout?(d.timeout=t.timeout,d.ontimeout=a):s=setTimeout(a,t.timeout),d.send(f)})},o.prototype._request.fallback=function(e,t){return e=l(e,t.headers),new a(function(n,r){c(e,t,function(e,t){return e?void r(e):void n(t)})})},o.prototype._promise={reject:function(e){return a.reject(e)},resolve:function(e){return a.resolve(e)},delay:function(e){return new a(function(t){setTimeout(t,e)})}}},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){var r;(function(e,o,i){(function(){"use strict";function a(e){return"function"==typeof e||"object"==typeof e&&null!==e}function s(e){return"function"==typeof e}function u(e){return"object"==typeof e&&null!==e}function l(e){z=e}function c(e){J=e}function p(){return function(){e.nextTick(v)}}function f(){return function(){Q(v)}}function d(){var e=0,t=new ee(v),n=document.createTextNode("");return t.observe(n,{characterData:!0}),function(){n.data=e=++e%2}}function h(){var e=new MessageChannel;return e.port1.onmessage=v,function(){e.port2.postMessage(0)}}function m(){return function(){setTimeout(v,1)}}function v(){for(var e=0;$>e;e+=2){var t=re[e],n=re[e+1];t(n),re[e]=void 0,re[e+1]=void 0}$=0}function g(){try{var e=n(10);return Q=e.runOnLoop||e.runOnContext,f()}catch(t){return m()}}function y(){}function b(){return new TypeError("You cannot resolve a promise with itself")}function _(){return new TypeError("A promises callback cannot return that same promise.")}function x(e){try{return e.then}catch(t){return se.error=t,se}}function P(e,t,n,r){try{e.call(t,n,r)}catch(o){return o}}function C(e,t,n){J(function(e){var r=!1,o=P(n,t,function(n){r||(r=!0,t!==n?E(e,n):O(e,n))},function(t){r||(r=!0,S(e,t))},"Settle: "+(e._label||" unknown promise"));!r&&o&&(r=!0,S(e,o))},e)}function w(e,t){t._state===ie?O(e,t._result):t._state===ae?S(e,t._result):j(t,void 0,function(t){E(e,t)},function(t){S(e,t)})}function R(e,t){if(t.constructor===e.constructor)w(e,t);else{var n=x(t);n===se?S(e,se.error):void 0===n?O(e,t):s(n)?C(e,t,n):O(e,t)}}function E(e,t){e===t?S(e,b()):a(t)?R(e,t):O(e,t)}function T(e){e._onerror&&e._onerror(e._result),N(e)}function O(e,t){e._state===oe&&(e._result=t,e._state=ie,0!==e._subscribers.length&&J(N,e))}function S(e,t){e._state===oe&&(e._state=ae,e._result=t,J(T,e))}function j(e,t,n,r){var o=e._subscribers,i=o.length;e._onerror=null,o[i]=t,o[i+ie]=n,o[i+ae]=r,0===i&&e._state&&J(N,e)}function N(e){var t=e._subscribers,n=e._state;if(0!==t.length){for(var r,o,i=e._result,a=0;a<t.length;a+=3)r=t[a],o=t[a+n],r?D(n,r,o,i):o(i);e._subscribers.length=0}}function k(){this.error=null}function M(e,t){try{return e(t)}catch(n){return ue.error=n,ue}}function D(e,t,n,r){var o,i,a,u,l=s(n);if(l){if(o=M(n,r),o===ue?(u=!0,i=o.error,o=null):a=!0,t===o)return void S(t,_())}else o=r,a=!0;t._state!==oe||(l&&a?E(t,o):u?S(t,i):e===ie?O(t,o):e===ae&&S(t,o))}function I(e,t){try{t(function(t){E(e,t)},function(t){S(e,t)})}catch(n){S(e,n)}}function A(e,t){var n=this;n._instanceConstructor=e,n.promise=new e(y),n._validateInput(t)?(n._input=t,n.length=t.length,n._remaining=t.length,n._init(),0===n.length?O(n.promise,n._result):(n.length=n.length||0,n._enumerate(),0===n._remaining&&O(n.promise,n._result))):S(n.promise,n._validationError())}function F(e){return new le(this,e).promise}function L(e){function t(e){E(o,e)}function n(e){S(o,e)}var r=this,o=new r(y);if(!Y(e))return S(o,new TypeError("You must pass an array to race.")),o;for(var i=e.length,a=0;o._state===oe&&i>a;a++)j(r.resolve(e[a]),void 0,t,n);return o}function U(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var n=new t(y);return E(n,e),n}function H(e){var t=this,n=new t(y);return S(n,e),n}function B(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function q(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function V(e){this._id=he++,this._state=void 0,this._result=void 0,this._subscribers=[],y!==e&&(s(e)||B(),this instanceof V||q(),I(this,e))}function W(){var e;if("undefined"!=typeof o)e=o;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=e.Promise;(!n||"[object Promise]"!==Object.prototype.toString.call(n.resolve())||n.cast)&&(e.Promise=me)}var K;K=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};var Q,z,G,Y=K,$=0,J=({}.toString,function(e,t){re[$]=e,re[$+1]=t,$+=2,2===$&&(z?z(v):G())}),X="undefined"!=typeof window?window:void 0,Z=X||{},ee=Z.MutationObserver||Z.WebKitMutationObserver,te="undefined"!=typeof e&&"[object process]"==={}.toString.call(e),ne="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,re=new Array(1e3);G=te?p():ee?d():ne?h():void 0===X?g():m();var oe=void 0,ie=1,ae=2,se=new k,ue=new k;A.prototype._validateInput=function(e){return Y(e)},A.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},A.prototype._init=function(){this._result=new Array(this.length)};var le=A;A.prototype._enumerate=function(){for(var e=this,t=e.length,n=e.promise,r=e._input,o=0;n._state===oe&&t>o;o++)e._eachEntry(r[o],o)},A.prototype._eachEntry=function(e,t){var n=this,r=n._instanceConstructor;u(e)?e.constructor===r&&e._state!==oe?(e._onerror=null,n._settledAt(e._state,t,e._result)):n._willSettleAt(r.resolve(e),t):(n._remaining--,n._result[t]=e)},A.prototype._settledAt=function(e,t,n){var r=this,o=r.promise;o._state===oe&&(r._remaining--,e===ae?S(o,n):r._result[t]=n),0===r._remaining&&O(o,r._result)},A.prototype._willSettleAt=function(e,t){var n=this;j(e,void 0,function(e){n._settledAt(ie,t,e)},function(e){n._settledAt(ae,t,e)})};var ce=F,pe=L,fe=U,de=H,he=0,me=V;V.all=ce,V.race=pe,V.resolve=fe,V.reject=de,V._setScheduler=l,V._setAsap=c,V._asap=J,V.prototype={constructor:V,then:function(e,t){var n=this,r=n._state;if(r===ie&&!e||r===ae&&!t)return this;var o=new this.constructor(y),i=n._result;if(r){var a=arguments[r-1];J(function(){D(r,o,a,i)})}else j(n,o,e,t);return o},"catch":function(e){return this.then(null,e)}};var ve=W,ge={Promise:me,polyfill:ve};n(11).amd?(r=function(){return ge}.call(t,n,t,i),!(void 0!==r&&(i.exports=r))):"undefined"!=typeof i&&i.exports?i.exports=ge:"undefined"!=typeof this&&(this.ES6Promise=ge),ve()}).call(this)}).call(t,n(8),function(){return this}(),n(9)(e))},function(e,t){function n(){l=!1,a.length?u=a.concat(u):c=-1,u.length&&r()}function r(){if(!l){var e=setTimeout(n);l=!0;for(var t=u.length;t;){for(a=u,u=[];++c<t;)a&&a[c].run();c=-1,t=u.length}a=null,l=!1,clearTimeout(e)}}function o(e,t){this.fun=e,this.array=t}function i(){}var a,s=e.exports={},u=[],l=!1,c=-1;s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new o(e,t)),1!==u.length||l||setTimeout(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=i,s.addListener=i,s.once=i,s.off=i,s.removeListener=i,s.removeAllListeners=i,s.emit=i,s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},function(e,t){},function(e,t){e.exports=function(){throw new Error("define cannot be used indirect")}},function(e,t,n){"use strict";function r(e,t,r){var i=n(40)("algoliasearch"),a=n(43),s=n(33),u=n(53),l="Usage: algoliasearch(applicationID, apiKey, opts)";if(!e)throw new p.AlgoliaSearchError("Please provide an application ID. "+l);if(!t)throw new p.AlgoliaSearchError("Please provide an API key. "+l);this.applicationID=e,this.apiKey=t;var c=[this.applicationID+"-1.algolianet.com",this.applicationID+"-2.algolianet.com",this.applicationID+"-3.algolianet.com"];this.hosts={read:[],write:[]},this.hostIndex={read:0,write:0},r=r||{};var f=r.protocol||"https:",d=void 0===r.timeout?2e3:r.timeout;if(/:$/.test(f)||(f+=":"),"http:"!==r.protocol&&"https:"!==r.protocol)throw new p.AlgoliaSearchError("protocol must be `http:` or `https:` (was `"+r.protocol+"`)");r.hosts?s(r.hosts)?(this.hosts.read=a(r.hosts),this.hosts.write=a(r.hosts)):(this.hosts.read=a(r.hosts.read),this.hosts.write=a(r.hosts.write)):(this.hosts.read=[this.applicationID+"-dsn.algolia.net"].concat(c),this.hosts.write=[this.applicationID+".algolia.net"].concat(c)),this.hosts.read=u(this.hosts.read,o(f)),this.hosts.write=u(this.hosts.write,o(f)),this.requestTimeout=d,this.extraHeaders=[],this.cache=r._cache||{},this._ua=r._ua,this._useCache=void 0===r._useCache||r._cache?!0:r._useCache,this._setTimeout=r._setTimeout,i("init done, %j",this)}function o(e){return function(t){return e+"//"+t.toLowerCase()}}function i(){var e="Not implemented in this environment.\nIf you feel this is a mistake, write to support@algolia.com";throw new p.AlgoliaSearchError(e)}function a(e,t){var n=e.toLowerCase().replace(".","").replace("()","");return"algoliasearch: `"+e+"` was replaced by `"+t+"`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#"+n}function s(e,t){t(e,0)}function u(e,t){function n(){return r||(console.log(t),r=!0),e.apply(this,arguments)}var r=!1;return n}function l(e){if(void 0===Array.prototype.toJSON)return JSON.stringify(e);var t=Array.prototype.toJSON;delete Array.prototype.toJSON;var n=JSON.stringify(e);return Array.prototype.toJSON=t,n}function c(e){return function(t,n,r){if("function"==typeof t&&"object"==typeof n||"object"==typeof r)throw new p.AlgoliaSearchError("index.search usage is index.search(query, params, cb)");0===arguments.length||"function"==typeof t?(r=t,t=""):(1===arguments.length||"function"==typeof n)&&(r=n,n=void 0),"object"==typeof t&&null!==t?(n=t,t=void 0):(void 0===t||null===t)&&(t="");var o="";return void 0!==t&&(o+=e+"="+encodeURIComponent(t)),void 0!==n&&(o=this.as._getSearchParams(n,o)),this._search(o,r)}}e.exports=r;var p=n(13);r.prototype={deleteIndex:function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(e),hostType:"write",callback:t})},moveIndex:function(e,t,n){var r={operation:"move",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},copyIndex:function(e,t,n){var r={operation:"copy",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},getLogs:function(e,t,n){return 0===arguments.length||"function"==typeof e?(n=e,e=0,t=10):(1===arguments.length||"function"==typeof t)&&(n=t,t=10),this._jsonRequest({method:"GET",url:"/1/logs?offset="+e+"&length="+t,hostType:"read",callback:n})},listIndexes:function(e,t){var n="";return void 0===e||"function"==typeof e?t=e:n="?page="+e,this._jsonRequest({method:"GET",url:"/1/indexes"+n,hostType:"read",callback:t})},initIndex:function(e){return new this.Index(this,e)},listUserKeys:function(e){return this._jsonRequest({method:"GET",url:"/1/keys",hostType:"read",callback:e})},getUserKeyACL:function(e,t){return this._jsonRequest({method:"GET",url:"/1/keys/"+e,hostType:"read",callback:t})},deleteUserKey:function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/keys/"+e,hostType:"write",callback:t})},addUserKey:function(e,t,r){var o=n(33),i="Usage: client.addUserKey(arrayOfAcls[, params, callback])";if(!o(e))throw new Error(i);(1===arguments.length||"function"==typeof t)&&(r=t,t=null);var a={acl:e};return t&&(a.validity=t.validity,a.maxQueriesPerIPPerHour=t.maxQueriesPerIPPerHour,a.maxHitsPerQuery=t.maxHitsPerQuery,a.indexes=t.indexes,a.description=t.description,t.queryParameters&&(a.queryParameters=this._getSearchParams(t.queryParameters,"")),a.referers=t.referers),this._jsonRequest({method:"POST",url:"/1/keys",body:a,hostType:"write",callback:r})},addUserKeyWithValidity:u(function(e,t,n){return this.addUserKey(e,t,n)},a("client.addUserKeyWithValidity()","client.addUserKey()")),updateUserKey:function(e,t,r,o){var i=n(33),a="Usage: client.updateUserKey(key, arrayOfAcls[, params, callback])";if(!i(t))throw new Error(a);(2===arguments.length||"function"==typeof r)&&(o=r,r=null);var s={acl:t};return r&&(s.validity=r.validity,s.maxQueriesPerIPPerHour=r.maxQueriesPerIPPerHour,s.maxHitsPerQuery=r.maxHitsPerQuery,s.indexes=r.indexes,s.description=r.description,r.queryParameters&&(s.queryParameters=this._getSearchParams(r.queryParameters,"")),s.referers=r.referers),this._jsonRequest({method:"PUT",url:"/1/keys/"+e,body:s,hostType:"write",callback:o})},setSecurityTags:function(e){if("[object Array]"===Object.prototype.toString.call(e)){for(var t=[],n=0;n<e.length;++n)if("[object Array]"===Object.prototype.toString.call(e[n])){for(var r=[],o=0;o<e[n].length;++o)r.push(e[n][o]);t.push("("+r.join(",")+")")}else t.push(e[n]);e=t.join(",")}this.securityTags=e},setUserToken:function(e){this.userToken=e},startQueriesBatch:u(function(){this._batch=[]},a("client.startQueriesBatch()","client.search()")),addQueryInBatch:u(function(e,t,n){this._batch.push({indexName:e,query:t,params:n})},a("client.addQueryInBatch()","client.search()")),clearCache:function(){this.cache={}},sendQueriesBatch:u(function(e){return this.search(this._batch,e)},a("client.sendQueriesBatch()","client.search()")),setRequestTimeout:function(e){e&&(this.requestTimeout=parseInt(e,10))},search:function(e,t){var r=n(33),o=n(53),i="Usage: client.search(arrayOfQueries[, callback])";if(!r(e))throw new Error(i);var a=this,s={requests:o(e,function(e){var t="";return void 0!==e.query&&(t+="query="+encodeURIComponent(e.query)),{indexName:e.indexName,params:a._getSearchParams(e.params,t)}})},u=o(s.requests,function(e,t){return t+"="+encodeURIComponent("/1/indexes/"+encodeURIComponent(e.indexName)+"?"+e.params)}).join("&");return this._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/*/queries",body:s,hostType:"read",fallback:{method:"GET",url:"/1/indexes/*",body:{params:u}},callback:t})},batch:function(e,t){var r=n(33),o="Usage: client.batch(operations[, callback])";if(!r(e))throw new Error(o);return this._jsonRequest({method:"POST",url:"/1/indexes/*/batch",body:{requests:e},hostType:"write",callback:t})},destroy:i,enableRateLimitForward:i,disableRateLimitForward:i,useSecuredAPIKey:i,disableSecuredAPIKey:i,generateSecuredApiKey:i,Index:function(e,t){this.indexName=t,this.as=e,this.typeAheadArgs=null,this.typeAheadValueOption=null,this.cache={}},setExtraHeader:function(e,t){this.extraHeaders.push({name:e.toLowerCase(),value:t})},addAlgoliaAgent:function(e){this._ua+=";"+e},_jsonRequest:function(e){function t(n,s){function d(e){var t=e&&e.body&&e.body.message&&e.body.status||e.statusCode||e&&e.body&&200;o("received response: statusCode: %s, computed statusCode: %d, headers: %j",e.statusCode,t,e.headers);var n=200===t||201===t,r=!n&&4!==Math.floor(t/100)&&1!==Math.floor(t/100);if(a._useCache&&n&&i&&(i[v]=e.responseText),n)return e.body;if(r)return u+=1,m();var s=new p.AlgoliaSearchError(e.body&&e.body.message);return a._promise.reject(s)}function h(r){return o("error: %s, stack: %s",r.message,r.stack),r instanceof p.AlgoliaSearchError||(r=new p.Unknown(r&&r.message,r)),u+=1,r instanceof p.Unknown||r instanceof p.UnparsableJSON||u>=a.hosts[e.hostType].length&&(c||!f)?a._promise.reject(r):(a.hostIndex[e.hostType]=++a.hostIndex[e.hostType]%a.hosts[e.hostType].length,r instanceof p.RequestTimeout?m():(c||(u=1/0),t(n,s)))}function m(){return a.hostIndex[e.hostType]=++a.hostIndex[e.hostType]%a.hosts[e.hostType].length,s.timeout=a.requestTimeout*(u+1),t(n,s)}var v;if(a._useCache&&(v=e.url),a._useCache&&r&&(v+="_body_"+s.body),a._useCache&&i&&void 0!==i[v])return o("serving response from cache"),a._promise.resolve(JSON.parse(i[v]));if(u>=a.hosts[e.hostType].length)return!f||c?(o("could not get any response"),a._promise.reject(new p.AlgoliaSearchError("Cannot connect to the AlgoliaSearch API. Send an email to support@algolia.com to report and resolve the issue. Application id was: "+a.applicationID))):(o("switching to fallback"),u=0,s.method=e.fallback.method,s.url=e.fallback.url,s.jsonBody=e.fallback.body,s.jsonBody&&(s.body=l(s.jsonBody)),s.timeout=a.requestTimeout*(u+1),a.hostIndex[e.hostType]=0,c=!0,t(a._request.fallback,s));var g=a.hosts[e.hostType][a.hostIndex[e.hostType]]+s.url,y={body:s.body,jsonBody:s.jsonBody,method:s.method,headers:a._computeRequestHeaders(),timeout:s.timeout,debug:o};return o("method: %s, url: %s, headers: %j, timeout: %d",y.method,g,y.headers,y.timeout),n===a._request.fallback&&o("using fallback"),n.call(a,g,y).then(d,h)}var r,o=n(40)("algoliasearch:"+e.url),i=e.cache,a=this,u=0,c=!1,f=a._request.fallback&&e.fallback;void 0!==e.body&&(r=l(e.body)),o("request start");var d=t(a._request,{url:e.url,method:e.method,body:r,jsonBody:e.body,timeout:a.requestTimeout*(u+1)});return e.callback?void d.then(function(t){s(function(){e.callback(null,t)},a._setTimeout||setTimeout)},function(t){s(function(){e.callback(t)},a._setTimeout||setTimeout)}):d},_getSearchParams:function(e,t){if(void 0===e||null===e)return t;for(var n in e)null!==n&&void 0!==e[n]&&e.hasOwnProperty(n)&&(t+=""===t?"":"&",t+=n+"="+encodeURIComponent("[object Array]"===Object.prototype.toString.call(e[n])?l(e[n]):e[n]));return t},_computeRequestHeaders:function(){var e=n(14),t={"x-algolia-api-key":this.apiKey,"x-algolia-application-id":this.applicationID,"x-algolia-agent":this._ua};return this.userToken&&(t["x-algolia-usertoken"]=this.userToken),this.securityTags&&(t["x-algolia-tagfilters"]=this.securityTags),this.extraHeaders&&e(this.extraHeaders,function(e){t[e.name]=e.value}),t}},r.prototype.Index.prototype={clearCache:function(){this.cache={}},addObject:function(e,t,n){var r=this;return(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0),this.as._jsonRequest({method:void 0!==t?"PUT":"POST",url:"/1/indexes/"+encodeURIComponent(r.indexName)+(void 0!==t?"/"+encodeURIComponent(t):""),body:e,hostType:"write",callback:n})},addObjects:function(e,t){var r=n(33),o="Usage: index.addObjects(arrayOfObjects[, callback])";if(!r(e))throw new Error(o);for(var i=this,a={requests:[]},s=0;s<e.length;++s){var u={action:"addObject",body:e[s]};a.requests.push(u)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(i.indexName)+"/batch",body:a,hostType:"write",callback:t})},getObject:function(e,t,n){var r=this;(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0);var o="";if(void 0!==t){o="?attributes=";for(var i=0;i<t.length;++i)0!==i&&(o+=","),o+=t[i]}return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e)+o,hostType:"read",callback:n})},getObjects:function(e,t,r){var o=n(33),i=n(53),a="Usage: index.getObjects(arrayOfObjectIDs[, callback])";if(!o(e))throw new Error(a);var s=this;(1===arguments.length||"function"==typeof t)&&(r=t,t=void 0);var u={requests:i(e,function(e){var n={indexName:s.indexName,objectID:e};return t&&(n.attributesToRetrieve=t.join(",")),n})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/*/objects",hostType:"read",body:u,callback:r})},partialUpdateObject:function(e,t,n){(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0);var r=this,o="/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e.objectID)+"/partial";return t===!1&&(o+="?createIfNotExists=false"),this.as._jsonRequest({method:"POST",url:o,body:e,hostType:"write",callback:n})},partialUpdateObjects:function(e,t){var r=n(33),o="Usage: index.partialUpdateObjects(arrayOfObjects[, callback])";if(!r(e))throw new Error(o);for(var i=this,a={requests:[]},s=0;s<e.length;++s){var u={action:"partialUpdateObject",objectID:e[s].objectID,body:e[s]};a.requests.push(u)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(i.indexName)+"/batch",body:a,hostType:"write",callback:t})},saveObject:function(e,t){var n=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/"+encodeURIComponent(e.objectID),body:e,hostType:"write",callback:t})},saveObjects:function(e,t){var r=n(33),o="Usage: index.saveObjects(arrayOfObjects[, callback])";if(!r(e))throw new Error(o);for(var i=this,a={requests:[]},s=0;s<e.length;++s){var u={action:"updateObject",objectID:e[s].objectID,body:e[s]};a.requests.push(u)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(i.indexName)+"/batch",body:a,hostType:"write",callback:t})},deleteObject:function(e,t){if("function"==typeof e||"string"!=typeof e&&"number"!=typeof e){var n=new p.AlgoliaSearchError("Cannot delete an object without an objectID");return t=e,"function"==typeof t?t(n):this.as._promise.reject(n)}var r=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e),hostType:"write",callback:t})},deleteObjects:function(e,t){var r=n(33),o=n(53),i="Usage: index.deleteObjects(arrayOfObjectIDs[, callback])";if(!r(e))throw new Error(i);var a=this,s={requests:o(e,function(e){return{action:"deleteObject",objectID:e,body:{objectID:e}}})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(a.indexName)+"/batch",body:s,hostType:"write",callback:t})},deleteByQuery:function(e,t,r){function o(e){if(0===e.nbHits)return e;var t=p(e.hits,function(e){return e.objectID});return f.deleteObjects(t).then(i).then(a)}function i(e){return f.waitTask(e.taskID)}function a(){return f.deleteByQuery(e,t)}function u(){s(function(){r(null)},d._setTimeout||setTimeout)}function l(e){s(function(){r(e)},d._setTimeout||setTimeout)}var c=n(43),p=n(53),f=this,d=f.as;1===arguments.length||"function"==typeof t?(r=t,t={}):t=c(t),t.attributesToRetrieve="objectID",t.hitsPerPage=1e3,t.distinct=!1,this.clearCache();var h=this.search(e,t).then(o);return r?void h.then(u,l):h},search:c("query"),similarSearch:c("similarQuery"),browse:function(e,t,r){var o,i,a=n(78),s=this;0===arguments.length||1===arguments.length&&"function"==typeof arguments[0]?(o=0,r=arguments[0],e=void 0):"number"==typeof arguments[0]?(o=arguments[0],"number"==typeof arguments[1]?i=arguments[1]:"function"==typeof arguments[1]&&(r=arguments[1],i=void 0),e=void 0,t=void 0):"object"==typeof arguments[0]?("function"==typeof arguments[1]&&(r=arguments[1]),t=arguments[0],e=void 0):"string"==typeof arguments[0]&&"function"==typeof arguments[1]&&(r=arguments[1],t=void 0),t=a({},t||{},{page:o,hitsPerPage:i,query:e});var u=this.as._getSearchParams(t,"");return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(s.indexName)+"/browse?"+u,hostType:"read",callback:r})},browseFrom:function(e,t){return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/browse?cursor="+encodeURIComponent(e),hostType:"read",callback:t})},browseAll:function(e,t){function r(e){if(!s._stopped){var t;t=void 0!==e?"cursor="+encodeURIComponent(e):c,u._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(l.indexName)+"/browse?"+t,hostType:"read",callback:o})}}function o(e,t){return s._stopped?void 0:e?void s._error(e):(s._result(t),void 0===t.cursor?void s._end():void r(t.cursor))}"object"==typeof e&&(t=e,e=void 0);var i=n(78),a=n(86),s=new a,u=this.as,l=this,c=u._getSearchParams(i({},t||{},{query:e}),"");return r(),s},ttAdapter:function(e){var t=this;return function(n,r,o){var i;i="function"==typeof o?o:r,t.search(n,e,function(e,t){return e?void i(e):void i(t.hits)})}},waitTask:function(e,t){function n(){return c._jsonRequest({method:"GET",hostType:"read",url:"/1/indexes/"+encodeURIComponent(l.indexName)+"/task/"+e}).then(function(e){u++;var t=i*u*u;return t>a&&(t=a),"published"!==e.status?c._promise.delay(t).then(n):e})}function r(e){s(function(){t(null,e)},c._setTimeout||setTimeout)}function o(e){s(function(){t(e)},c._setTimeout||setTimeout)}var i=100,a=5e3,u=0,l=this,c=l.as,p=n();return t?void p.then(r,o):p},clearIndex:function(e){var t=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/clear",hostType:"write",callback:e})},getSettings:function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/settings",hostType:"read",callback:e})},setSettings:function(e,t){var n=this; return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/settings",hostType:"write",body:e,callback:t})},listUserKeys:function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/keys",hostType:"read",callback:e})},getUserKeyACL:function(e,t){var n=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"read",callback:t})},deleteUserKey:function(e,t){var n=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"write",callback:t})},addUserKey:function(e,t,r){var o=n(33),i="Usage: index.addUserKey(arrayOfAcls[, params, callback])";if(!o(e))throw new Error(i);(1===arguments.length||"function"==typeof t)&&(r=t,t=null);var a={acl:e};return t&&(a.validity=t.validity,a.maxQueriesPerIPPerHour=t.maxQueriesPerIPPerHour,a.maxHitsPerQuery=t.maxHitsPerQuery,a.description=t.description,t.queryParameters&&(a.queryParameters=this.as._getSearchParams(t.queryParameters,"")),a.referers=t.referers),this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys",body:a,hostType:"write",callback:r})},addUserKeyWithValidity:u(function(e,t,n){return this.addUserKey(e,t,n)},a("index.addUserKeyWithValidity()","index.addUserKey()")),updateUserKey:function(e,t,r,o){var i=n(33),a="Usage: index.updateUserKey(key, arrayOfAcls[, params, callback])";if(!i(t))throw new Error(a);(2===arguments.length||"function"==typeof r)&&(o=r,r=null);var s={acl:t};return r&&(s.validity=r.validity,s.maxQueriesPerIPPerHour=r.maxQueriesPerIPPerHour,s.maxHitsPerQuery=r.maxHitsPerQuery,s.description=r.description,r.queryParameters&&(s.queryParameters=this.as._getSearchParams(r.queryParameters,"")),s.referers=r.referers),this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys/"+e,body:s,hostType:"write",callback:o})},_search:function(e,t){return this.as._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/query",body:{params:e},hostType:"read",fallback:{method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName),body:{params:e}},callback:t})},as:null,indexName:null,typeAheadArgs:null,typeAheadValueOption:null}},function(e,t,n){"use strict";function r(e,t){var r=n(14),o=this;"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):o.stack=(new Error).stack||"Cannot get a stacktrace, browser is too old",this.name=this.constructor.name,this.message=e||"Unknown error",t&&r(t,function(e,t){o[t]=e})}function o(e,t){function n(){var n=Array.prototype.slice.call(arguments,0);"string"!=typeof n[0]&&n.unshift(t),r.apply(this,n),this.name="AlgoliaSearch"+e+"Error"}return i(n,r),n}var i=n(6);i(r,Error),e.exports={AlgoliaSearchError:r,UnparsableJSON:o("UnparsableJSON","Could not parse the incoming response as JSON, see err.more for details"),RequestTimeout:o("RequestTimeout","Request timedout before getting a response"),Network:o("Network","Network issue, see err.more for details"),JSONPScriptFail:o("JSONPScriptFail","<script> was loaded but did not call our provided callback"),JSONPScriptError:o("JSONPScriptError","<script> unable to load due to an `error` event on it"),Unknown:o("Unknown","Unknown error occured")}},function(e,t,n){var r=n(15),o=n(16),i=n(37),a=i(r,o);e.exports=a},function(e,t){function n(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}e.exports=n},function(e,t,n){var r=n(17),o=n(36),i=o(r);e.exports=i},function(e,t,n){function r(e,t){return o(e,t,i)}var o=n(18),i=n(22);e.exports=r},function(e,t,n){var r=n(19),o=r();e.exports=o},function(e,t,n){function r(e){return function(t,n,r){for(var i=o(t),a=r(t),s=a.length,u=e?s:-1;e?u--:++u<s;){var l=a[u];if(n(i[l],l,i)===!1)break}return t}}var o=n(20);e.exports=r},function(e,t,n){function r(e){return o(e)?e:Object(e)}var o=n(21);e.exports=r},function(e,t){function n(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=n},function(e,t,n){var r=n(23),o=n(27),i=n(21),a=n(31),s=r(Object,"keys"),u=s?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&o(e)?a(e):i(e)?s(e):[]}:a;e.exports=u},function(e,t,n){function r(e,t){var n=null==e?void 0:e[t];return o(n)?n:void 0}var o=n(24);e.exports=r},function(e,t,n){function r(e){return null==e?!1:o(e)?c.test(u.call(e)):i(e)&&a.test(e)}var o=n(25),i=n(26),a=/^\[object .+?Constructor\]$/,s=Object.prototype,u=Function.prototype.toString,l=s.hasOwnProperty,c=RegExp("^"+u.call(l).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){function r(e){return o(e)&&s.call(e)==i}var o=n(21),i="[object Function]",a=Object.prototype,s=a.toString;e.exports=r},function(e,t){function n(e){return!!e&&"object"==typeof e}e.exports=n},function(e,t,n){function r(e){return null!=e&&i(o(e))}var o=n(28),i=n(30);e.exports=r},function(e,t,n){var r=n(29),o=r("length");e.exports=o},function(e,t){function n(e){return function(t){return null==t?void 0:t[e]}}e.exports=n},function(e,t){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&r>=e}var r=9007199254740991;e.exports=n},function(e,t,n){function r(e){for(var t=u(e),n=t.length,r=n&&e.length,l=!!r&&s(r)&&(i(e)||o(e)),p=-1,f=[];++p<n;){var d=t[p];(l&&a(d,r)||c.call(e,d))&&f.push(d)}return f}var o=n(32),i=n(33),a=n(34),s=n(30),u=n(35),l=Object.prototype,c=l.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e)&&s.call(e,"callee")&&!u.call(e,"callee")}var o=n(27),i=n(26),a=Object.prototype,s=a.hasOwnProperty,u=a.propertyIsEnumerable;e.exports=r},function(e,t,n){var r=n(23),o=n(30),i=n(26),a="[object Array]",s=Object.prototype,u=s.toString,l=r(Array,"isArray"),c=l||function(e){return i(e)&&o(e.length)&&u.call(e)==a};e.exports=c},function(e,t){function n(e,t){return e="number"==typeof e||r.test(e)?+e:-1,t=null==t?o:t,e>-1&&e%1==0&&t>e}var r=/^\d+$/,o=9007199254740991;e.exports=n},function(e,t,n){function r(e){if(null==e)return[];u(e)||(e=Object(e));var t=e.length;t=t&&s(t)&&(i(e)||o(e))&&t||0;for(var n=e.constructor,r=-1,l="function"==typeof n&&n.prototype===e,p=Array(t),f=t>0;++r<t;)p[r]=r+"";for(var d in e)f&&a(d,t)||"constructor"==d&&(l||!c.call(e,d))||p.push(d);return p}var o=n(32),i=n(33),a=n(34),s=n(30),u=n(21),l=Object.prototype,c=l.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t){return function(n,r){var s=n?o(n):0;if(!i(s))return e(n,r);for(var u=t?s:-1,l=a(n);(t?u--:++u<s)&&r(l[u],u,l)!==!1;);return n}}var o=n(28),i=n(30),a=n(20);e.exports=r},function(e,t,n){function r(e,t){return function(n,r,a){return"function"==typeof r&&void 0===a&&i(n)?e(n,r):t(n,o(r,a,3))}}var o=n(38),i=n(33);e.exports=r},function(e,t,n){function r(e,t,n){if("function"!=typeof e)return o;if(void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 3:return function(n,r,o){return e.call(t,n,r,o)};case 4:return function(n,r,o,i){return e.call(t,n,r,o,i)};case 5:return function(n,r,o,i,a){return e.call(t,n,r,o,i,a)}}return function(){return e.apply(t,arguments)}}var o=n(39);e.exports=r},function(e,t){function n(e){return e}e.exports=n},function(e,t,n){function r(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function o(){var e=arguments,n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),!n)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var o=0,i=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(o++,"%c"===e&&(i=o))}),e.splice(i,0,r),e}function i(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(n){}}function s(){var e;try{e=t.storage.debug}catch(n){}return e}function u(){try{return window.localStorage}catch(e){}}t=e.exports=n(41),t.log=i,t.formatArgs=o,t.save=a,t.load=s,t.useColors=r,t.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){return JSON.stringify(e)},t.enable(s())},function(e,t,n){function r(){return t.colors[c++%t.colors.length]}function o(e){function n(){}function o(){var e=o,n=+new Date,i=n-(l||n);e.diff=i,e.prev=l,e.curr=n,l=n,null==e.useColors&&(e.useColors=t.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(n,r){if("%%"===n)return n;s++;var o=t.formatters[r];if("function"==typeof o){var i=a[s];n=o.call(e,i),a.splice(s,1),s--}return n}),"function"==typeof t.formatArgs&&(a=t.formatArgs.apply(e,a));var u=o.log||t.log||console.log.bind(console);u.apply(e,a)}n.enabled=!1,o.enabled=!0;var i=t.enabled(e)?o:n;return i.namespace=e,i}function i(e){t.save(e);for(var n=(e||"").split(/[\s,]+/),r=n.length,o=0;r>o;o++)n[o]&&(e=n[o].replace(/\*/g,".*?"),"-"===e[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))}function a(){t.enable("")}function s(e){var n,r;for(n=0,r=t.skips.length;r>n;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;r>n;n++)if(t.names[n].test(e))return!0;return!1}function u(e){return e instanceof Error?e.stack||e.message:e}t=e.exports=o,t.coerce=u,t.disable=a,t.enable=i,t.enabled=s,t.humanize=n(42),t.names=[],t.skips=[],t.formatters={};var l,c=0},function(e,t){function n(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"days":case"day":case"d":return n*l;case"hours":case"hour":case"hrs":case"hr":case"h":return n*u;case"minutes":case"minute":case"mins":case"min":case"m":return n*s;case"seconds":case"second":case"secs":case"sec":case"s":return n*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function r(e){return e>=l?Math.round(e/l)+"d":e>=u?Math.round(e/u)+"h":e>=s?Math.round(e/s)+"m":e>=a?Math.round(e/a)+"s":e+"ms"}function o(e){return i(e,l,"day")||i(e,u,"hour")||i(e,s,"minute")||i(e,a,"second")||e+" ms"}function i(e,t,n){return t>e?void 0:1.5*t>e?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}var a=1e3,s=60*a,u=60*s,l=24*u,c=365.25*l;e.exports=function(e,t){return t=t||{},"string"==typeof e?n(e):t["long"]?o(e):r(e)}},function(e,t,n){function r(e,t,n,r){return t&&"boolean"!=typeof t&&a(e,t,n)?t=!1:"function"==typeof t&&(r=n,n=t,t=!1),"function"==typeof n?o(e,t,i(n,r,3)):o(e,t)}var o=n(44),i=n(38),a=n(52);e.exports=r},function(e,t,n){function r(e,t,n,h,m,v,g){var b;if(n&&(b=m?n(e,h,m):n(e)),void 0!==b)return b;if(!f(e))return e;var _=p(e);if(_){if(b=u(e),!t)return o(e,b)}else{var P=L.call(e),C=P==y;if(P!=x&&P!=d&&(!C||m))return A[P]?l(e,P,t):m?e:{};if(b=c(C?{}:e),!t)return a(b,e)}v||(v=[]),g||(g=[]);for(var w=v.length;w--;)if(v[w]==e)return g[w];return v.push(e),g.push(b),(_?i:s)(e,function(o,i){b[i]=r(o,t,n,i,e,v,g)}),b}var o=n(45),i=n(15),a=n(46),s=n(17),u=n(48),l=n(49),c=n(51),p=n(33),f=n(21),d="[object Arguments]",h="[object Array]",m="[object Boolean]",v="[object Date]",g="[object Error]",y="[object Function]",b="[object Map]",_="[object Number]",x="[object Object]",P="[object RegExp]",C="[object Set]",w="[object String]",R="[object WeakMap]",E="[object ArrayBuffer]",T="[object Float32Array]",O="[object Float64Array]",S="[object Int8Array]",j="[object Int16Array]",N="[object Int32Array]",k="[object Uint8Array]",M="[object Uint8ClampedArray]",D="[object Uint16Array]",I="[object Uint32Array]",A={};A[d]=A[h]=A[E]=A[m]=A[v]=A[T]=A[O]=A[S]=A[j]=A[N]=A[_]=A[x]=A[P]=A[w]=A[k]=A[M]=A[D]=A[I]=!0,A[g]=A[y]=A[b]=A[C]=A[R]=!1;var F=Object.prototype,L=F.toString;e.exports=r},function(e,t){function n(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}e.exports=n},function(e,t,n){function r(e,t){return null==t?e:o(t,i(t),e)}var o=n(47),i=n(22);e.exports=r},function(e,t){function n(e,t,n){n||(n={});for(var r=-1,o=t.length;++r<o;){var i=t[r];n[i]=e[i]}return n}e.exports=n},function(e,t){function n(e){var t=e.length,n=new e.constructor(t);return t&&"string"==typeof e[0]&&o.call(e,"index")&&(n.index=e.index,n.input=e.input),n}var r=Object.prototype,o=r.hasOwnProperty;e.exports=n},function(e,t,n){function r(e,t,n){var r=e.constructor;switch(t){case c:return o(e);case i:case a:return new r(+e);case p:case f:case d:case h:case m:case v:case g:case y:case b:var x=e.buffer;return new r(n?o(x):x,e.byteOffset,e.length);case s:case l:return new r(e);case u:var P=new r(e.source,_.exec(e));P.lastIndex=e.lastIndex}return P}var o=n(50),i="[object Boolean]",a="[object Date]",s="[object Number]",u="[object RegExp]",l="[object String]",c="[object ArrayBuffer]",p="[object Float32Array]",f="[object Float64Array]",d="[object Int8Array]",h="[object Int16Array]",m="[object Int32Array]",v="[object Uint8Array]",g="[object Uint8ClampedArray]",y="[object Uint16Array]",b="[object Uint32Array]",_=/\w*$/;e.exports=r},function(e,t){(function(t){function n(e){var t=new r(e.byteLength),n=new o(t);return n.set(new o(e)),t}var r=t.ArrayBuffer,o=t.Uint8Array;e.exports=n}).call(t,function(){return this}())},function(e,t){function n(e){var t=e.constructor;return"function"==typeof t&&t instanceof t||(t=Object),new t}e.exports=n},function(e,t,n){function r(e,t,n){if(!a(n))return!1;var r=typeof t;if("number"==r?o(n)&&i(t,n.length):"string"==r&&t in n){var s=n[t];return e===e?e===s:s!==s}return!1}var o=n(27),i=n(34),a=n(21);e.exports=r},function(e,t,n){function r(e,t,n){var r=s(e)?o:a;return t=i(t,n,3),r(e,t)}var o=n(54),i=n(55),a=n(77),s=n(33);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=n},function(e,t,n){function r(e,t,n){var r=typeof e;return"function"==r?void 0===t?e:a(e,t,n):null==e?s:"object"==r?o(e):void 0===t?u(e):i(e,t)}var o=n(56),i=n(68),a=n(38),s=n(39),u=n(75);e.exports=r},function(e,t,n){function r(e){var t=i(e);if(1==t.length&&t[0][2]){var n=t[0][0],r=t[0][1];return function(e){return null==e?!1:e[n]===r&&(void 0!==r||n in a(e))}}return function(e){return o(e,t)}}var o=n(57),i=n(65),a=n(20);e.exports=r},function(e,t,n){function r(e,t,n){var r=t.length,a=r,s=!n;if(null==e)return!a;for(e=i(e);r--;){var u=t[r];if(s&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++r<a;){u=t[r];var l=u[0],c=e[l],p=u[1];if(s&&u[2]){if(void 0===c&&!(l in e))return!1}else{var f=n?n(c,p,l):void 0;if(!(void 0===f?o(p,c,n,!0):f))return!1}}return!0}var o=n(58),i=n(20);e.exports=r},function(e,t,n){function r(e,t,n,s,u,l){return e===t?!0:null==e||null==t||!i(e)&&!a(t)?e!==e&&t!==t:o(e,t,r,n,s,u,l)}var o=n(59),i=n(21),a=n(26);e.exports=r},function(e,t,n){function r(e,t,n,r,f,m,v){var g=s(e),y=s(t),b=c,_=c;g||(b=h.call(e),b==l?b=p:b!=p&&(g=u(e))),y||(_=h.call(t),_==l?_=p:_!=p&&(y=u(t)));var x=b==p,P=_==p,C=b==_;if(C&&!g&&!x)return i(e,t,b);if(!f){var w=x&&d.call(e,"__wrapped__"),R=P&&d.call(t,"__wrapped__");if(w||R)return n(w?e.value():e,R?t.value():t,r,f,m,v)}if(!C)return!1;m||(m=[]),v||(v=[]);for(var E=m.length;E--;)if(m[E]==e)return v[E]==t;m.push(e),v.push(t);var T=(g?o:a)(e,t,n,r,f,m,v);return m.pop(),v.pop(),T}var o=n(60),i=n(62),a=n(63),s=n(33),u=n(64),l="[object Arguments]",c="[object Array]",p="[object Object]",f=Object.prototype,d=f.hasOwnProperty,h=f.toString;e.exports=r},function(e,t,n){function r(e,t,n,r,i,a,s){var u=-1,l=e.length,c=t.length;if(l!=c&&!(i&&c>l))return!1;for(;++u<l;){var p=e[u],f=t[u],d=r?r(i?f:p,i?p:f,u):void 0;if(void 0!==d){if(d)continue;return!1}if(i){if(!o(t,function(e){return p===e||n(p,e,r,i,a,s)}))return!1}else if(p!==f&&!n(p,f,r,i,a,s))return!1}return!0}var o=n(61);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}e.exports=n},function(e,t){function n(e,t,n){switch(n){case r:case o:return+e==+t;case i:return e.name==t.name&&e.message==t.message;case a:return e!=+e?t!=+t:e==+t;case s:case u:return e==t+""}return!1}var r="[object Boolean]",o="[object Date]",i="[object Error]",a="[object Number]",s="[object RegExp]",u="[object String]";e.exports=n},function(e,t,n){function r(e,t,n,r,i,s,u){var l=o(e),c=l.length,p=o(t),f=p.length;if(c!=f&&!i)return!1;for(var d=c;d--;){var h=l[d];if(!(i?h in t:a.call(t,h)))return!1}for(var m=i;++d<c;){h=l[d];var v=e[h],g=t[h],y=r?r(i?g:v,i?v:g,h):void 0;if(!(void 0===y?n(v,g,r,i,s,u):y))return!1;m||(m="constructor"==h)}if(!m){var b=e.constructor,_=t.constructor;if(b!=_&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof _&&_ instanceof _))return!1}return!0}var o=n(22),i=Object.prototype,a=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e.length)&&!!S[N.call(e)]}var o=n(30),i=n(26),a="[object Arguments]",s="[object Array]",u="[object Boolean]",l="[object Date]",c="[object Error]",p="[object Function]",f="[object Map]",d="[object Number]",h="[object Object]",m="[object RegExp]",v="[object Set]",g="[object String]",y="[object WeakMap]",b="[object ArrayBuffer]",_="[object Float32Array]",x="[object Float64Array]",P="[object Int8Array]",C="[object Int16Array]",w="[object Int32Array]",R="[object Uint8Array]",E="[object Uint8ClampedArray]",T="[object Uint16Array]",O="[object Uint32Array]",S={};S[_]=S[x]=S[P]=S[C]=S[w]=S[R]=S[E]=S[T]=S[O]=!0,S[a]=S[s]=S[b]=S[u]=S[l]=S[c]=S[p]=S[f]=S[d]=S[h]=S[m]=S[v]=S[g]=S[y]=!1;var j=Object.prototype,N=j.toString;e.exports=r},function(e,t,n){function r(e){for(var t=i(e),n=t.length;n--;)t[n][2]=o(t[n][1]);return t}var o=n(66),i=n(67);e.exports=r},function(e,t,n){function r(e){return e===e&&!o(e)}var o=n(21);e.exports=r},function(e,t,n){function r(e){e=i(e);for(var t=-1,n=o(e),r=n.length,a=Array(r);++t<r;){var s=n[t];a[t]=[s,e[s]]}return a}var o=n(22),i=n(20);e.exports=r},function(e,t,n){function r(e,t){var n=s(e),r=u(e)&&l(t),d=e+"";return e=f(e),function(s){if(null==s)return!1;var u=d;if(s=p(s),(n||!r)&&!(u in s)){if(s=1==e.length?s:o(s,a(e,0,-1)),null==s)return!1;u=c(e),s=p(s)}return s[u]===t?void 0!==t||u in s:i(t,s[u],void 0,!0)}}var o=n(69),i=n(58),a=n(70),s=n(33),u=n(71),l=n(66),c=n(72),p=n(20),f=n(73);e.exports=r},function(e,t,n){function r(e,t,n){if(null!=e){void 0!==n&&n in o(e)&&(t=[n]);for(var r=0,i=t.length;null!=e&&i>r;)e=e[t[r++]];return r&&r==i?e:void 0}}var o=n(20);e.exports=r},function(e,t){function n(e,t,n){var r=-1,o=e.length;t=null==t?0:+t||0,0>t&&(t=-t>o?0:o+t),n=void 0===n||n>o?o:+n||0,0>n&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(o);++r<o;)i[r]=e[r+t];return i}e.exports=n},function(e,t,n){function r(e,t){var n=typeof e;if("string"==n&&s.test(e)||"number"==n)return!0;if(o(e))return!1;var r=!a.test(e);return r||null!=t&&e in i(t)}var o=n(33),i=n(20),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,s=/^\w*$/;e.exports=r},function(e,t){function n(e){var t=e?e.length:0;return t?e[t-1]:void 0}e.exports=n},function(e,t,n){function r(e){if(i(e))return e;var t=[];return o(e).replace(a,function(e,n,r,o){t.push(r?o.replace(s,"$1"):n||e)}),t}var o=n(74),i=n(33),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,s=/\\(\\)?/g;e.exports=r},function(e,t){function n(e){return null==e?"":e+""}e.exports=n},function(e,t,n){function r(e){return a(e)?o(e):i(e)}var o=n(29),i=n(76),a=n(71);e.exports=r},function(e,t,n){function r(e){var t=e+"";return e=i(e),function(n){return o(n,e,t)}}var o=n(69),i=n(73);e.exports=r},function(e,t,n){function r(e,t){var n=-1,r=i(e)?Array(e.length):[];return o(e,function(e,o,i){r[++n]=t(e,o,i)}),r}var o=n(16),i=n(27);e.exports=r},function(e,t,n){var r=n(79),o=n(84),i=o(r);e.exports=i},function(e,t,n){function r(e,t,n,f,d){if(!u(e))return e;var h=s(t)&&(a(t)||c(t)),m=h?void 0:p(t);return o(m||t,function(o,a){if(m&&(a=o,o=t[a]),l(o))f||(f=[]),d||(d=[]),i(e,t,a,r,n,f,d);else{var s=e[a],u=n?n(s,o,a,e,t):void 0,c=void 0===u;c&&(u=o),void 0===u&&(!h||a in e)||!c&&(u===u?u===s:s!==s)||(e[a]=u)}}),e}var o=n(15),i=n(80),a=n(33),s=n(27),u=n(21),l=n(26),c=n(64),p=n(22);e.exports=r},function(e,t,n){function r(e,t,n,r,p,f,d){for(var h=f.length,m=t[n];h--;)if(f[h]==m)return void(e[n]=d[h]);var v=e[n],g=p?p(v,m,n,e,t):void 0,y=void 0===g;y&&(g=m,s(m)&&(a(m)||l(m))?g=a(v)?v:s(v)?o(v):[]:u(m)||i(m)?g=i(v)?c(v):u(v)?v:{}:y=!1),f.push(m),d.push(g),y?e[n]=r(g,m,p,f,d):(g===g?g!==v:v===v)&&(e[n]=g)}var o=n(45),i=n(32),a=n(33),s=n(27),u=n(81),l=n(64),c=n(83);e.exports=r},function(e,t,n){function r(e){var t;if(!a(e)||c.call(e)!=s||i(e)||!l.call(e,"constructor")&&(t=e.constructor,"function"==typeof t&&!(t instanceof t)))return!1;var n;return o(e,function(e,t){n=t}),void 0===n||l.call(e,n)}var o=n(82),i=n(32),a=n(26),s="[object Object]",u=Object.prototype,l=u.hasOwnProperty,c=u.toString;e.exports=r},function(e,t,n){function r(e,t){return o(e,t,i)}var o=n(18),i=n(35);e.exports=r},function(e,t,n){function r(e){return o(e,i(e))}var o=n(47),i=n(35);e.exports=r},function(e,t,n){function r(e){return a(function(t,n){var r=-1,a=null==t?0:n.length,s=a>2?n[a-2]:void 0,u=a>2?n[2]:void 0,l=a>1?n[a-1]:void 0;for("function"==typeof s?(s=o(s,l,5),a-=2):(s="function"==typeof l?l:void 0,a-=s?1:0),u&&i(n[0],n[1],u)&&(s=3>a?void 0:s,a=1);++r<a;){var c=n[r];c&&e(t,c,s)}return t})}var o=n(38),i=n(52),a=n(85);e.exports=r},function(e,t){function n(e,t){if("function"!=typeof e)throw new TypeError(r);return t=o(void 0===t?e.length-1:+t||0,0),function(){for(var n=arguments,r=-1,i=o(n.length-t,0),a=Array(i);++r<i;)a[r]=n[t+r];switch(t){case 0:return e.call(this,a);case 1:return e.call(this,n[0],a);case 2:return e.call(this,n[0],n[1],a)}var s=Array(t+1);for(r=-1;++r<t;)s[r]=n[r];return s[t]=a,e.apply(this,s)}}var r="Expected a function",o=Math.max;e.exports=n},function(e,t,n){"use strict";function r(){}e.exports=r;var o=n(6),i=n(87).EventEmitter;o(r,i),r.prototype.stop=function(){this._stopped=!0,this._clean()},r.prototype._end=function(){this.emit("end"),this._clean()},r.prototype._error=function(e){this.emit("error",e),this._clean()},r.prototype._result=function(e){this.emit("result",e)},r.prototype._clean=function(){this.removeAllListeners("stop"),this.removeAllListeners("end"),this.removeAllListeners("error"),this.removeAllListeners("result")}},function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function o(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function a(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!o(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,o,s,u,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[e],a(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),n.apply(this,s)}else if(i(n))for(s=Array.prototype.slice.call(arguments,1),l=n.slice(),o=l.length,u=0;o>u;u++)l[u].apply(this,s);return!0},n.prototype.addListener=function(e,t){var o;if(!r(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?i(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,i(this._events[e])&&!this._events[e].warned&&(o=a(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,o&&o>0&&this._events[e].length>o&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),o||(o=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var o=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,o,a,s;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],a=n.length,o=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(s=a;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){o=s;break}if(0>o)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,n){"use strict";function r(e,t){return e+=/\?/.test(e)?"&":"?",e+o.encode(t)}e.exports=r;var o=n(89)},function(e,t,n){"use strict";t.decode=t.parse=n(90),t.encode=t.stringify=n(91)},function(e,t){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,r,o){t=t||"&",r=r||"=";var i={};if("string"!=typeof e||0===e.length)return i;var a=/\+/g;e=e.split(t);var s=1e3;o&&"number"==typeof o.maxKeys&&(s=o.maxKeys);var u=e.length;s>0&&u>s&&(u=s);for(var l=0;u>l;++l){var c,p,f,d,h=e[l].replace(a,"%20"),m=h.indexOf(r);m>=0?(c=h.substr(0,m),p=h.substr(m+1)):(c=h,p=""),f=decodeURIComponent(c),d=decodeURIComponent(p),n(i,f)?Array.isArray(i[f])?i[f].push(d):i[f]=[i[f],d]:i[f]=d}return i}},function(e,t){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,r,o){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map(function(o){var i=encodeURIComponent(n(o))+r;return Array.isArray(e[o])?e[o].map(function(e){return i+encodeURIComponent(n(e))}).join(t):i+encodeURIComponent(n(e[o]))}).join(t):o?encodeURIComponent(n(o))+r+encodeURIComponent(n(e)):""}},function(e,t,n){"use strict";function r(e,t,n){function r(){t.debug("JSONP: success"),m||p||(m=!0,c||(t.debug("JSONP: Fail. Script loaded but did not call the callback"),s(),n(new o.JSONPScriptFail)))}function a(){("loaded"===this.readyState||"complete"===this.readyState)&&r()}function s(){clearTimeout(v),d.onload=null,d.onreadystatechange=null,d.onerror=null,f.removeChild(d);try{delete window[h],delete window[h+"_loaded"]}catch(e){window[h]=null,window[h+"_loaded"]=null}}function u(){t.debug("JSONP: Script timeout"),p=!0,s(),n(new o.RequestTimeout)}function l(){t.debug("JSONP: Script error"),m||p||(s(),n(new o.JSONPScriptError))}if("GET"!==t.method)return void n(new Error("Method "+t.method+" "+e+" is not supported by JSONP."));t.debug("JSONP: start");var c=!1,p=!1;i+=1;var f=document.getElementsByTagName("head")[0],d=document.createElement("script"),h="algoliaJSONP_"+i,m=!1;window[h]=function(e){try{delete window[h]}catch(t){window[h]=void 0}p||(c=!0,s(),n(null,{body:e}))},e+="&callback="+h,t.jsonBody&&t.jsonBody.params&&(e+="&"+t.jsonBody.params);var v=setTimeout(u,t.timeout);d.onreadystatechange=a,d.onload=r,d.onerror=l,d.async=!0,d.defer=!0,d.src=e,f.appendChild(d)}e.exports=r;var o=n(13),i=0},function(e,t,n){function r(e,t,n){return"function"==typeof t?o(e,!0,i(t,n,3)):o(e,!0)}var o=n(44),i=n(38);e.exports=r},function(e,t){"use strict";function n(){var e=window.document.location.protocol;return"http:"!==e&&"https:"!==e&&(e="http:"),e}e.exports=n},function(e,t){"use strict";e.exports="3.11.0"},function(e,t,n){"use strict";function r(e,t,n){return new o(e,t,n)}var o=n(97),i=n(98),a=n(141);r.version=n(210),r.AlgoliaSearchHelper=o,r.SearchParameters=i,r.SearchResults=a,r.url=n(200),e.exports=r},function(e,t,n){"use strict";function r(e,t,n){this.client=e;var r=n||{};r.index=t,this.state=o.make(r),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1}var o=n(98),i=n(141),a=n(195),s=n(196),u=n(87),l=n(14),c=n(53),p=n(199),f=n(124),d=n(188),h=n(200);s.inherits(r,u.EventEmitter),r.prototype.search=function(){return this._search(),this},r.prototype.searchOnce=function(e,t){var n=this.state.setQueryParameters(e),r=a._getQueries(n.index,n);return t?this.client.search(r,function(e,r){t(e,new i(n,r),n)}):this.client.search(r).then(function(e){return{content:new i(n,e),state:n}})},r.prototype.setQuery=function(e){return this.state=this.state.setQuery(e),this._change(),this},r.prototype.clearRefinements=function(e){return this.state=this.state.clearRefinements(e),this._change(),this},r.prototype.clearTags=function(){return this.state=this.state.clearTags(),this._change(),this},r.prototype.addDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.addDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.addNumericRefinement=function(e,t,n){return this.state=this.state.addNumericRefinement(e,t,n),this._change(),this},r.prototype.addFacetRefinement=function(e,t){return this.state=this.state.addFacetRefinement(e,t),this._change(),this},r.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},r.prototype.addFacetExclusion=function(e,t){return this.state=this.state.addExcludeRefinement(e,t),this._change(),this},r.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},r.prototype.addTag=function(e){return this.state=this.state.addTagRefinement(e),this._change(),this},r.prototype.removeNumericRefinement=function(e,t,n){return this.state=this.state.removeNumericRefinement(e,t,n),this._change(),this},r.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.removeDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.removeFacetRefinement=function(e,t){return this.state=this.state.removeFacetRefinement(e,t),this._change(),this},r.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},r.prototype.removeFacetExclusion=function(e,t){return this.state=this.state.removeExcludeRefinement(e,t),this._change(),this},r.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},r.prototype.removeTag=function(e){return this.state=this.state.removeTagRefinement(e), this._change(),this},r.prototype.toggleFacetExclusion=function(e,t){return this.state=this.state.toggleExcludeFacetRefinement(e,t),this._change(),this},r.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},r.prototype.toggleRefinement=function(e,t){return this.state=this.state.toggleRefinement(e,t),this._change(),this},r.prototype.toggleRefine=function(){return this.toggleRefinement.apply(this,arguments)},r.prototype.toggleTag=function(e){return this.state=this.state.toggleTagRefinement(e),this._change(),this},r.prototype.nextPage=function(){return this.setCurrentPage(this.state.page+1)},r.prototype.previousPage=function(){return this.setCurrentPage(this.state.page-1)},r.prototype.setCurrentPage=function(e){if(0>e)throw new Error("Page requested below 0.");return this.state=this.state.setPage(e),this._change(),this},r.prototype.setIndex=function(e){return this.state=this.state.setIndex(e),this._change(),this},r.prototype.setQueryParameter=function(e,t){var n=this.state.setQueryParameter(e,t);return this.state===n?this:(this.state=n,this._change(),this)},r.prototype.setState=function(e){return this.state=new o(e),this._change(),this},r.prototype.getState=function(e){return void 0===e?this.state:this.state.filter(e)},r.prototype.getStateAsQueryString=function(e){var t=e&&e.filters||["query","attribute:*"],n=this.getState(t);return h.getQueryStringFromState(n,e)},r.getConfigurationFromQueryString=h.getStateFromQueryString,r.getForeignConfigurationInQueryString=h.getUnrecognizedParametersInQueryString,r.prototype.setStateFromQueryString=function(e,t){var n=t&&t.triggerChange||!1,r=h.getStateFromQueryString(e,t),o=this.state.setQueryParameters(r);n?this.setState(o):this.overrideStateWithoutTriggeringChangeEvent(o)},r.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new o(e),this},r.prototype.isRefined=function(e,t){if(this.state.isConjunctiveFacet(e))return this.state.isFacetRefined(e,t);if(this.state.isDisjunctiveFacet(e))return this.state.isDisjunctiveFacetRefined(e,t);throw new Error(e+" is not properly defined in this helper configuration(use the facets or disjunctiveFacets keys to configure it)")},r.prototype.hasRefinements=function(e){return f(this.state.getNumericRefinements(e))?this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):this.state.isHierarchicalFacet(e)?this.state.isHierarchicalFacetRefined(e):!1:!0},r.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},r.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},r.prototype.hasTag=function(e){return this.state.isTagRefined(e)},r.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},r.prototype.getIndex=function(){return this.state.index},r.prototype.getCurrentPage=function(){return this.state.page},r.prototype.getTags=function(){return this.state.tagRefinements},r.prototype.getQueryParameter=function(e){return this.state.getQueryParameter(e)},r.prototype.getRefinements=function(e){var t=[];if(this.state.isConjunctiveFacet(e)){var n=this.state.getConjunctiveRefinements(e);l(n,function(e){t.push({value:e,type:"conjunctive"})});var r=this.state.getExcludeRefinements(e);l(r,function(e){t.push({value:e,type:"exclude"})})}else if(this.state.isDisjunctiveFacet(e)){var o=this.state.getDisjunctiveRefinements(e);l(o,function(e){t.push({value:e,type:"disjunctive"})})}var i=this.state.getNumericRefinements(e);return l(i,function(e,n){t.push({value:e,operator:n,type:"numeric"})}),t},r.prototype.getNumericRefinement=function(e,t){return this.state.getNumericRefinement(e,t)},r.prototype.getHierarchicalFacetBreadcrumb=function(e){return c(this.state.getHierarchicalRefinement(e)[0].split(this.state._getHierarchicalFacetSeparator(this.state.getHierarchicalFacetByName(e))),function(e){return d(e)})},r.prototype._search=function(){var e=this.state,t=a._getQueries(e.index,e);this.emit("search",e,this.lastResults),this.client.search(t,p(this._handleResponse,this,e,this._queryId++))},r.prototype._handleResponse=function(e,t,n,r){if(!(t<this._lastQueryIdReceived)){if(this._lastQueryIdReceived=t,n)return void this.emit("error",n);var o=this.lastResults=new i(e,r);this.emit("result",o,e)}},r.prototype.containsRefinement=function(e,t,n,r){return e||0!==t.length||0!==n.length||0!==r.length},r.prototype._hasDisjunctiveRefinements=function(e){return this.state.disjunctiveRefinements[e]&&this.state.disjunctiveRefinements[e].length>0},r.prototype._change=function(){this.emit("change",this.state,this.lastResults)},e.exports=r},function(e,t,n){"use strict";function r(e){var t=e?r._parseNumbers(e):{};this.index=t.index||"",this.query=t.query||"",this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{},this.numericFilters=t.numericFilters,this.tagFilters=t.tagFilters,this.optionalTagFilters=t.optionalTagFilters,this.optionalFacetFilters=t.optionalFacetFilters,this.hitsPerPage=t.hitsPerPage,this.maxValuesPerFacet=t.maxValuesPerFacet,this.page=t.page||0,this.queryType=t.queryType,this.typoTolerance=t.typoTolerance,this.minWordSizefor1Typo=t.minWordSizefor1Typo,this.minWordSizefor2Typos=t.minWordSizefor2Typos,this.minProximity=t.minProximity,this.allowTyposOnNumericTokens=t.allowTyposOnNumericTokens,this.ignorePlurals=t.ignorePlurals,this.restrictSearchableAttributes=t.restrictSearchableAttributes,this.advancedSyntax=t.advancedSyntax,this.analytics=t.analytics,this.analyticsTags=t.analyticsTags,this.synonyms=t.synonyms,this.replaceSynonymsInHighlight=t.replaceSynonymsInHighlight,this.optionalWords=t.optionalWords,this.removeWordsIfNoResults=t.removeWordsIfNoResults,this.attributesToRetrieve=t.attributesToRetrieve,this.attributesToHighlight=t.attributesToHighlight,this.highlightPreTag=t.highlightPreTag,this.highlightPostTag=t.highlightPostTag,this.attributesToSnippet=t.attributesToSnippet,this.getRankingInfo=t.getRankingInfo,this.distinct=t.distinct,this.aroundLatLng=t.aroundLatLng,this.aroundLatLngViaIP=t.aroundLatLngViaIP,this.aroundRadius=t.aroundRadius,this.minimumAroundRadius=t.minimumAroundRadius,this.aroundPrecision=t.aroundPrecision,this.insideBoundingBox=t.insideBoundingBox,this.insidePolygon=t.insidePolygon,this.snippetEllipsisText=t.snippetEllipsisText,this.disableExactOnAttributes=t.disableExactOnAttributes,this.enableExactOnSingleWordQuery=t.enableExactOnSingleWordQuery,this.offset=t.offset,this.length=t.length,a(t,function(e,t){if(!this.hasOwnProperty(t)){var n="Unsupported SearchParameter: `"+t+"` (this will throw in the next version)";window?window.console&&window.console.error(n):console.error(n)}},this)}var o=n(22),i=n(99),a=n(106),s=n(14),u=n(108),l=n(53),c=n(111),p=n(115),f=n(121),d=n(33),h=n(124),m=n(126),v=n(125),g=n(127),y=n(25),b=n(128),_=n(132),x=n(133),P=n(78),C=n(138),w=n(139),R=n(140);r.PARAMETERS=o(new r),r._parseNumbers=function(e){var t={},n=["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet","distinct","minimumAroundRadius","hitsPerPage","minProximity"];if(s(n,function(n){var r=e[n];v(r)&&(t[n]=parseFloat(e[n]))}),e.numericRefinements){var r={};s(e.numericRefinements,function(e,t){r[t]={},s(e,function(e,n){var o=l(e,function(e){return d(e)?l(e,function(e){return v(e)?parseFloat(e):e}):v(e)?parseFloat(e):e});r[t][n]=o})}),t.numericRefinements=r}return P({},e,t)},r.make=function(e){var t=new r(e);return s(e.hierarchicalFacets,function(e){if(e.rootPath){var n=t.getHierarchicalRefinement(e.name);n.length>0&&0!==n[0].indexOf(e.rootPath)&&(t=t.clearRefinements(e.name)),n=t.getHierarchicalRefinement(e.name),0===n.length&&(t=t.toggleHierarchicalFacetRefinement(e.name,e.rootPath))}}),C(t)},r.validate=function(e,t){var n=t||{},r=o(n),i=u(r,function(t){return!e.hasOwnProperty(t)});return 1===i.length?new Error("Property "+i[0]+" is not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)"):i.length>1?new Error("Properties "+i.join(" ")+" are not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)"):e.tagFilters&&n.tagRefinements&&n.tagRefinements.length>0?new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method."):e.tagRefinements.length>0&&n.tagFilters?new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method."):e.numericFilters&&n.numericRefinements&&!h(n.numericRefinements)?new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):!h(e.numericRefinements)&&n.numericFilters?new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):null},r.prototype={constructor:r,clearRefinements:function(e){var t=R.clearRefinement;return this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(e),facetsRefinements:t(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:t(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:t(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:t(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")})},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({page:0,tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e,page:0})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e,page:0})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e,page:0})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e,page:0})},addNumericRefinement:function(e,t,n){var r;if(g(n))r=n;else if(v(n))r=parseFloat(n);else{if(!d(n))throw new Error("The value should be a number, a parseable string or an array of those.");r=l(n,function(e){return v(e)?parseFloat(e):e})}if(this.isNumericRefined(e,t,r))return this;var o=P({},this.numericRefinements);return o[e]=P({},o[e]),o[e][t]?(o[e][t]=o[e][t].slice(),o[e][t].push(r)):o[e][t]=[r],this.setQueryParameters({page:0,numericRefinements:o})},getConjunctiveRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsExcludes[e]||[]},removeNumericRefinement:function(e,t,n){return void 0!==n?this.isNumericRefined(e,t,n)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(r,o){return o===e&&r.op===t&&r.val===n})}):this:void 0!==t?this.isNumericRefined(e,t)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(n,r){return r===e&&n.op===t})}):this:this.isNumericRefined(e)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(t,n){return n===e})}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(e){return m(e)?{}:v(e)?p(this.numericRefinements,e):y(e)?c(this.numericRefinements,function(t,n,r){var o={};return s(n,function(t,n){var i=[];s(t,function(t){var o=e({val:t,op:n},r,"numeric");o||i.push(t)}),h(i)||(o[n]=i)}),h(o)||(t[r]=o),t},{}):void 0},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return R.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({page:0,facetsRefinements:R.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return R.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({page:0,facetsExcludes:R.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return R.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({page:0,disjunctiveFacetsRefinements:R.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={page:0,tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return R.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({page:0,facetsRefinements:R.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return R.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({page:0,facetsExcludes:R.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return R.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({page:0,disjunctiveFacetsRefinements:R.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(e){if(!this.isTagRefined(e))return this;var t={page:0,tagRefinements:u(this.tagRefinements,function(t){return t!==e})};return this.setQueryParameters(t)},toggleRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({page:0,facetsRefinements:R.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({page:0,facetsExcludes:R.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({page:0,disjunctiveFacetsRefinements:R.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),r={},o=void 0!==this.hierarchicalFacetsRefinements[e]&&this.hierarchicalFacetsRefinements[e].length>0&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+n));return o?-1===t.indexOf(n)?r[e]=[]:r[e]=[t.slice(0,t.lastIndexOf(n))]:r[e]=[t],this.setQueryParameters({page:0,hierarchicalFacetsRefinements:x({},r,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return f(this.disjunctiveFacets,e)>-1},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return f(this.facets,e)>-1},isFacetRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return R.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return R.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return R.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this.getHierarchicalRefinement(e);return t?-1!==f(n,t):n.length>0},isNumericRefined:function(e,t,n){if(m(n)&&m(t))return!!this.numericRefinements[e];if(m(n))return this.numericRefinements[e]&&!m(this.numericRefinements[e][t]);var r=parseFloat(n);return this.numericRefinements[e]&&!m(this.numericRefinements[e][t])&&-1!==f(this.numericRefinements[e][t],r)},isTagRefined:function(e){return-1!==f(this.tagRefinements,e)},getRefinedDisjunctiveFacets:function(){var e=i(o(this.numericRefinements),this.disjunctiveFacets);return o(this.disjunctiveFacetsRefinements).concat(e).concat(this.getRefinedHierarchicalFacets())},getRefinedHierarchicalFacets:function(){return i(_(this.hierarchicalFacets,"name"),o(this.hierarchicalFacetsRefinements))},getUnrefinedDisjunctiveFacets:function(){var e=this.getRefinedDisjunctiveFacets();return u(this.disjunctiveFacets,function(t){return-1===f(e,t)})},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacets","hierarchicalFacetsRefinements"],getQueryParams:function(){var e=this.managedParameters,t={};return a(this,function(n,r){-1===f(e,r)&&void 0!==n&&(t[r]=n)}),t},getQueryParameter:function(e){if(!this.hasOwnProperty(e))throw new Error("Parameter '"+e+"' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)");return this[e]},setQueryParameter:function(e,t){if(this[e]===t)return this;var n={};return n[e]=t,this.setQueryParameters(n)},setQueryParameters:function(e){var t=r.validate(this,e);if(t)throw t;var n=r._parseNumbers(e);return this.mutateMe(function(t){var r=o(e);return s(r,function(e){t[e]=n[e]}),t})},filter:function(e){return w(this,e)},mutateMe:function(e){var t=new this.constructor(this);return e(t,this),C(t)},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},_getHierarchicalRootPath:function(e){return e.rootPath||null},_getHierarchicalShowParentLevel:function(e){return"boolean"==typeof e.showParentLevel?e.showParentLevel:!0},getHierarchicalFacetByName:function(e){return b(this.hierarchicalFacets,{name:e})}},e.exports=r},function(e,t,n){var r=n(100),o=n(102),i=n(103),a=n(27),s=n(85),u=s(function(e){for(var t=e.length,n=t,s=Array(h),u=r,l=!0,c=[];n--;){var p=e[n]=a(p=e[n])?p:[];s[n]=l&&p.length>=120?i(n&&p):null}var f=e[0],d=-1,h=f?f.length:0,m=s[0];e:for(;++d<h;)if(p=f[d],(m?o(m,p):u(c,p,0))<0){for(var n=t;--n;){var v=s[n];if((v?o(v,p):u(e[n],p,0))<0)continue e}m&&m.push(p),c.push(p)}return c});e.exports=u},function(e,t,n){function r(e,t,n){if(t!==t)return o(e,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}var o=n(101);e.exports=r},function(e,t){function n(e,t,n){for(var r=e.length,o=t+(n?0:-1);n?o--:++o<r;){var i=e[o];if(i!==i)return o}return-1}e.exports=n},function(e,t,n){function r(e,t){var n=e.data,r="string"==typeof t||o(t)?n.set.has(t):n.hash[t];return r?0:-1}var o=n(21);e.exports=r},function(e,t,n){(function(t){function r(e){return s&&a?new o(e):null}var o=n(104),i=n(23),a=i(t,"Set"),s=i(Object,"create");e.exports=r}).call(t,function(){return this}())},function(e,t,n){(function(t){function r(e){var t=e?e.length:0;for(this.data={hash:s(null),set:new a};t--;)this.push(e[t])}var o=n(105),i=n(23),a=i(t,"Set"),s=i(Object,"create");r.prototype.push=o,e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e){var t=this.data;"string"==typeof e||o(e)?t.set.add(e):t.hash[e]=!0}var o=n(21);e.exports=r},function(e,t,n){var r=n(17),o=n(107),i=o(r);e.exports=i},function(e,t,n){function r(e){return function(t,n,r){return("function"!=typeof n||void 0!==r)&&(n=o(n,r,3)),e(t,n)}}var o=n(38);e.exports=r},function(e,t,n){function r(e,t,n){var r=s(e)?o:a;return t=i(t,n,3),r(e,t)}var o=n(109),i=n(55),a=n(110),s=n(33);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=e.length,o=-1,i=[];++n<r;){var a=e[n];t(a,n,e)&&(i[++o]=a)}return i}e.exports=n},function(e,t,n){function r(e,t){var n=[];return o(e,function(e,r,o){t(e,r,o)&&n.push(e)}),n}var o=n(16);e.exports=r},function(e,t,n){var r=n(112),o=n(16),i=n(113),a=i(r,o);e.exports=a},function(e,t){function n(e,t,n,r){var o=-1,i=e.length;for(r&&i&&(n=e[++o]);++o<i;)n=t(n,e[o],o,e);return n}e.exports=n},function(e,t,n){function r(e,t){return function(n,r,s,u){var l=arguments.length<3;return"function"==typeof r&&void 0===u&&a(n)?e(n,r,s,l):i(n,o(r,u,4),s,l,t)}}var o=n(55),i=n(114),a=n(33);e.exports=r},function(e,t){function n(e,t,n,r,o){return o(e,function(e,o,i){n=r?(r=!1,e):t(n,e,o,i)}),n}e.exports=n},function(e,t,n){var r=n(54),o=n(116),i=n(117),a=n(38),s=n(35),u=n(119),l=n(120),c=n(85),p=c(function(e,t){if(null==e)return{};if("function"!=typeof t[0]){var t=r(i(t),String);return u(e,o(s(e),t))}var n=a(t[0],t[1],3);return l(e,function(e,t,r){return!n(e,t,r)})});e.exports=p},function(e,t,n){function r(e,t){var n=e?e.length:0,r=[];if(!n)return r;var u=-1,l=o,c=!0,p=c&&t.length>=s?a(t):null,f=t.length;p&&(l=i,c=!1,t=p);e:for(;++u<n;){var d=e[u];if(c&&d===d){for(var h=f;h--;)if(t[h]===d)continue e;r.push(d)}else l(t,d,0)<0&&r.push(d)}return r}var o=n(100),i=n(102),a=n(103),s=200;e.exports=r},function(e,t,n){function r(e,t,n,l){l||(l=[]);for(var c=-1,p=e.length;++c<p;){var f=e[c];u(f)&&s(f)&&(n||a(f)||i(f))?t?r(f,t,n,l):o(l,f):n||(l[l.length]=f)}return l}var o=n(118),i=n(32),a=n(33),s=n(27),u=n(26);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}e.exports=n},function(e,t,n){function r(e,t){e=o(e);for(var n=-1,r=t.length,i={};++n<r;){var a=t[n];a in e&&(i[a]=e[a])}return i}var o=n(20);e.exports=r},function(e,t,n){function r(e,t){var n={};return o(e,function(e,r,o){t(e,r,o)&&(n[r]=e)}),n}var o=n(82);e.exports=r},function(e,t,n){function r(e,t,n){var r=e?e.length:0;if(!r)return-1;if("number"==typeof n)n=0>n?a(r+n,0):n;else if(n){var s=i(e,t);return r>s&&(t===t?t===e[s]:e[s]!==e[s])?s:-1}return o(e,t,n||0)}var o=n(100),i=n(122),a=Math.max;e.exports=r},function(e,t,n){function r(e,t,n){var r=0,a=e?e.length:r;if("number"==typeof t&&t===t&&s>=a){for(;a>r;){var u=r+a>>>1,l=e[u];(n?t>=l:t>l)&&null!==l?r=u+1:a=u}return a}return o(e,t,i,n)}var o=n(123),i=n(39),a=4294967295,s=a>>>1;e.exports=r},function(e,t){function n(e,t,n,i){t=n(t);for(var s=0,u=e?e.length:0,l=t!==t,c=null===t,p=void 0===t;u>s;){var f=r((s+u)/2),d=n(e[f]),h=void 0!==d,m=d===d;if(l)var v=m||i;else v=c?m&&h&&(i||null!=d):p?m&&(i||h):null==d?!1:i?t>=d:t>d;v?s=f+1:u=f}return o(u,a)}var r=Math.floor,o=Math.min,i=4294967295,a=i-1;e.exports=n},function(e,t,n){function r(e){return null==e?!0:a(e)&&(i(e)||l(e)||o(e)||u(e)&&s(e.splice))?!e.length:!c(e).length}var o=n(32),i=n(33),a=n(27),s=n(25),u=n(26),l=n(125),c=n(22);e.exports=r},function(e,t,n){function r(e){return"string"==typeof e||o(e)&&s.call(e)==i}var o=n(26),i="[object String]",a=Object.prototype,s=a.toString;e.exports=r},function(e,t){function n(e){return void 0===e}e.exports=n},function(e,t,n){function r(e){return"number"==typeof e||o(e)&&s.call(e)==i}var o=n(26),i="[object Number]",a=Object.prototype,s=a.toString;e.exports=r},function(e,t,n){var r=n(16),o=n(129),i=o(r);e.exports=i},function(e,t,n){function r(e,t){return function(n,r,u){if(r=o(r,u,3),s(n)){var l=a(n,r,t);return l>-1?n[l]:void 0}return i(n,r,e)}}var o=n(55),i=n(130),a=n(131),s=n(33);e.exports=r},function(e,t){function n(e,t,n,r){var o;return n(e,function(e,n,i){return t(e,n,i)?(o=r?n:e,!1):void 0}),o}e.exports=n},function(e,t){function n(e,t,n){for(var r=e.length,o=n?r:-1;n?o--:++o<r;)if(t(e[o],o,e))return o;return-1}e.exports=n},function(e,t,n){function r(e,t){return o(e,i(t))}var o=n(53),i=n(75);e.exports=r},function(e,t,n){var r=n(134),o=n(136),i=n(137),a=i(r,o);e.exports=a},function(e,t,n){var r=n(135),o=n(46),i=n(84),a=i(function(e,t,n){return n?r(e,t,n):o(e,t)});e.exports=a},function(e,t,n){function r(e,t,n){for(var r=-1,i=o(t),a=i.length;++r<a;){var s=i[r],u=e[s],l=n(u,t[s],s,e,t);(l===l?l===u:u!==u)&&(void 0!==u||s in e)||(e[s]=l)}return e}var o=n(22);e.exports=r},function(e,t){function n(e,t){return void 0===e?t:e}e.exports=n},function(e,t,n){function r(e,t){return o(function(n){var r=n[0];return null==r?r:(n.push(t),e.apply(void 0,n))})}var o=n(85);e.exports=r},function(e,t,n){"use strict";var r=n(14),o=n(39),i=n(21),a=function(e){return i(e)?(r(e,a),Object.isFrozen(e)||Object.freeze(e),e):e};e.exports=Object.freeze?a:o},function(e,t,n){"use strict";function r(e,t){var n={},r=i(t,function(e){return-1!==e.indexOf("attribute:")}),l=a(r,function(e){return e.split(":")[1]});-1===u(l,"*")?o(l,function(t){e.isConjunctiveFacet(t)&&e.isFacetRefined(t)&&(n.facetsRefinements||(n.facetsRefinements={}),n.facetsRefinements[t]=e.facetsRefinements[t]),e.isDisjunctiveFacet(t)&&e.isDisjunctiveFacetRefined(t)&&(n.disjunctiveFacetsRefinements||(n.disjunctiveFacetsRefinements={}),n.disjunctiveFacetsRefinements[t]=e.disjunctiveFacetsRefinements[t]);var r=e.getNumericRefinements(t);s(r)||(n.numericRefinements||(n.numericRefinements={}),n.numericRefinements[t]=e.numericRefinements[t])}):(s(e.numericRefinements)||(n.numericRefinements=e.numericRefinements),s(e.facetsRefinements)||(n.facetsRefinements=e.facetsRefinements),s(e.disjunctiveFacetsRefinements)||(n.disjunctiveFacetsRefinements=e.disjunctiveFacetsRefinements),s(e.hierarchicalFacetsRefinements)||(n.hierarchicalFacetsRefinements=e.hierarchicalFacetsRefinements));var c=i(t,function(e){return-1===e.indexOf("attribute:")});return o(c,function(t){n[t]=e[t]}),n}var o=n(14),i=n(108),a=n(53),s=n(124),u=n(121);e.exports=r},function(e,t,n){"use strict";var r=n(126),o=n(125),i=n(25),a=n(124),s=n(133),u=n(111),l=n(108),c=n(115),p={addRefinement:function(e,t,n){if(p.isRefined(e,t,n))return e;var r=""+n,o=e[t]?e[t].concat(r):[r],i={};return i[t]=o,s({},i,e)},removeRefinement:function(e,t,n){if(r(n))return p.clearRefinement(e,t);var o=""+n;return p.clearRefinement(e,function(e,n){return t===n&&o===e})},toggleRefinement:function(e,t,n){if(r(n))throw new Error("toggleRefinement should be used with a value");return p.isRefined(e,t,n)?p.removeRefinement(e,t,n):p.addRefinement(e,t,n)},clearRefinement:function(e,t,n){return r(t)?{}:o(t)?c(e,t):i(t)?u(e,function(e,r,o){var i=l(r,function(e){return!t(e,o,n)});return a(i)||(e[o]=i),e},{}):void 0},isRefined:function(e,t,o){var i=n(121),a=!!e[t]&&e[t].length>0;if(r(o)||!a)return a;var s=""+o;return-1!==i(e[t],s)}};e.exports=p},function(e,t,n){"use strict";function r(e){var t={};return p(e,function(e,n){t[e]=n}),t}function o(e,t,n){t&&t[n]&&(e.stats=t[n])}function i(e,t){return v(e,function(e){return g(e.attributes,t)})}function a(e,t){var n=t.results[0];this.query=n.query,this.parsedQuery=n.parsedQuery,this.hits=n.hits,this.index=n.index,this.hitsPerPage=n.hitsPerPage,this.nbHits=n.nbHits,this.nbPages=n.nbPages,this.page=n.page,this.processingTimeMS=m(t.results,"processingTimeMS"),this.aroundLatLng=n.aroundLatLng,this.automaticRadius=n.automaticRadius,this.serverUsed=n.serverUsed,this.timeoutCounts=n.timeoutCounts,this.timeoutHits=n.timeoutHits,this.disjunctiveFacets=[],this.hierarchicalFacets=y(e.hierarchicalFacets,function(){return[]}),this.facets=[];var a=e.getRefinedDisjunctiveFacets(),s=r(e.facets),u=r(e.disjunctiveFacets),l=1;p(n.facets,function(t,r){var a=i(e.hierarchicalFacets,r);if(a){var l=a.attributes.indexOf(r);this.hierarchicalFacets[h(e.hierarchicalFacets,{name:a.name})][l]={attribute:r,data:t,exhaustive:n.exhaustiveFacetsCount}}else{var c,p=-1!==d(e.disjunctiveFacets,r),f=-1!==d(e.facets,r);p&&(c=u[r],this.disjunctiveFacets[c]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},o(this.disjunctiveFacets[c],n.facets_stats,r)),f&&(c=s[r],this.facets[c]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},o(this.facets[c],n.facets_stats,r))}},this),this.hierarchicalFacets=f(this.hierarchicalFacets),p(a,function(r){var i=t.results[l],a=e.getHierarchicalFacetByName(r);p(i.facets,function(t,r){var s;if(a){s=h(e.hierarchicalFacets,{name:a.name});var l=h(this.hierarchicalFacets[s],{attribute:r});if(-1===l)return;this.hierarchicalFacets[s][l].data=x({},this.hierarchicalFacets[s][l].data,t)}else{s=u[r];var c=n.facets&&n.facets[r]||{};this.disjunctiveFacets[s]={name:r,data:_({},t,c),exhaustive:i.exhaustiveFacetsCount},o(this.disjunctiveFacets[s],i.facets_stats,r),e.disjunctiveFacetsRefinements[r]&&p(e.disjunctiveFacetsRefinements[r],function(t){!this.disjunctiveFacets[s].data[t]&&d(e.disjunctiveFacetsRefinements[r],t)>-1&&(this.disjunctiveFacets[s].data[t]=0)},this)}},this),l++},this),p(e.getRefinedHierarchicalFacets(),function(n){var r=e.getHierarchicalFacetByName(n),o=e._getHierarchicalFacetSeparator(r),i=e.getHierarchicalRefinement(n);if(!(0===i.length||i[0].split(o).length<2)){var a=t.results[l];p(a.facets,function(t,n){var a=h(e.hierarchicalFacets,{name:r.name}),s=h(this.hierarchicalFacets[a],{attribute:n});if(-1!==s){var u={};if(i.length>0){var l=i[0].split(o)[0];u[l]=this.hierarchicalFacets[a][s].data[l]}this.hierarchicalFacets[a][s].data=_(u,t,this.hierarchicalFacets[a][s].data)}},this),l++}},this),p(e.facetsExcludes,function(e,t){var r=s[t];this.facets[r]={name:t,data:n.facets[t],exhaustive:n.exhaustiveFacetsCount},p(e,function(e){this.facets[r]=this.facets[r]||{name:t},this.facets[r].data=this.facets[r].data||{},this.facets[r].data[e]=0},this)},this),this.hierarchicalFacets=y(this.hierarchicalFacets,T(e)),this.facets=f(this.facets),this.disjunctiveFacets=f(this.disjunctiveFacets),this._state=e}function s(e,t){var n={name:t};if(e._state.isConjunctiveFacet(t)){var r=v(e.facets,n);return r?y(r.data,function(n,r){return{name:r,count:n,isRefined:e._state.isFacetRefined(t,r)}; }):[]}if(e._state.isDisjunctiveFacet(t)){var o=v(e.disjunctiveFacets,n);return o?y(o.data,function(n,r){return{name:r,count:n,isRefined:e._state.isDisjunctiveFacetRefined(t,r)}}):[]}return e._state.isHierarchicalFacet(t)?v(e.hierarchicalFacets,n):void 0}function u(e,t){if(!t.data||0===t.data.length)return t;var n=y(t.data,w(u,e)),r=e(n),o=x({},t,{data:r});return o}function l(e,t){return t.sort(e)}function c(e,t){var n=v(e,{name:t});return n&&n.stats}var p=n(14),f=n(142),d=n(121),h=n(143),m=n(145),v=n(128),g=n(152),y=n(53),b=n(153),_=n(133),x=n(78),P=n(33),C=n(25),w=n(158),R=n(185),E=n(186),T=n(187);a.prototype.getFacetByName=function(e){var t={name:e};return v(this.facets,t)||v(this.disjunctiveFacets,t)||v(this.hierarchicalFacets,t)},a.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],a.prototype.getFacetValues=function(e,t){var n=s(this,e);if(!n)throw new Error(e+" is not a retrieved facet.");var r=_({},t,{sortBy:a.DEFAULT_SORT});if(P(r.sortBy)){var o=E(r.sortBy);return P(n)?b(n,o[0],o[1]):u(R(b,o[0],o[1]),n)}if(C(r.sortBy))return P(n)?n.sort(r.sortBy):u(w(l,r.sortBy),n);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")},a.prototype.getFacetStats=function(e){if(this._state.isConjunctiveFacet(e))return c(this.facets,e);if(this._state.isDisjunctiveFacet(e))return c(this.disjunctiveFacets,e);throw new Error(e+" is not present in `facets` or `disjunctiveFacets`")},e.exports=a},function(e,t){function n(e){for(var t=-1,n=e?e.length:0,r=-1,o=[];++t<n;){var i=e[t];i&&(o[++r]=i)}return o}e.exports=n},function(e,t,n){var r=n(144),o=r();e.exports=o},function(e,t,n){function r(e){return function(t,n,r){return t&&t.length?(n=o(n,r,3),i(t,n,e)):-1}}var o=n(55),i=n(131);e.exports=r},function(e,t,n){e.exports=n(146)},function(e,t,n){function r(e,t,n){return n&&u(e,t,n)&&(t=void 0),t=i(t,n,3),1==t.length?o(s(e)?e:l(e),t):a(e,t)}var o=n(147),i=n(55),a=n(148),s=n(33),u=n(52),l=n(149);e.exports=r},function(e,t){function n(e,t){for(var n=e.length,r=0;n--;)r+=+t(e[n])||0;return r}e.exports=n},function(e,t,n){function r(e,t){var n=0;return o(e,function(e,r,o){n+=+t(e,r,o)||0}),n}var o=n(16);e.exports=r},function(e,t,n){function r(e){return null==e?[]:o(e)?i(e)?e:Object(e):a(e)}var o=n(27),i=n(21),a=n(150);e.exports=r},function(e,t,n){function r(e){return o(e,i(e))}var o=n(151),i=n(22);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=t.length,o=Array(r);++n<r;)o[n]=e[t[n]];return o}e.exports=n},function(e,t,n){function r(e,t,n,r){var f=e?i(e):0;return u(f)||(e=c(e),f=e.length),n="number"!=typeof n||r&&s(t,n,r)?0:0>n?p(f+n,0):n||0,"string"==typeof e||!a(e)&&l(e)?f>=n&&e.indexOf(t,n)>-1:!!f&&o(e,t,n)>-1}var o=n(100),i=n(28),a=n(33),s=n(52),u=n(30),l=n(125),c=n(150),p=Math.max;e.exports=r},function(e,t,n){function r(e,t,n,r){return null==e?[]:(r&&a(t,n,r)&&(n=void 0),i(t)||(t=null==t?[]:[t]),i(n)||(n=null==n?[]:[n]),o(e,t,n))}var o=n(154),i=n(33),a=n(52);e.exports=r},function(e,t,n){function r(e,t,n){var r=-1;t=o(t,function(e){return i(e)});var l=a(e,function(e){var n=o(t,function(t){return t(e)});return{criteria:n,index:++r,value:e}});return s(l,function(e,t){return u(e,t,n)})}var o=n(54),i=n(55),a=n(77),s=n(155),u=n(156);e.exports=r},function(e,t){function n(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}e.exports=n},function(e,t,n){function r(e,t,n){for(var r=-1,i=e.criteria,a=t.criteria,s=i.length,u=n.length;++r<s;){var l=o(i[r],a[r]);if(l){if(r>=u)return l;var c=n[r];return l*("asc"===c||c===!0?1:-1)}}return e.index-t.index}var o=n(157);e.exports=r},function(e,t){function n(e,t){if(e!==t){var n=null===e,r=void 0===e,o=e===e,i=null===t,a=void 0===t,s=t===t;if(e>t&&!i||!o||n&&!a&&s||r&&s)return 1;if(t>e&&!n||!s||i&&!r&&o||a&&o)return-1}return 0}e.exports=n},function(e,t,n){var r=n(159),o=32,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){function r(e){var t=a(function(n,r){var a=i(r,t.placeholder);return o(n,e,void 0,r,a)});return t}var o=n(160),i=n(180),a=n(85);e.exports=r},function(e,t,n){function r(e,t,n,r,g,y,b,_){var x=t&f;if(!x&&"function"!=typeof e)throw new TypeError(m);var P=r?r.length:0;if(P||(t&=~(d|h),r=g=void 0),P-=g?g.length:0,t&h){var C=r,w=g;r=g=void 0}var R=x?void 0:u(e),E=[e,t,n,r,g,C,w,y,b,_];if(R&&(l(E,R),t=E[1],_=E[9]),E[9]=null==_?x?0:e.length:v(_-P,0)||0,t==p)var T=i(E[0],E[2]);else T=t!=d&&t!=(p|d)||E[4].length?a.apply(void 0,E):s.apply(void 0,E);var O=R?o:c;return O(T,E)}var o=n(161),i=n(163),a=n(166),s=n(183),u=n(172),l=n(184),c=n(181),p=1,f=2,d=32,h=64,m="Expected a function",v=Math.max;e.exports=r},function(e,t,n){var r=n(39),o=n(162),i=o?function(e,t){return o.set(e,t),e}:r;e.exports=i},function(e,t,n){(function(t){var r=n(23),o=r(t,"WeakMap"),i=o&&new o;e.exports=i}).call(t,function(){return this}())},function(e,t,n){(function(t){function r(e,n){function r(){var o=this&&this!==t&&this instanceof r?i:e;return o.apply(n,arguments)}var i=o(e);return r}var o=n(164);e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var n=o(e.prototype),r=e.apply(n,t);return i(r)?r:n}}var o=n(165),i=n(21);e.exports=r},function(e,t,n){var r=n(21),o=function(){function e(){}return function(t){if(r(t)){e.prototype=t;var n=new e;e.prototype=void 0}return n||{}}}();e.exports=o},function(e,t,n){(function(t){function r(e,n,x,P,C,w,R,E,T,O){function S(){for(var h=arguments.length,m=h,v=Array(h);m--;)v[m]=arguments[m];if(P&&(v=i(v,P,C)),w&&(v=a(v,w,R)),M||I){var b=S.placeholder,F=c(v,b);if(h-=F.length,O>h){var L=E?o(E):void 0,U=_(O-h,0),H=M?F:void 0,B=M?void 0:F,q=M?v:void 0,V=M?void 0:v;n|=M?g:y,n&=~(M?y:g),D||(n&=~(f|d));var W=[e,n,x,q,H,V,B,L,T,U],K=r.apply(void 0,W);return u(e)&&p(K,W),K.placeholder=b,K}}var Q=N?x:this,z=k?Q[e]:e;return E&&(v=l(v,E)),j&&T<v.length&&(v.length=T),this&&this!==t&&this instanceof S&&(z=A||s(e)),z.apply(Q,v)}var j=n&b,N=n&f,k=n&d,M=n&m,D=n&h,I=n&v,A=k?void 0:s(e);return S}var o=n(45),i=n(167),a=n(168),s=n(164),u=n(169),l=n(179),c=n(180),p=n(181),f=1,d=2,h=4,m=8,v=16,g=32,y=64,b=128,_=Math.max;e.exports=r}).call(t,function(){return this}())},function(e,t){function n(e,t,n){for(var o=n.length,i=-1,a=r(e.length-o,0),s=-1,u=t.length,l=Array(u+a);++s<u;)l[s]=t[s];for(;++i<o;)l[n[i]]=e[i];for(;a--;)l[s++]=e[i++];return l}var r=Math.max;e.exports=n},function(e,t){function n(e,t,n){for(var o=-1,i=n.length,a=-1,s=r(e.length-i,0),u=-1,l=t.length,c=Array(s+l);++a<s;)c[a]=e[a];for(var p=a;++u<l;)c[p+u]=t[u];for(;++o<i;)c[p+n[o]]=e[a++];return c}var r=Math.max;e.exports=n},function(e,t,n){function r(e){var t=a(e),n=s[t];if("function"!=typeof n||!(t in o.prototype))return!1;if(e===n)return!0;var r=i(n);return!!r&&e===r[0]}var o=n(170),i=n(172),a=n(174),s=n(176);e.exports=r},function(e,t,n){function r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=a,this.__views__=[]}var o=n(165),i=n(171),a=Number.POSITIVE_INFINITY;r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e,t){function n(){}e.exports=n},function(e,t,n){var r=n(162),o=n(173),i=r?function(e){return r.get(e)}:o;e.exports=i},function(e,t){function n(){}e.exports=n},function(e,t,n){function r(e){for(var t=e.name+"",n=o[t],r=n?n.length:0;r--;){var i=n[r],a=i.func;if(null==a||a==e)return i.name}return t}var o=n(175);e.exports=r},function(e,t){var n={};e.exports=n},function(e,t,n){function r(e){if(u(e)&&!s(e)&&!(e instanceof o)){if(e instanceof i)return e;if(p.call(e,"__chain__")&&p.call(e,"__wrapped__"))return l(e)}return new i(e)}var o=n(170),i=n(177),a=n(171),s=n(33),u=n(26),l=n(178),c=Object.prototype,p=c.hasOwnProperty;r.prototype=a.prototype,e.exports=r},function(e,t,n){function r(e,t,n){this.__wrapped__=e,this.__actions__=n||[],this.__chain__=!!t}var o=n(165),i=n(171);r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e,t,n){function r(e){return e instanceof o?e.clone():new i(e.__wrapped__,e.__chain__,a(e.__actions__))}var o=n(170),i=n(177),a=n(45);e.exports=r},function(e,t,n){function r(e,t){for(var n=e.length,r=a(t.length,n),s=o(e);r--;){var u=t[r];e[r]=i(u,n)?s[u]:void 0}return e}var o=n(45),i=n(34),a=Math.min;e.exports=r},function(e,t){function n(e,t){for(var n=-1,o=e.length,i=-1,a=[];++n<o;)e[n]===t&&(e[n]=r,a[++i]=n);return a}var r="__lodash_placeholder__";e.exports=n},function(e,t,n){var r=n(161),o=n(182),i=150,a=16,s=function(){var e=0,t=0;return function(n,s){var u=o(),l=a-(u-t);if(t=u,l>0){if(++e>=i)return n}else e=0;return r(n,s)}}();e.exports=s},function(e,t,n){var r=n(23),o=r(Date,"now"),i=o||function(){return(new Date).getTime()};e.exports=i},function(e,t,n){(function(t){function r(e,n,r,a){function s(){for(var n=-1,o=arguments.length,i=-1,c=a.length,p=Array(c+o);++i<c;)p[i]=a[i];for(;o--;)p[i++]=arguments[++n];var f=this&&this!==t&&this instanceof s?l:e;return f.apply(u?r:this,p)}var u=n&i,l=o(e);return s}var o=n(164),i=1;e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e,t){var n=e[1],r=t[1],m=n|r,v=p>m,g=r==p&&n==c||r==p&&n==f&&e[7].length<=t[8]||r==(p|f)&&n==c;if(!v&&!g)return e;r&u&&(e[2]=t[2],m|=n&u?0:l);var y=t[3];if(y){var b=e[3];e[3]=b?i(b,y,t[4]):o(y),e[4]=b?s(e[3],d):o(t[4])}return y=t[5],y&&(b=e[5],e[5]=b?a(b,y,t[6]):o(y),e[6]=b?s(e[5],d):o(t[6])),y=t[7],y&&(e[7]=o(y)),r&p&&(e[8]=null==e[8]?t[8]:h(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=m,e}var o=n(45),i=n(167),a=n(168),s=n(180),u=1,l=4,c=8,p=128,f=256,d="__lodash_placeholder__",h=Math.min;e.exports=r},function(e,t,n){var r=n(159),o=64,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){"use strict";var r=n(111);e.exports=function(e){return r(e,function(e,t){var n=t.split(":");return e[0].push(n[0]),e[1].push(n[1]),e},[[],[]])}},function(e,t,n){"use strict";function r(e){return function(t,n){var r=e.hierarchicalFacets[n],i=e.hierarchicalFacetsRefinements[r.name]&&e.hierarchicalFacetsRefinements[r.name][0]||"",a=e._getHierarchicalFacetSeparator(r),s=e._getHierarchicalRootPath(r),u=e._getHierarchicalShowParentLevel(r),c=h(e._getHierarchicalFacetSortBy(r)),p=o(c,a,s,u,i),f=t;return s&&(f=t.slice(s.split(a).length)),l(f,p,{name:e.hierarchicalFacets[n].name,count:null,isRefined:!0,path:null,data:null})}}function o(e,t,n,r,o){return function(s,l,p){var h=s;if(p>0){var m=0;for(h=s;p>m;)h=h&&f(h.data,{isRefined:!0}),m++}if(h){var v=i(h.path||n,o,t,n,r);h.data=c(u(d(l.data,v),a(t,o)),e[0],e[1])}return s}}function i(e,t,n,r,o){return function(i,a){return!r||0===a.indexOf(r)&&r!==a?!r&&-1===a.indexOf(n)||r&&a.split(n).length-r.split(n).length===1||-1===a.indexOf(n)&&-1===t.indexOf(n)||0===t.indexOf(a)||0===a.indexOf(e+n)&&(o||0===a.indexOf(t)):!1}}function a(e,t){return function(n,r){return{name:p(s(r.split(e))),path:r,count:n,isRefined:t===r||0===t.indexOf(r+e),data:null}}}e.exports=r;var s=n(72),u=n(53),l=n(111),c=n(153),p=n(188),f=n(128),d=n(194),h=n(186)},function(e,t,n){function r(e,t,n){var r=e;return(e=o(e))?(n?s(r,t,n):null==t)?e.slice(u(e),l(e)+1):(t+="",e.slice(i(e,t),a(e,t)+1)):e}var o=n(74),i=n(189),a=n(190),s=n(52),u=n(191),l=n(193);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=e.length;++n<r&&t.indexOf(e.charAt(n))>-1;);return n}e.exports=n},function(e,t){function n(e,t){for(var n=e.length;n--&&t.indexOf(e.charAt(n))>-1;);return n}e.exports=n},function(e,t,n){function r(e){for(var t=-1,n=e.length;++t<n&&o(e.charCodeAt(t)););return t}var o=n(192);e.exports=r},function(e,t){function n(e){return 160>=e&&e>=9&&13>=e||32==e||160==e||5760==e||6158==e||e>=8192&&(8202>=e||8232==e||8233==e||8239==e||8287==e||12288==e||65279==e)}e.exports=n},function(e,t,n){function r(e){for(var t=e.length;t--&&o(e.charCodeAt(t)););return t}var o=n(192);e.exports=r},function(e,t,n){var r=n(117),o=n(38),i=n(119),a=n(120),s=n(85),u=s(function(e,t){return null==e?{}:"function"==typeof t[0]?a(e,o(t[0],t[1],3)):i(e,r(t))});e.exports=u},function(e,t,n){"use strict";var r=n(14),o=n(53),i=n(111),a=n(78),s=n(33),u={_getQueries:function(e,t){var n=[];return n.push({indexName:e,params:this._getHitsSearchParams(t)}),r(t.getRefinedDisjunctiveFacets(),function(r){n.push({indexName:e,params:this._getDisjunctiveFacetSearchParams(t,r)})},this),r(t.getRefinedHierarchicalFacets(),function(r){var o=t.getHierarchicalFacetByName(r),i=t.getHierarchicalRefinement(r);i.length>0&&i[0].split(t._getHierarchicalFacetSeparator(o)).length>1&&n.push({indexName:e,params:this._getDisjunctiveFacetSearchParams(t,r,!0)})},this),n},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(this._getHitsHierarchicalFacetsAttributes(e)),n=this._getFacetFilters(e),r=this._getNumericFilters(e),o=this._getTagFilters(e),i={facets:t,tagFilters:o};return n.length>0&&(i.facetFilters=n),r.length>0&&(i.numericFilters=r),a(e.getQueryParams(),i)},_getDisjunctiveFacetSearchParams:function(e,t,n){var r=this._getFacetFilters(e,t,n),o=this._getNumericFilters(e,t),i=this._getTagFilters(e),s={hitsPerPage:1,page:0,attributesToRetrieve:[],attributesToHighlight:[],attributesToSnippet:[],tagFilters:i},u=e.getHierarchicalFacetByName(t);return u?s.facets=this._getDisjunctiveHierarchicalFacetAttribute(e,u,n):s.facets=t,o.length>0&&(s.numericFilters=o),r.length>0&&(s.facetFilters=r),a(e.getQueryParams(),s)},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var n=[];return r(e.numericRefinements,function(e,i){r(e,function(e,a){t!==i&&r(e,function(e){if(s(e)){var t=o(e,function(e){return i+a+e});n.push(t)}else n.push(i+a+e)})})}),n},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(e,t,n){var o=[];return r(e.facetsRefinements,function(e,t){r(e,function(e){o.push(t+":"+e)})}),r(e.facetsExcludes,function(e,t){r(e,function(e){o.push(t+":-"+e)})}),r(e.disjunctiveFacetsRefinements,function(e,n){if(n!==t&&e&&0!==e.length){var i=[];r(e,function(e){i.push(n+":"+e)}),o.push(i)}}),r(e.hierarchicalFacetsRefinements,function(r,i){var a=r[0];if(void 0!==a){var s,u,l=e.getHierarchicalFacetByName(i),c=e._getHierarchicalFacetSeparator(l),p=e._getHierarchicalRootPath(l);if(t===i){if(-1===a.indexOf(c)||!p&&n===!0||p&&p.split(c).length===a.split(c).length)return;p?(u=p.split(c).length-1,a=p):(u=a.split(c).length-2,a=a.slice(0,a.lastIndexOf(c))),s=l.attributes[u]}else u=a.split(c).length-1,s=l.attributes[u];s&&o.push([s+":"+a])}}),o},_getHitsHierarchicalFacetsAttributes:function(e){var t=[];return i(e.hierarchicalFacets,function(t,n){var r=e.getHierarchicalRefinement(n.name)[0];if(!r)return t.push(n.attributes[0]),t;var o=r.split(e._getHierarchicalFacetSeparator(n)).length,i=n.attributes.slice(0,o+1);return t.concat(i)},t)},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,n){var r=e._getHierarchicalFacetSeparator(t);if(n===!0){var o=e._getHierarchicalRootPath(t),i=0;return o&&(i=o.split(r).length),[t.attributes[i]]}var a=e.getHierarchicalRefinement(t.name)[0]||"",s=a.split(r).length-1;return t.attributes.slice(0,s+1)}};e.exports=u},function(e,t,n){(function(e,r){function o(e,n){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),m(n)?r.showHidden=n:n&&t._extend(r,n),x(r.showHidden)&&(r.showHidden=!1),x(r.depth)&&(r.depth=2),x(r.colors)&&(r.colors=!1),x(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=i),u(r,e,r.depth)}function i(e,t){var n=o.styles[t];return n?"["+o.colors[n][0]+"m"+e+"["+o.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,n,r){if(e.customInspect&&n&&E(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var o=n.inspect(r,e);return b(o)||(o=u(e,o,r)),o}var i=l(e,n);if(i)return i;var a=Object.keys(n),m=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(n)),R(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(n);if(0===a.length){if(E(n)){var v=n.name?": "+n.name:"";return e.stylize("[Function"+v+"]","special")}if(P(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(w(n))return e.stylize(Date.prototype.toString.call(n),"date");if(R(n))return c(n)}var g="",y=!1,_=["{","}"];if(h(n)&&(y=!0,_=["[","]"]),E(n)){var x=n.name?": "+n.name:"";g=" [Function"+x+"]"}if(P(n)&&(g=" "+RegExp.prototype.toString.call(n)),w(n)&&(g=" "+Date.prototype.toUTCString.call(n)),R(n)&&(g=" "+c(n)),0===a.length&&(!y||0==n.length))return _[0]+g+_[1];if(0>r)return P(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var C;return C=y?p(e,n,r,m,a):a.map(function(t){return f(e,n,r,m,t,y)}),e.seen.pop(),d(C,g,_)}function l(e,t){if(x(t))return e.stylize("undefined","undefined");if(b(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return y(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):v(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function p(e,t,n,r,o){for(var i=[],a=0,s=t.length;s>a;++a)N(t,String(a))?i.push(f(e,t,n,r,String(a),!0)):i.push("");return o.forEach(function(o){o.match(/^\d+$/)||i.push(f(e,t,n,r,o,!0))}),i}function f(e,t,n,r,o,i){var a,s,l;if(l=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]},l.get?s=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(s=e.stylize("[Setter]","special")),N(r,o)||(a="["+o+"]"),s||(e.seen.indexOf(l.value)<0?(s=v(n)?u(e,l.value,null):u(e,l.value,n-1),s.indexOf("\n")>-1&&(s=i?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),x(a)){if(i&&o.match(/^\d+$/))return s;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,n){var r=0,o=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return o>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function h(e){return Array.isArray(e)}function m(e){return"boolean"==typeof e}function v(e){return null===e}function g(e){return null==e}function y(e){return"number"==typeof e}function b(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function x(e){return void 0===e}function P(e){return C(e)&&"[object RegExp]"===O(e)}function C(e){return"object"==typeof e&&null!==e}function w(e){return C(e)&&"[object Date]"===O(e)}function R(e){return C(e)&&("[object Error]"===O(e)||e instanceof Error)}function E(e){return"function"==typeof e}function T(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function O(e){return Object.prototype.toString.call(e)}function S(e){return 10>e?"0"+e.toString(10):e.toString(10)}function j(){var e=new Date,t=[S(e.getHours()),S(e.getMinutes()),S(e.getSeconds())].join(":");return[e.getDate(),I[e.getMonth()],t].join(" ")}function N(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var k=/%[sdj%]/g;t.format=function(e){if(!b(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(o(arguments[n]));return t.join(" ")}for(var n=1,r=arguments,i=r.length,a=String(e).replace(k,function(e){if("%%"===e)return"%";if(n>=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(t){return"[Circular]"}default:return e}}),s=r[n];i>n;s=r[++n])a+=v(s)||!C(s)?" "+s:" "+o(s);return a},t.deprecate=function(n,o){function i(){if(!a){if(r.throwDeprecation)throw new Error(o);r.traceDeprecation?console.trace(o):console.error(o),a=!0}return n.apply(this,arguments)}if(x(e.process))return function(){return t.deprecate(n,o).apply(this,arguments)};if(r.noDeprecation===!0)return n;var a=!1;return i};var M,D={};t.debuglog=function(e){if(x(M)&&(M={NODE_ENV:"production"}.NODE_DEBUG||""),e=e.toUpperCase(),!D[e])if(new RegExp("\\b"+e+"\\b","i").test(M)){var n=r.pid;D[e]=function(){var r=t.format.apply(t,arguments);console.error("%s %d: %s",e,n,r)}}else D[e]=function(){};return D[e]},t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=h,t.isBoolean=m,t.isNull=v,t.isNullOrUndefined=g,t.isNumber=y,t.isString=b,t.isSymbol=_,t.isUndefined=x,t.isRegExp=P,t.isObject=C,t.isDate=w,t.isError=R,t.isFunction=E,t.isPrimitive=T,t.isBuffer=n(197);var I=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.log=function(){console.log("%s - %s",j(),t.format.apply(t,arguments))},t.inherits=n(198),t._extend=function(e,t){if(!t||!C(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(t,function(){return this}(),n(8))},function(e,t){e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){var r=n(160),o=n(180),i=n(85),a=1,s=32,u=i(function(e,t,n){var i=a;if(n.length){var l=o(n,u.placeholder);i|=s}return r(e,i,t,n,l)});u.placeholder={},e.exports=u},function(e,t,n){"use strict";function r(e){return m(e)?d(e,r):v(e)?p(e,r):h(e)?g(e):e}function o(e,t,n){if(null!==e&&(t=t.replace(e,""),n=n.replace(e,"")),-1!==b.indexOf(t)||-1!==b.indexOf(n)){if("q"===t)return-1;if("q"===n)return 1;var r=-1!==y.indexOf(t),o=-1!==y.indexOf(n);if(r&&!o)return 1;if(o&&!r)return-1}return t.localeCompare(n)}var i=n(201),a=n(98),s=n(203),u=n(199),l=n(14),c=n(194),p=n(53),f=n(207),d=n(209),h=n(125),m=n(81),v=n(33),g=n(205).encode,y=["dFR","fR","nR","hFR","tR"],b=i.ENCODED_PARAMETERS;t.getStateFromQueryString=function(e,t){var n=t&&t.prefix||"",r=s.parse(e),o=new RegExp("^"+n),u=f(r,function(e,t){if(n&&o.test(t)){var r=t.replace(o,"");return i.decode(r)}var a=i.decode(t);return a||t}),l=a._parseNumbers(u);return c(l,a.PARAMETERS)},t.getUnrecognizedParametersInQueryString=function(e,t){var n=t&&t.prefix,r={},o=s.parse(e);if(n){var a=new RegExp("^"+n);l(o,function(e,t){a.test(t)||(r[t]=e)})}else l(o,function(e,t){i.decode(t)||(r[t]=e)});return r},t.getQueryStringFromState=function(e,t){var n=t&&t.moreAttributes,a=t&&t.prefix||"",l=r(e),c=f(l,function(e,t){var n=i.encode(t);return a+n}),p=""===a?null:new RegExp("^"+a),d=u(o,null,p);if(n){var h=s.stringify(c,{encode:!1,sort:d}),m=s.stringify(n,{encode:!1});return h?h+"&"+m:m}return s.stringify(c,{encode:!1,sort:d})}},function(e,t,n){"use strict";var r=n(202),o=n(22),i={advancedSyntax:"aS",allowTyposOnNumericTokens:"aTONT",analyticsTags:"aT",analytics:"a",aroundLatLngViaIP:"aLLVIP",aroundLatLng:"aLL",aroundPrecision:"aP",aroundRadius:"aR",attributesToHighlight:"aTH",attributesToRetrieve:"aTR",attributesToSnippet:"aTS",disjunctiveFacetsRefinements:"dFR",disjunctiveFacets:"dF",distinct:"d",facetsExcludes:"fE",facetsRefinements:"fR",facets:"f",getRankingInfo:"gRI",hierarchicalFacetsRefinements:"hFR",hierarchicalFacets:"hF",highlightPostTag:"hPoT",highlightPreTag:"hPrT",hitsPerPage:"hPP",ignorePlurals:"iP",index:"idx",insideBoundingBox:"iBB",insidePolygon:"iPg",length:"l",maxValuesPerFacet:"mVPF",minimumAroundRadius:"mAR",minProximity:"mP",minWordSizefor1Typo:"mWS1T",minWordSizefor2Typos:"mWS2T",numericFilters:"nF",numericRefinements:"nR",offset:"o",optionalWords:"oW",page:"p",queryType:"qT",query:"q",removeWordsIfNoResults:"rWINR",replaceSynonymsInHighlight:"rSIH",restrictSearchableAttributes:"rSA",synonyms:"s",tagFilters:"tF",tagRefinements:"tR",typoTolerance:"tT",optionalTagFilters:"oTF",optionalFacetFilters:"oFF",snippetEllipsisText:"sET",disableExactOnAttributes:"dEOA",enableExactOnSingleWordQuery:"eEOSWQ"},a=r(i);e.exports={ENCODED_PARAMETERS:o(a),decode:function(e){return a[e]},encode:function(e){return i[e]}}},function(e,t,n){function r(e,t,n){n&&o(e,t,n)&&(t=void 0);for(var r=-1,a=i(e),u=a.length,l={};++r<u;){var c=a[r],p=e[c];t?s.call(l,p)?l[p].push(c):l[p]=[c]:l[p]=c}return l}var o=n(52),i=n(22),a=Object.prototype,s=a.hasOwnProperty;e.exports=r},function(e,t,n){var r=n(204),o=n(206);e.exports={stringify:r,parse:o}},function(e,t,n){var r=n(205),o={delimiter:"&",arrayPrefixGenerators:{brackets:function(e,t){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e,t){return e}},strictNullHandling:!1,skipNulls:!1,encode:!0};o.stringify=function(e,t,n,i,a,s,u,l){if("function"==typeof u)e=u(t,e);else if(r.isBuffer(e))e=e.toString();else if(e instanceof Date)e=e.toISOString();else if(null===e){if(i)return s?r.encode(t):t;e=""}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return s?[r.encode(t)+"="+r.encode(e)]:[t+"="+e];var c=[];if("undefined"==typeof e)return c;var p;if(Array.isArray(u))p=u;else{var f=Object.keys(e);p=l?f.sort(l):f}for(var d=0,h=p.length;h>d;++d){var m=p[d];a&&null===e[m]||(c=Array.isArray(e)?c.concat(o.stringify(e[m],n(t,m),n,i,a,s,u)):c.concat(o.stringify(e[m],t+"["+m+"]",n,i,a,s,u)))}return c},e.exports=function(e,t){t=t||{};var n,r,i="undefined"==typeof t.delimiter?o.delimiter:t.delimiter,a="boolean"==typeof t.strictNullHandling?t.strictNullHandling:o.strictNullHandling,s="boolean"==typeof t.skipNulls?t.skipNulls:o.skipNulls,u="boolean"==typeof t.encode?t.encode:o.encode,l="function"==typeof t.sort?t.sort:null;"function"==typeof t.filter?(r=t.filter,e=r("",e)):Array.isArray(t.filter)&&(n=r=t.filter);var c=[];if("object"!=typeof e||null===e)return"";var p;p=t.arrayFormat in o.arrayPrefixGenerators?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":"indices";var f=o.arrayPrefixGenerators[p];n||(n=Object.keys(e)),l&&n.sort(l);for(var d=0,h=n.length;h>d;++d){var m=n[d];s&&null===e[m]||(c=c.concat(o.stringify(e[m],m,f,a,s,u,r,l)))}return c.join(i)}},function(e,t){var n={};n.hexTable=new Array(256);for(var r=0;256>r;++r)n.hexTable[r]="%"+((16>r?"0":"")+r.toString(16)).toUpperCase();t.arrayToObject=function(e,t){for(var n=t.plainObjects?Object.create(null):{},r=0,o=e.length;o>r;++r)"undefined"!=typeof e[r]&&(n[r]=e[r]);return n},t.merge=function(e,n,r){if(!n)return e;if("object"!=typeof n)return Array.isArray(e)?e.push(n):"object"==typeof e?e[n]=!0:e=[e,n],e;if("object"!=typeof e)return e=[e].concat(n);Array.isArray(e)&&!Array.isArray(n)&&(e=t.arrayToObject(e,r));for(var o=Object.keys(n),i=0,a=o.length;a>i;++i){var s=o[i],u=n[s];Object.prototype.hasOwnProperty.call(e,s)?e[s]=t.merge(e[s],u,r):e[s]=u}return e},t.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},t.encode=function(e){if(0===e.length)return e;"string"!=typeof e&&(e=""+e);for(var t="",r=0,o=e.length;o>r;++r){var i=e.charCodeAt(r);45===i||46===i||95===i||126===i||i>=48&&57>=i||i>=65&&90>=i||i>=97&&122>=i?t+=e[r]:128>i?t+=n.hexTable[i]:2048>i?t+=n.hexTable[192|i>>6]+n.hexTable[128|63&i]:55296>i||i>=57344?t+=n.hexTable[224|i>>12]+n.hexTable[128|i>>6&63]+n.hexTable[128|63&i]:(++r,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t+=n.hexTable[240|i>>18]+n.hexTable[128|i>>12&63]+n.hexTable[128|i>>6&63]+n.hexTable[128|63&i])}return t},t.compact=function(e,n){if("object"!=typeof e||null===e)return e;n=n||[];var r=n.indexOf(e);if(-1!==r)return n[r];if(n.push(e),Array.isArray(e)){for(var o=[],i=0,a=e.length;a>i;++i)"undefined"!=typeof e[i]&&o.push(e[i]);return o}var s=Object.keys(e);for(i=0,a=s.length;a>i;++i){var u=s[i];e[u]=t.compact(e[u],n)}return e},t.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},t.isBuffer=function(e){return null===e||"undefined"==typeof e?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}},function(e,t,n){var r=n(205),o={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1};o.parseValues=function(e,t){for(var n={},o=e.split(t.delimiter,t.parameterLimit===1/0?void 0:t.parameterLimit),i=0,a=o.length;a>i;++i){var s=o[i],u=-1===s.indexOf("]=")?s.indexOf("="):s.indexOf("]=")+1;if(-1===u)n[r.decode(s)]="",t.strictNullHandling&&(n[r.decode(s)]=null);else{var l=r.decode(s.slice(0,u)),c=r.decode(s.slice(u+1));Object.prototype.hasOwnProperty.call(n,l)?n[l]=[].concat(n[l]).concat(c):n[l]=c}}return n},o.parseObject=function(e,t,n){if(!e.length)return t;var r,i=e.shift();if("[]"===i)r=[],r=r.concat(o.parseObject(e,t,n));else{r=n.plainObjects?Object.create(null):{};var a="["===i[0]&&"]"===i[i.length-1]?i.slice(1,i.length-1):i,s=parseInt(a,10),u=""+s;!isNaN(s)&&i!==a&&u===a&&s>=0&&n.parseArrays&&s<=n.arrayLimit?(r=[],r[s]=o.parseObject(e,t,n)):r[a]=o.parseObject(e,t,n)}return r},o.parseKeys=function(e,t,n){if(e){n.allowDots&&(e=e.replace(/\.([^\.\[]+)/g,"[$1]"));var r=/^([^\[\]]*)/,i=/(\[[^\[\]]*\])/g,a=r.exec(e),s=[];if(a[1]){if(!n.plainObjects&&Object.prototype.hasOwnProperty(a[1])&&!n.allowPrototypes)return;s.push(a[1])}for(var u=0;null!==(a=i.exec(e))&&u<n.depth;)++u,(n.plainObjects||!Object.prototype.hasOwnProperty(a[1].replace(/\[|\]/g,""))||n.allowPrototypes)&&s.push(a[1]);return a&&s.push("["+e.slice(a.index)+"]"),o.parseObject(s,t,n)}},e.exports=function(e,t){if(t=t||{},t.delimiter="string"==typeof t.delimiter||r.isRegExp(t.delimiter)?t.delimiter:o.delimiter,t.depth="number"==typeof t.depth?t.depth:o.depth,t.arrayLimit="number"==typeof t.arrayLimit?t.arrayLimit:o.arrayLimit,t.parseArrays=t.parseArrays!==!1,t.allowDots="boolean"==typeof t.allowDots?t.allowDots:o.allowDots,t.plainObjects="boolean"==typeof t.plainObjects?t.plainObjects:o.plainObjects,t.allowPrototypes="boolean"==typeof t.allowPrototypes?t.allowPrototypes:o.allowPrototypes,t.parameterLimit="number"==typeof t.parameterLimit?t.parameterLimit:o.parameterLimit,t.strictNullHandling="boolean"==typeof t.strictNullHandling?t.strictNullHandling:o.strictNullHandling,""===e||null===e||"undefined"==typeof e)return t.plainObjects?Object.create(null):{};for(var n="string"==typeof e?o.parseValues(e,t):e,i=t.plainObjects?Object.create(null):{},a=Object.keys(n),s=0,u=a.length;u>s;++s){var l=a[s],c=o.parseKeys(l,n[l],t);i=r.merge(i,c,t)}return r.compact(i)}},function(e,t,n){var r=n(208),o=r(!0);e.exports=o},function(e,t,n){function r(e){return function(t,n,r){var a={};return n=o(n,r,3),i(t,function(t,r,o){var i=n(t,r,o);r=e?i:r,t=e?t:i,a[r]=t}),a}}var o=n(55),i=n(17);e.exports=r},function(e,t,n){var r=n(208),o=r();e.exports=o},function(e,t){"use strict";e.exports="2.8.1"},function(e,t,n){var r=n(117),o=n(212),i=n(85),a=i(function(e){return o(r(e,!1,!0))});e.exports=a},function(e,t,n){function r(e,t){var n=-1,r=o,u=e.length,l=!0,c=l&&u>=s,p=c?a():null,f=[];p?(r=i,l=!1):(c=!1,p=t?[]:f);e:for(;++n<u;){var d=e[n],h=t?t(d,n,e):d;if(l&&d===d){for(var m=p.length;m--;)if(p[m]===h)continue e;t&&p.push(h),f.push(d)}else r(p,h,0)<0&&((t||c)&&p.push(h),f.push(d))}return f}var o=n(100),i=n(102),a=n(103),s=200;e.exports=r},function(e,t,n){"use strict";function r(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 i(e){var t=e;return function(){var e=Date.now(),n=e-t;return t=e,n}}function a(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.useHash||!1,n=t?y:b; return new _(n,e)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=n(96),l=r(u),c=n(200),p=r(c),f=n(214),d=r(f),h=n(78),m=r(h),v=l["default"].AlgoliaSearchHelper,g=n(215).split(".")[0],y={character:"#",onpopstate:function(e){window.addEventListener("hashchange",e)},pushState:function(e){window.location.assign(this.createURL(e))},replaceState:function(e){window.location.replace(this.createURL(e))},createURL:function(e){return document.location.search+this.character+e},readUrl:function(){return window.location.hash.slice(1)}},b={character:"?",onpopstate:function(e){window.addEventListener("popstate",e)},pushState:function(e){window.history.pushState(null,"",this.createURL(e))},replaceState:function(e){window.history.replaceState(null,"",this.createURL(e))},createURL:function(e){return this.character+e+document.location.hash},readUrl:function(){return window.location.search.slice(1)}},_=function(){function e(t,n){o(this,e),this.urlUtils=t,this.originalConfig=null,this.timer=i(Date.now()),this.threshold=n.threshold||700,this.trackedParameters=n.trackedParameters||["query","attribute:*","index","page","hitsPerPage"]}return s(e,[{key:"getConfiguration",value:function(e){this.originalConfig=e;var t=this.urlUtils.readUrl(),n=v.getConfigurationFromQueryString(t);return n}},{key:"init",value:function(e){var t=this,n=e.helper;n.on("change",function(e){t.renderURLFromState(e)}),this.onHistoryChange(this.onPopState.bind(this,n))}},{key:"onPopState",value:function(e,t){var n=e.getState(this.trackedParameters),r=(0,m["default"])({},this.originalConfig,n);(0,d["default"])(r,t)||e.overrideStateWithoutTriggeringChangeEvent(t).search()}},{key:"renderURLFromState",value:function(e){var t=this.urlUtils.readUrl(),n=v.getForeignConfigurationInQueryString(t);n.is_v=g;var r=p["default"].getQueryStringFromState(e.filter(this.trackedParameters),{moreAttributes:n});this.timer()<this.threshold?this.urlUtils.replaceState(r):this.urlUtils.pushState(r)}},{key:"createURL",value:function(e){var t=this.urlUtils.readUrl(),n=e.filter(this.trackedParameters),r=l["default"].url.getUnrecognizedParametersInQueryString(t);return r.is_v=g,this.urlUtils.createURL(l["default"].url.getQueryStringFromState(n))}},{key:"onHistoryChange",value:function(e){var t=this;this.urlUtils.onpopstate(function(){var n=t.urlUtils.readUrl(),r=v.getConfigurationFromQueryString(n),o=(0,m["default"])({},t.originalConfig,r);e(o)})}}]),e}();t["default"]=a,e.exports=t["default"]},function(e,t,n){function r(e,t,n,r){n="function"==typeof n?i(n,r,3):void 0;var a=n?n(e,t):void 0;return void 0===a?o(e,t,n):!!a}var o=n(58),i=n(38);e.exports=r},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]="1.2.1",e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(e){var t=e.numberLocale;return{formatNumber:function(e,n){return Number(n(e)).toLocaleString(t)}}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.templates,o=void 0===r?g["default"]:r,i=e.cssClasses,s=void 0===i?{}:i,c=e.autoHideContainer,f=void 0===c?!0:c;if(!t)throw new Error(b);var h=(0,l.getContainerNode)(t),v=(0,m["default"])(n(387));return f===!0&&(v=(0,d["default"])(v)),{render:function(e){var t=e.results,n=e.helper,r=e.state,i=e.templatesConfig,c=e.createURL,f=0!==(0,l.getRefinements)(t,r).length,d={root:(0,p["default"])(y(null),s.root),header:(0,p["default"])(y("header"),s.header),body:(0,p["default"])(y("body"),s.body),footer:(0,p["default"])(y("footer"),s.footer),link:(0,p["default"])(y("link"),s.link)},m=c((0,l.clearRefinementsFromState)(r)),b=l.clearRefinementsAndSearch.bind(null,n),_=(0,l.prepareTemplateProps)({defaultTemplates:g["default"],templatesConfig:i,templates:o});u["default"].render(a["default"].createElement(v,{clearAll:b,cssClasses:d,hasRefinements:f,shouldAutoHideContainer:!f,templateProps:_,url:m}),h)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=n(377),p=r(c),f=n(378),d=r(f),h=n(379),m=r(h),v=n(386),g=r(v),y=(0,l.bemHelper)("ais-clear-all"),b="Usage:\nclearAll({\n container,\n [cssClasses.{root,header,body,footer,link}={}],\n [templates.{header,link,footer}={header: '', link: 'Clear all', footer: ''}],\n [autoHideContainer=true]\n})";t["default"]=o,e.exports=t["default"]},function(e,t,n){(function(t){e.exports=t.React=n(219)}).call(t,function(){return this}())},function(e,t,n){"use strict";e.exports=n(220)},function(e,t,n){"use strict";var r=n(221),o=n(361),i=n(365),a=n(256),s=n(370),u={};a(u,i),a(u,{findDOMNode:s("findDOMNode","ReactDOM","react-dom",r,r.findDOMNode),render:s("render","ReactDOM","react-dom",r,r.render),unmountComponentAtNode:s("unmountComponentAtNode","ReactDOM","react-dom",r,r.unmountComponentAtNode),renderToString:s("renderToString","ReactDOMServer","react-dom/server",o,o.renderToString),renderToStaticMarkup:s("renderToStaticMarkup","ReactDOMServer","react-dom/server",o,o.renderToStaticMarkup)}),u.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=r,u.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=o,e.exports=u},function(e,t,n){"use strict";var r=n(222),o=n(223),i=n(288),a=n(262),s=n(245),u=n(235),l=n(267),c=n(271),p=n(359),f=n(308),d=n(360);n(242);i.inject();var h=u.measure("React","render",s.render),m={findDOMNode:f,render:h,unmountComponentAtNode:s.unmountComponentAtNode,version:p,unstable_batchedUpdates:c.batchedUpdates,unstable_renderSubtreeIntoContainer:d};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:r,InstanceHandles:a,Mount:s,Reconciler:l,TextComponent:o});e.exports=m},function(e,t){"use strict";var n={current:null};e.exports=n},function(e,t,n){"use strict";var r=n(224),o=n(239),i=n(243),a=n(245),s=n(256),u=n(238),l=n(237),c=(n(287),function(e){});s(c.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){if(this._rootNodeID=e,t.useCreateElement){var r=n[a.ownerDocumentContextKey],i=r.createElement("span");return o.setAttributeForID(i,e),a.getID(i),l(i,this._stringText),i}var s=u(this._stringText);return t.renderToStaticMarkup?s:"<span "+o.createMarkupForID(e)+">"+s+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var o=a.getNode(this._rootNodeID);r.updateTextContent(o,n)}}},unmountComponent:function(){i.unmountIDFromEnvironment(this._rootNodeID)}}),e.exports=c},function(e,t,n){"use strict";function r(e,t,n){var r=n>=e.childNodes.length?null:e.childNodes.item(n);e.insertBefore(t,r)}var o=n(225),i=n(233),a=n(235),s=n(236),u=n(237),l=n(230),c={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:u,processUpdates:function(e,t){for(var n,a=null,c=null,p=0;p<e.length;p++)if(n=e[p],n.type===i.MOVE_EXISTING||n.type===i.REMOVE_NODE){var f=n.fromIndex,d=n.parentNode.childNodes[f],h=n.parentID;d?void 0:l(!1),a=a||{},a[h]=a[h]||[],a[h][f]=d,c=c||[],c.push(d)}var m;if(m=t.length&&"string"==typeof t[0]?o.dangerouslyRenderMarkup(t):t,c)for(var v=0;v<c.length;v++)c[v].parentNode.removeChild(c[v]);for(var g=0;g<e.length;g++)switch(n=e[g],n.type){case i.INSERT_MARKUP:r(n.parentNode,m[n.markupIndex],n.toIndex);break;case i.MOVE_EXISTING:r(n.parentNode,a[n.parentID][n.fromIndex],n.toIndex);break;case i.SET_MARKUP:s(n.parentNode,n.content);break;case i.TEXT_CONTENT:u(n.parentNode,n.content);break;case i.REMOVE_NODE:}}};a.measureMethods(c,"DOMChildrenOperations",{updateTextContent:"updateTextContent"}),e.exports=c},function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=n(226),i=n(227),a=n(232),s=n(231),u=n(230),l=/^(<[^ \/>]+)/,c="data-danger-index",p={dangerouslyRenderMarkup:function(e){o.canUseDOM?void 0:u(!1);for(var t,n={},p=0;p<e.length;p++)e[p]?void 0:u(!1),t=r(e[p]),t=s(t)?t:"*",n[t]=n[t]||[],n[t][p]=e[p];var f=[],d=0;for(t in n)if(n.hasOwnProperty(t)){var h,m=n[t];for(h in m)if(m.hasOwnProperty(h)){var v=m[h];m[h]=v.replace(l,"$1 "+c+'="'+h+'" ')}for(var g=i(m.join(""),a),y=0;y<g.length;++y){var b=g[y];b.hasAttribute&&b.hasAttribute(c)&&(h=+b.getAttribute(c),b.removeAttribute(c),f.hasOwnProperty(h)?u(!1):void 0,f[h]=b,d+=1)}}return d!==f.length?u(!1):void 0,f.length!==e.length?u(!1):void 0,f},dangerouslyReplaceNodeWithMarkup:function(e,t){o.canUseDOM?void 0:u(!1),t?void 0:u(!1),"html"===e.tagName.toLowerCase()?u(!1):void 0;var n;n="string"==typeof t?i(t,a)[0]:t,e.parentNode.replaceChild(n,e)}};e.exports=p},function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.match(c);return t&&t[1].toLowerCase()}function o(e,t){var n=l;l?void 0:u(!1);var o=r(e),i=o&&s(o);if(i){n.innerHTML=i[1]+e+i[2];for(var c=i[0];c--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(t?void 0:u(!1),a(p).forEach(t));for(var f=a(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return f}var i=n(226),a=n(228),s=n(231),u=n(230),l=i.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;e.exports=o},function(e,t,n){"use strict";function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return r(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=n(229);e.exports=o},function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?o(!1):void 0,"number"!=typeof t?o(!1):void 0,0===t||t-1 in e?void 0:o(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;t>i;i++)r[i]=e[i];return r}var o=n(230);e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,s],c=0;u=new Error(t.replace(/%s/g,function(){return l[c++]})),u.name="Invariant Violation"}throw u.framesToPop=1,u}}e.exports=r},function(e,t,n){"use strict";function r(e){return a?void 0:i(!1),f.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?f[e]:null}var o=n(226),i=n(230),a=o.canUseDOM?document.createElement("div"):null,s={},u=[1,'<select multiple="true">',"</select>"],l=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],f={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:u,option:u,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c},d=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];d.forEach(function(e){f[e]=p,s[e]=!0}),e.exports=r},function(e,t){"use strict";function n(e){return function(){return e}}function r(){}r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t,n){"use strict";var r=n(234),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});e.exports=o},function(e,t,n){"use strict";var r=n(230),o=function(e){var t,n={};e instanceof Object&&!Array.isArray(e)?void 0:r(!1);for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};e.exports=o},function(e,t,n){"use strict";function r(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:r,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){o.storedMeasure=e}}};e.exports=o},function(e,t,n){"use strict";var r=n(226),o=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(a=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var s=document.createElement("div");s.innerHTML=" ",""===s.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}e.exports=a},function(e,t,n){"use strict";var r=n(226),o=n(238),i=n(236),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),e.exports=a},function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(i,n)}var o={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},i=/[&><"']/g;e.exports=r},function(e,t,n){"use strict";function r(e){return c.hasOwnProperty(e)?!0:l.hasOwnProperty(e)?!1:u.test(e)?(c[e]=!0,!0):(l[e]=!0,!1)}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&1>t||e.hasOverloadedBooleanValue&&t===!1}var i=n(240),a=n(235),s=n(241),u=(n(242),/^[a-zA-Z_][\w\.\-]*$/),l={},c={},p={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+s(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForProperty:function(e,t){var n=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&t===!0?r+'=""':r+"="+s(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+s(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+s(t):""},setValueForProperty:function(e,t,n){var r=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else if(o(r,n))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute){var s=r.attributeName,u=r.attributeNamespace;u?e.setAttributeNS(u,s,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?e.setAttribute(s,""):e.setAttribute(s,""+n)}else{var l=r.propertyName;r.hasSideEffects&&""+e[l]==""+n||(e[l]=n)}}else i.isCustomAttribute(t)&&p.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){r(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){var n=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseAttribute)e.removeAttribute(n.attributeName);else{var o=n.propertyName,a=i.getDefaultValueForProperty(e.nodeName,o);n.hasSideEffects&&""+e[o]===a||(e[o]=a)}}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};a.measureMethods(p,"DOMPropertyOperations",{setValueForProperty:"setValueForProperty",setValueForAttribute:"setValueForAttribute",deleteValueForProperty:"deleteValueForProperty"}),e.exports=p},function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=n(230),i={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=i,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},u=e.DOMAttributeNames||{},l=e.DOMPropertyNames||{},c=e.DOMMutationMethods||{};e.isCustomAttribute&&s._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var p in n){s.properties.hasOwnProperty(p)?o(!1):void 0;var f=p.toLowerCase(),d=n[p],h={attributeName:f,attributeNamespace:null,propertyName:p,mutationMethod:null,mustUseAttribute:r(d,t.MUST_USE_ATTRIBUTE),mustUseProperty:r(d,t.MUST_USE_PROPERTY),hasSideEffects:r(d,t.HAS_SIDE_EFFECTS),hasBooleanValue:r(d,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(d,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(d,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(d,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(h.mustUseAttribute&&h.mustUseProperty?o(!1):void 0,!h.mustUseProperty&&h.hasSideEffects?o(!1):void 0,h.hasBooleanValue+h.hasNumericValue+h.hasOverloadedBooleanValue<=1?void 0:o(!1),u.hasOwnProperty(p)){var m=u[p];h.attributeName=m}a.hasOwnProperty(p)&&(h.attributeNamespace=a[p]),l.hasOwnProperty(p)&&(h.propertyName=l[p]),c.hasOwnProperty(p)&&(h.mutationMethod=c[p]),s.properties[p]=h}}},a={},s={ID_ATTRIBUTE_NAME:"data-reactid",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<s._isCustomAttributeFunctions.length;t++){var n=s._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=a[e];return r||(a[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:i};e.exports=s},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(238);e.exports=r},function(e,t,n){"use strict";var r=n(232),o=r;e.exports=o},function(e,t,n){"use strict";var r=n(244),o=n(245),i={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};e.exports=i},function(e,t,n){"use strict";var r=n(224),o=n(239),i=n(245),a=n(235),s=n(230),u={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:function(e,t,n){var r=i.getNode(e);u.hasOwnProperty(t)?s(!1):void 0,null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)}};a.measureMethods(l,"ReactDOMIDOperations",{dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),e.exports=l},function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===q?e.documentElement:e.firstChild:null}function i(e){var t=o(e);return t&&$.getID(t)}function a(e){var t=s(e);if(t)if(H.hasOwnProperty(t)){var n=H[t];n!==e&&(p(n,t)?A(!1):void 0,H[t]=e)}else H[t]=e;return t}function s(e){return e&&e.getAttribute&&e.getAttribute(U)||""}function u(e,t){var n=s(e);n!==t&&delete H[n],e.setAttribute(U,t),H[t]=e}function l(e){return H.hasOwnProperty(e)&&p(H[e],e)||(H[e]=$.findReactNodeByID(e)),H[e]}function c(e){var t=E.get(e)._rootNodeID;return w.isNullComponentID(t)?null:(H.hasOwnProperty(t)&&p(H[t],t)||(H[t]=$.findReactNodeByID(t)),H[t])}function p(e,t){if(e){s(e)!==t?A(!1):void 0;var n=$.findReactContainerForID(t);if(n&&D(n,e))return!0}return!1}function f(e){delete H[e]}function d(e){var t=H[e];return t&&p(t,e)?void(G=t):!1}function h(e){G=null,R.traverseAncestors(e,d);var t=G;return G=null,t}function m(e,t,n,r,o,i){P.useCreateElement&&(i=k({},i),n.nodeType===q?i[W]=n:i[W]=n.ownerDocument);var a=S.mountComponent(e,t,r,i);e._renderedComponent._topLevelWrapper=e,$._mountImageIntoNode(a,n,o,r)}function v(e,t,n,r,o){var i=N.ReactReconcileTransaction.getPooled(r);i.perform(m,null,e,t,n,i,r,o),N.ReactReconcileTransaction.release(i)}function g(e,t){for(S.unmountComponent(e),t.nodeType===q&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function y(e){var t=i(e);return t?t!==R.getReactRootIDFromNodeID(t):!1}function b(e){for(;e&&e.parentNode!==e;e=e.parentNode)if(1===e.nodeType){var t=s(e);if(t){var n,r=R.getReactRootIDFromNodeID(t),o=e;do if(n=s(o),o=o.parentNode,null==o)return null;while(n!==r);if(o===Q[r])return e}}return null}var _=n(240),x=n(246),P=(n(222),n(258)),C=n(259),w=n(261),R=n(262),E=n(264),T=n(265),O=n(235),S=n(267),j=n(270),N=n(271),k=n(256),M=n(275),D=n(276),I=n(279),A=n(230),F=n(236),L=n(284),U=(n(287),n(242),_.ID_ATTRIBUTE_NAME),H={},B=1,q=9,V=11,W="__ReactMount_ownerDocument$"+Math.random().toString(36).slice(2),K={},Q={},z=[],G=null,Y=function(){};Y.prototype.isReactComponent={},Y.prototype.render=function(){return this.props};var $={TopLevelWrapper:Y,_instancesByReactRootID:K,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return $.scrollMonitor(n,function(){j.enqueueElementInternal(e,t),r&&j.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){!t||t.nodeType!==B&&t.nodeType!==q&&t.nodeType!==V?A(!1):void 0,x.ensureScrollValueMonitoring();var n=$.registerContainer(t);return K[n]=e,n},_renderNewRootComponent:function(e,t,n,r){var o=I(e,null),i=$._registerComponent(o,t);return N.batchedUpdates(v,o,i,t,n,r),o},renderSubtreeIntoContainer:function(e,t,n,r){return null==e||null==e._reactInternalInstance?A(!1):void 0,$._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){C.isValidElement(t)?void 0:A(!1);var a=new C(Y,null,null,null,null,null,t),u=K[i(n)];if(u){var l=u._currentElement,c=l.props;if(L(c,t)){var p=u._renderedComponent.getPublicInstance(),f=r&&function(){r.call(p)};return $._updateRootComponent(u,a,n,f),p}$.unmountComponentAtNode(n)}var d=o(n),h=d&&!!s(d),m=y(n),v=h&&!u&&!m,g=$._renderNewRootComponent(a,n,v,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):M)._renderedComponent.getPublicInstance();return r&&r.call(g),g},render:function(e,t,n){return $._renderSubtreeIntoContainer(null,e,t,n)},registerContainer:function(e){var t=i(e);return t&&(t=R.getReactRootIDFromNodeID(t)),t||(t=R.createReactRootID()),Q[t]=e,t},unmountComponentAtNode:function(e){!e||e.nodeType!==B&&e.nodeType!==q&&e.nodeType!==V?A(!1):void 0;var t=i(e),n=K[t];if(!n){var r=(y(e),s(e));r&&r===R.getReactRootIDFromNodeID(r);return!1}return N.batchedUpdates(g,n,e),delete K[t],delete Q[t],!0},findReactContainerForID:function(e){var t=R.getReactRootIDFromNodeID(e),n=Q[t];return n},findReactNodeByID:function(e){var t=$.findReactContainerForID(e);return $.findComponentRoot(t,e)},getFirstReactDOM:function(e){return b(e)},findComponentRoot:function(e,t){var n=z,r=0,o=h(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=$.getID(a);s?t===s?i=a:R.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,A(!1)},_mountImageIntoNode:function(e,t,n,i){if(!t||t.nodeType!==B&&t.nodeType!==q&&t.nodeType!==V?A(!1):void 0,n){var a=o(t);if(T.canReuseMarkup(e,a))return;var s=a.getAttribute(T.CHECKSUM_ATTR_NAME);a.removeAttribute(T.CHECKSUM_ATTR_NAME);var u=a.outerHTML;a.setAttribute(T.CHECKSUM_ATTR_NAME,s);var l=e,c=r(l,u);" (client) "+l.substring(c-20,c+20)+"\n (server) "+u.substring(c-20,c+20);t.nodeType===q?A(!1):void 0}if(t.nodeType===q?A(!1):void 0,i.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);t.appendChild(e)}else F(t,e)},ownerDocumentContextKey:W,getReactRootID:i,getID:a,setID:u,getNode:l,getNodeFromInstance:c,isValid:p,purgeID:f};O.measureMethods($,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),e.exports=$},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,v)||(e[v]=h++,f[e[v]]={}),f[e[v]]}var o=n(247),i=n(248),a=n(249),s=n(254),u=n(235),l=n(255),c=n(256),p=n(257),f={},d=!1,h=0,m={topAbort:"abort",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},v="_reactListenersID"+String(Math.random()).slice(2),g=c({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(g.handleTopLevel),g.ReactEventListener=e}},setEnabled:function(e){g.ReactEventListener&&g.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!g.ReactEventListener||!g.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=r(n),s=a.registrationNameDependencies[e],u=o.topLevelTypes,l=0;l<s.length;l++){var c=s[l];i.hasOwnProperty(c)&&i[c]||(c===u.topWheel?p("wheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",n):p("mousewheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",n):g.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",n):c===u.topScroll?p("scroll",!0)?g.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",n):g.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",g.ReactEventListener.WINDOW_HANDLE):c===u.topFocus||c===u.topBlur?(p("focus",!0)?(g.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",n),g.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",n)):p("focusin")&&(g.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",n),g.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",n)),i[u.topBlur]=!0,i[u.topFocus]=!0):m.hasOwnProperty(c)&&g.ReactEventListener.trapBubbledEvent(c,m[c],n),i[c]=!0)}},trapBubbledEvent:function(e,t,n){return g.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return g.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!d){var e=l.refreshScrollValues;g.ReactEventListener.monitorScrollValue(e),d=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});u.measureMethods(g,"ReactBrowserEventEmitter",{putListener:"putListener",deleteListener:"deleteListener"}),e.exports=g},function(e,t,n){"use strict";var r=n(234),o=r({bubbled:null,captured:null}),i=r({topAbort:null,topBlur:null,topCanPlay:null,topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topVolumeChange:null,topWaiting:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:o};e.exports=a},function(e,t,n){"use strict";var r=n(249),o=n(250),i=n(251),a=n(252),s=n(253),u=n(230),l=(n(242),{}),c=null,p=function(e,t){e&&(o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},f=function(e){return p(e,!0)},d=function(e){return p(e,!1)},h=null,m={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){h=e},getInstanceHandle:function(){return h},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){"function"!=typeof n?u(!1):void 0;var o=l[t]||(l[t]={});o[e]=n;var i=r.registrationNameModules[t];i&&i.didPutListener&&i.didPutListener(e,t,n)},getListener:function(e,t){var n=l[t];return n&&n[e]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=l[t];o&&delete o[e]},deleteAllListeners:function(e){for(var t in l)if(l[t][e]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete l[t][e]}},extractEvents:function(e,t,n,o,i){for(var s,u=r.plugins,l=0;l<u.length;l++){var c=u[l];if(c){var p=c.extractEvents(e,t,n,o,i);p&&(s=a(s,p))}}return s},enqueueEvents:function(e){e&&(c=a(c,e))},processEventQueue:function(e){var t=c;c=null,e?s(t,f):s(t,d),c?u(!1):void 0,i.rethrowCaughtError()},__purge:function(){l={}},__getListenerBank:function(){return l}};e.exports=m},function(e,t,n){"use strict";function r(){if(s)for(var e in u){var t=u[e],n=s.indexOf(e);if(n>-1?void 0:a(!1),!l.plugins[n]){t.extractEvents?void 0:a(!1),l.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)?void 0:a(!1)}}}function o(e,t,n){l.eventNameDispatchConfigs.hasOwnProperty(n)?a(!1):void 0,l.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var s=r[o];i(s,t,n)}return!0}return e.registrationName?(i(e.registrationName,t,n),!0):!1}function i(e,t,n){l.registrationNameModules[e]?a(!1):void 0,l.registrationNameModules[e]=t,l.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(230),s=null,u={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){s?a(!1):void 0,s=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];u.hasOwnProperty(n)&&u[n]===o||(u[n]?a(!1):void 0,u[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return l.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=l.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[e];l.plugins.length=0;var t=l.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=l.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};e.exports=l},function(e,t,n){"use strict";function r(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel; }function o(e){return e===v.topMouseMove||e===v.topTouchMove}function i(e){return e===v.topMouseDown||e===v.topTouchStart}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=m.Mount.getNode(r),t?d.invokeGuardedCallbackWithCatch(o,n,e,r):d.invokeGuardedCallback(o,n,e,r),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)a(e,t,n[o],r[o]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function l(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function c(e){var t=e._dispatchListeners,n=e._dispatchIDs;Array.isArray(t)?h(!1):void 0;var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var f=n(247),d=n(251),h=n(230),m=(n(242),{Mount:null,injectMount:function(e){m.Mount=e}}),v=f.topLevelTypes,g={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:c,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:l,hasDispatches:p,getNode:function(e){return m.Mount.getNode(e)},getID:function(e){return m.Mount.getID(e)},injection:m};e.exports=g},function(e,t,n){"use strict";function r(e,t,n,r){try{return t(n,r)}catch(i){return void(null===o&&(o=i))}}var o=null,i={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};e.exports=i},function(e,t,n){"use strict";function r(e,t){if(null==t?o(!1):void 0,null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=n(230);e.exports=r},function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};e.exports=n},function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(248),i={handleTopLevel:function(e,t,n,i,a){var s=o.extractEvents(e,t,n,i,a);r(s)}};e.exports=i},function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};e.exports=n},function(e,t){"use strict";function n(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),r=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i){var a=Object(i);for(var s in a)r.call(a,s)&&(n[s]=a[s])}}return n}e.exports=n},function(e,t,n){"use strict";function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=n(226);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=r},function(e,t){"use strict";var n={useCreateElement:!1};e.exports=n},function(e,t,n){"use strict";var r=n(222),o=n(256),i=(n(260),"function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103),a={key:!0,ref:!0,__self:!0,__source:!0},s=function(e,t,n,r,o,a,s){var u={$$typeof:i,type:e,key:t,ref:n,props:s,_owner:a};return u};s.createElement=function(e,t,n){var o,i={},u=null,l=null,c=null,p=null;if(null!=t){l=void 0===t.ref?null:t.ref,u=void 0===t.key?null:""+t.key,c=void 0===t.__self?null:t.__self,p=void 0===t.__source?null:t.__source;for(o in t)t.hasOwnProperty(o)&&!a.hasOwnProperty(o)&&(i[o]=t[o])}var f=arguments.length-2;if(1===f)i.children=n;else if(f>1){for(var d=Array(f),h=0;f>h;h++)d[h]=arguments[h+2];i.children=d}if(e&&e.defaultProps){var m=e.defaultProps;for(o in m)"undefined"==typeof i[o]&&(i[o]=m[o])}return s(e,u,l,c,p,r.current,i)},s.createFactory=function(e){var t=s.createElement.bind(null,e);return t.type=e,t},s.cloneAndReplaceKey=function(e,t){var n=s(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},s.cloneAndReplaceProps=function(e,t){var n=s(e.type,e.key,e.ref,e._self,e._source,e._owner,t);return n},s.cloneElement=function(e,t,n){var i,u=o({},e.props),l=e.key,c=e.ref,p=e._self,f=e._source,d=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,d=r.current),void 0!==t.key&&(l=""+t.key);for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(u[i]=t[i])}var h=arguments.length-2;if(1===h)u.children=n;else if(h>1){for(var m=Array(h),v=0;h>v;v++)m[v]=arguments[v+2];u.children=m}return s(e.type,l,c,p,f,d,u)},s.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===i},e.exports=s},function(e,t,n){"use strict";var r=!1;e.exports=r},function(e,t){"use strict";function n(e){return!!i[e]}function r(e){i[e]=!0}function o(e){delete i[e]}var i={},a={isNullComponentID:n,registerNullComponentID:r,deregisterNullComponentID:o};e.exports=a},function(e,t,n){"use strict";function r(e){return d+e.toString(36)}function o(e,t){return e.charAt(t)===d||t===e.length}function i(e){return""===e||e.charAt(0)===d&&e.charAt(e.length-1)!==d}function a(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function s(e){return e?e.substr(0,e.lastIndexOf(d)):""}function u(e,t){if(i(e)&&i(t)?void 0:f(!1),a(e,t)?void 0:f(!1),e===t)return e;var n,r=e.length+h;for(n=r;n<t.length&&!o(t,n);n++);return t.substr(0,n)}function l(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,a=0;n>=a;a++)if(o(e,a)&&o(t,a))r=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,r);return i(s)?void 0:f(!1),s}function c(e,t,n,r,o,i){e=e||"",t=t||"",e===t?f(!1):void 0;var l=a(t,e);l||a(e,t)?void 0:f(!1);for(var c=0,p=l?s:u,d=e;;d=p(d,t)){var h;if(o&&d===e||i&&d===t||(h=n(d,l,r)),h===!1||d===t)break;c++<m?void 0:f(!1)}}var p=n(263),f=n(230),d=".",h=d.length,m=1e4,v={createReactRootID:function(){return r(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===d&&e.length>1){var t=e.indexOf(d,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=l(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseTwoPhaseSkipTarget:function(e,t,n){e&&(c("",e,t,n,!0,!0),c(e,"",t,n,!0,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},getFirstCommonAncestorID:l,_getNextDescendantID:u,isAncestorIDOf:a,SEPARATOR:d};e.exports=v},function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};e.exports=r},function(e,t){"use strict";var n={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=n},function(e,t,n){"use strict";var r=n(266),o=/\/?>/,i={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(o," "+i.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(i.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};e.exports=i},function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0,i=e.length,a=-4&i;a>o;){for(;o<Math.min(o+4096,a);o+=4)n+=(t+=e.charCodeAt(o))+(t+=e.charCodeAt(o+1))+(t+=e.charCodeAt(o+2))+(t+=e.charCodeAt(o+3));t%=r,n%=r}for(;i>o;o++)n+=t+=e.charCodeAt(o);return t%=r,n%=r,t|n<<16}var r=65521;e.exports=n},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(268),i={mountComponent:function(e,t,n,o){var i=e.mountComponent(t,n,o);return e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e),i},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var s=o.shouldUpdateRefs(a,t);s&&o.detachRefs(e,a),e.receiveComponent(t,n,i),s&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(269),a={};a.attachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null===e||e===!1,r=null===t||t===!1;return n||r||t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=a},function(e,t,n){"use strict";var r=n(230),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};e.exports=o},function(e,t,n){"use strict";function r(e){s.enqueueUpdate(e)}function o(e,t){var n=a.get(e);return n?n:null}var i=(n(222),n(259)),a=n(264),s=n(271),u=n(256),l=n(230),c=(n(242),{isMounted:function(e){var t=a.get(e);return t?!!t._renderedComponent:!1},enqueueCallback:function(e,t){"function"!=typeof t?l(!1):void 0;var n=o(e);return n?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){"function"!=typeof t?l(!1):void 0,e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");n&&c.enqueueSetPropsInternal(n,t)},enqueueSetPropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:l(!1);var o=n._pendingElement||n._currentElement,a=o.props,s=u({},a.props,t);n._pendingElement=i.cloneAndReplaceProps(o,i.cloneAndReplaceProps(a,s)),r(n)},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");n&&c.enqueueReplacePropsInternal(n,t)},enqueueReplacePropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:l(!1);var o=n._pendingElement||n._currentElement,a=o.props;n._pendingElement=i.cloneAndReplaceProps(o,i.cloneAndReplaceProps(a,t)),r(n)},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});e.exports=c},function(e,t,n){"use strict";function r(){E.ReactReconcileTransaction&&_?void 0:v(!1)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=E.ReactReconcileTransaction.getPooled(!1)}function i(e,t,n,o,i,a){r(),_.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;t!==g.length?v(!1):void 0,g.sort(a);for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,d.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var i=0;i<o.length;i++)e.callbackQueue.enqueue(o[i],r.getPublicInstance())}}function u(e){return r(),_.isBatchingUpdates?void g.push(e):void _.batchedUpdates(u,e)}function l(e,t){_.isBatchingUpdates?void 0:v(!1),y.enqueue(e,t),b=!0}var c=n(272),p=n(273),f=n(235),d=n(267),h=n(274),m=n(256),v=n(230),g=[],y=c.getPooled(),b=!1,_=null,x={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),w()):g.length=0}},P={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},C=[x,P];m(o.prototype,h.Mixin,{getTransactionWrappers:function(){return C},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,E.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return h.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var w=function(){for(;g.length||b;){if(g.length){var e=o.getPooled();e.perform(s,null,e),o.release(e)}if(b){b=!1;var t=y;y=c.getPooled(),t.notifyAll(),c.release(t)}}};w=f.measure("ReactUpdates","flushBatchedUpdates",w);var R={injectReconcileTransaction:function(e){e?void 0:v(!1),E.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:v(!1),"function"!=typeof e.batchedUpdates?v(!1):void 0,"boolean"!=typeof e.isBatchingUpdates?v(!1):void 0,_=e}},E={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:u,flushBatchedUpdates:w,injection:R,asap:l};e.exports=E},function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=n(273),i=n(256),a=n(230);i(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){e.length!==t.length?a(!1):void 0,this._callbacks=null,this._contexts=null;for(var n=0;n<e.length;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(230),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},s=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},u=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},l=function(e){var t=this;e instanceof t?void 0:r(!1),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=10,p=o,f=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=c),n.release=l,n},d={addPoolingTo:f,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:s,fiveArgumentPooler:u};e.exports=d},function(e,t,n){"use strict";var r=n(230),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,s,u){this.isInTransaction()?r(!1):void 0;var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=e.call(t,n,o,i,a,s,u),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){this.isInTransaction()?void 0:r(!1);for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],s=this.wrapperInitData[n];try{o=!0,s!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,s),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(u){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};e.exports=i},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=!0;e:for(;n;){var r=e,i=t;if(n=!1,r&&i){if(r===i)return!0;if(o(r))return!1;if(o(i)){e=r,t=i.parentNode,n=!0;continue e}return r.contains?r.contains(i):r.compareDocumentPosition?!!(16&r.compareDocumentPosition(i)):!1}return!1}}var o=n(277);e.exports=r},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(278);e.exports=r},function(e,t){"use strict";function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=n},function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e){var t;if(null===e||e===!1)t=new a(o);else if("object"==typeof e){var n=e;!n||"function"!=typeof n.type&&"string"!=typeof n.type?l(!1):void 0,t="string"==typeof n.type?s.createInternalComponent(n):r(n.type)?new n.type(n):new c}else"string"==typeof e||"number"==typeof e?t=s.createInstanceForText(e):l(!1);return t.construct(e),t._mountIndex=0,t._mountImage=null,t}var i=n(280),a=n(285),s=n(286),u=n(256),l=n(230),c=(n(242),function(){});u(c.prototype,i.Mixin,{_instantiateReactComponent:o}),e.exports=o},function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}function o(e){}var i=n(281),a=n(222),s=n(259),u=n(264),l=n(235),c=n(282),p=(n(283),n(267)),f=n(270),d=n(256),h=n(275),m=n(230),v=n(284);n(242);o.prototype.render=function(){var e=u.get(this)._currentElement.type;return e(this.props,this.context,this.updater)};var g=1,y={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=g++,this._rootNodeID=e;var r,i,a=this._processProps(this._currentElement.props),l=this._processContext(n),c=this._currentElement.type,d="prototype"in c;d&&(r=new c(a,l,f)),(!d||null===r||r===!1||s.isValidElement(r))&&(i=r,r=new o(c)),r.props=a,r.context=l,r.refs=h,r.updater=f,this._instance=r,u.set(r,this);var v=r.state;void 0===v&&(r.state=v=null),"object"!=typeof v||Array.isArray(v)?m(!1):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,r.componentWillMount&&(r.componentWillMount(),this._pendingStateQueue&&(r.state=this._processPendingState(r.props,r.context))),void 0===i&&(i=this._renderValidatedComponent()),this._renderedComponent=this._instantiateReactComponent(i);var y=p.mountComponent(this._renderedComponent,e,t,this._processChildContext(n));return r.componentDidMount&&t.getReactMountReady().enqueue(r.componentDidMount,r),y},unmountComponent:function(){var e=this._instance;e.componentWillUnmount&&e.componentWillUnmount(),p.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._instance=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,u.remove(e)},_maskContext:function(e){var t=null,n=this._currentElement.type,r=n.contextTypes;if(!r)return h;t={};for(var o in r)t[o]=e[o];return t},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._currentElement.type,n=this._instance,r=n.getChildContext&&n.getChildContext();if(r){"object"!=typeof t.childContextTypes?m(!1):void 0;for(var o in r)o in t.childContextTypes?void 0:m(!1);return d({},e,r)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{"function"!=typeof e[i]?m(!1):void 0,a=e[i](t,i,o,n)}catch(s){a=s}if(a instanceof Error){r(this);n===c.prop}}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&p.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},updateComponent:function(e,t,n,r,o){var i,a=this._instance,s=this._context===o?a.context:this._processContext(o);t===n?i=n.props:(i=this._processProps(n.props),a.componentWillReceiveProps&&a.componentWillReceiveProps(i,s));var u=this._processPendingState(i,s),l=this._pendingForceUpdate||!a.shouldComponentUpdate||a.shouldComponentUpdate(i,u,s);l?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,i,u,s,e,o)):(this._currentElement=n,this._context=o,a.props=i,a.state=u,a.context=s)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=d({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var s=r[a];d(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a,s,u,l=this._instance,c=Boolean(l.componentDidUpdate);c&&(a=l.props,s=l.state,u=l.context),l.componentWillUpdate&&l.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,l.props=t,l.state=n,l.context=r,this._updateRenderedComponent(o,i),c&&o.getReactMountReady().enqueue(l.componentDidUpdate.bind(l,a,s,u),l)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(v(r,o))p.receiveComponent(n,o,e,this._processChildContext(t));else{var i=this._rootNodeID,a=n._rootNodeID;p.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(o);var s=p.mountComponent(this._renderedComponent,i,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(a,s)}},_replaceNodeWithMarkupByID:function(e,t){i.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(){var e;a.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{a.current=null}return null===e||e===!1||s.isValidElement(e)?void 0:m(!1),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n?m(!1):void 0;var r=t.getPublicInstance(),o=n.refs===h?n.refs={}:n.refs;o[e]=r},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return e instanceof o?null:e},_instantiateReactComponent:null};l.measureMethods(y,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var b={Mixin:y};e.exports=b},function(e,t,n){"use strict";var r=n(230),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o?r(!1):void 0,i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=i},function(e,t,n){"use strict";var r=n(234),o=r({prop:null,context:null,childContext:null});e.exports=o},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t){"use strict";function n(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}e.exports=n},function(e,t,n){"use strict";var r,o=n(259),i=n(261),a=n(267),s=n(256),u={injectEmptyComponent:function(e){r=o.createElement(e)}},l=function(e){this._currentElement=null,this._rootNodeID=null,this._renderedComponent=e(r)};s(l.prototype,{construct:function(e){},mountComponent:function(e,t,n){return i.registerNullComponentID(e),this._rootNodeID=e,a.mountComponent(this._renderedComponent,e,t,n)},receiveComponent:function(){},unmountComponent:function(e,t,n){a.unmountComponent(this._renderedComponent),i.deregisterNullComponentID(this._rootNodeID),this._rootNodeID=null,this._renderedComponent=null}}),l.injection=u,e.exports=l},function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=l(t)),n}function o(e){return c?void 0:u(!1),new c(e.type,e.props)}function i(e){return new f(e)}function a(e){return e instanceof f}var s=n(256),u=n(230),l=null,c=null,p={},f=null,d={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){f=e},injectComponentClasses:function(e){s(p,e)}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:d};e.exports=h},function(e,t,n){"use strict";var r=(n(256),n(232)),o=(n(242),r);e.exports=o},function(e,t,n){"use strict";function r(){if(!R){R=!0,g.EventEmitter.injectReactEventListener(v),g.EventPluginHub.injectEventPluginOrder(s),g.EventPluginHub.injectInstanceHandle(y),g.EventPluginHub.injectMount(b),g.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:C,EnterLeaveEventPlugin:u,ChangeEventPlugin:i,SelectEventPlugin:x,BeforeInputEventPlugin:o}),g.NativeComponent.injectGenericComponentClass(h),g.NativeComponent.injectTextComponentClass(m),g.Class.injectMixin(p),g.DOMProperty.injectDOMPropertyConfig(c),g.DOMProperty.injectDOMPropertyConfig(w),g.EmptyComponent.injectEmptyComponent("noscript"),g.Updates.injectReconcileTransaction(_),g.Updates.injectBatchingStrategy(d),g.RootIndex.injectCreateReactRootIndex(l.canUseDOM?a.createReactRootIndex:P.createReactRootIndex),g.Component.injectEnvironment(f)}}var o=n(289),i=n(297),a=n(300),s=n(301),u=n(302),l=n(226),c=n(306),p=n(307),f=n(243),d=n(309),h=n(310),m=n(223),v=n(335),g=n(338),y=n(262),b=n(245),_=n(342),x=n(347),P=n(348),C=n(349),w=n(358),R=!1;e.exports={inject:r}},function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case O.topCompositionStart:return S.compositionStart;case O.topCompositionEnd:return S.compositionEnd;case O.topCompositionUpdate:return S.compositionUpdate}}function a(e,t){return e===O.topKeyDown&&t.keyCode===x}function s(e,t){switch(e){case O.topKeyUp:return-1!==_.indexOf(t.keyCode);case O.topKeyDown:return t.keyCode!==x;case O.topKeyPress:case O.topMouseDown:case O.topBlur:return!0;default:return!1}}function u(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function l(e,t,n,r,o){var l,c;if(P?l=i(e):N?s(e,r)&&(l=S.compositionEnd):a(e,r)&&(l=S.compositionStart),!l)return null;R&&(N||l!==S.compositionStart?l===S.compositionEnd&&N&&(c=N.getData()):N=v.getPooled(t));var p=g.getPooled(l,n,r,o);if(c)p.data=c;else{var f=u(r);null!==f&&(p.data=f)}return h.accumulateTwoPhaseDispatches(p),p}function c(e,t){switch(e){case O.topCompositionEnd:return u(t);case O.topKeyPress:var n=t.which;return n!==E?null:(j=!0,T);case O.topTextInput:var r=t.data;return r===T&&j?null:r;default:return null}}function p(e,t){if(N){if(e===O.topCompositionEnd||s(e,t)){var n=N.getData();return v.release(N),N=null,n}return null}switch(e){case O.topPaste:return null;case O.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case O.topCompositionEnd:return R?null:t.data;default:return null}}function f(e,t,n,r,o){var i;if(i=w?c(e,r):p(e,r),!i)return null;var a=y.getPooled(S.beforeInput,n,r,o);return a.data=i,h.accumulateTwoPhaseDispatches(a),a}var d=n(247),h=n(290),m=n(226),v=n(291),g=n(293),y=n(295),b=n(296),_=[9,13,27,32],x=229,P=m.canUseDOM&&"CompositionEvent"in window,C=null;m.canUseDOM&&"documentMode"in document&&(C=document.documentMode);var w=m.canUseDOM&&"TextEvent"in window&&!C&&!r(),R=m.canUseDOM&&(!P||C&&C>8&&11>=C),E=32,T=String.fromCharCode(E),O=d.topLevelTypes,S={beforeInput:{phasedRegistrationNames:{bubbled:b({onBeforeInput:null}),captured:b({onBeforeInputCapture:null})},dependencies:[O.topCompositionEnd,O.topKeyPress,O.topTextInput,O.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:b({onCompositionEnd:null}),captured:b({onCompositionEndCapture:null})},dependencies:[O.topBlur,O.topCompositionEnd,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:b({onCompositionStart:null}),captured:b({onCompositionStartCapture:null})},dependencies:[O.topBlur,O.topCompositionStart,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:b({onCompositionUpdate:null}),captured:b({onCompositionUpdateCapture:null})},dependencies:[O.topBlur,O.topCompositionUpdate,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]}},j=!1,N=null,k={eventTypes:S,extractEvents:function(e,t,n,r,o){return[l(e,t,n,r,o),f(e,t,n,r,o)]}};e.exports=k},function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return y(e,r)}function o(e,t,n){var o=t?g.bubbled:g.captured,i=r(e,n,o);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchIDs=m(n._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(e.dispatchMarker,o,e)}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=y(e,r);o&&(n._dispatchListeners=m(n._dispatchListeners,o),n._dispatchIDs=m(n._dispatchIDs,e))}}function u(e){e&&e.dispatchConfig.registrationName&&s(e.dispatchMarker,null,e)}function l(e){v(e,i)}function c(e){v(e,a)}function p(e,t,n,r){h.injection.getInstanceHandle().traverseEnterLeave(n,r,s,e,t)}function f(e){v(e,u)}var d=n(247),h=n(248),m=(n(242),n(252)),v=n(253),g=d.PropagationPhases,y=h.getListener,b={accumulateTwoPhaseDispatches:l,accumulateTwoPhaseDispatchesSkipTarget:c,accumulateDirectDispatches:f,accumulateEnterLeaveDispatches:p};e.exports=b},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(273),i=n(256),a=n(292);i(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=n(226),i=null;e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(294),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var s=o[i];s?this[i]=s(n):"target"===i?this.target=r:this[i]=n[i]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;u?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse; }var o=n(273),i=n(256),a=n(232),s=(n(242),{type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null});i(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);i(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.fourArgumentPooler)},o.addPoolingTo(r,o.fourArgumentPooler),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(294),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t){"use strict";var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=n},function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=C.getPooled(S.change,N,e,w(e));_.accumulateTwoPhaseDispatches(t),P.batchedUpdates(i,t)}function i(e){b.enqueueEvents(e),b.processEventQueue(!1)}function a(e,t){j=e,N=t,j.attachEvent("onchange",o)}function s(){j&&(j.detachEvent("onchange",o),j=null,N=null)}function u(e,t,n){return e===O.topChange?n:void 0}function l(e,t,n){e===O.topFocus?(s(),a(t,n)):e===O.topBlur&&s()}function c(e,t){j=e,N=t,k=e.value,M=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(j,"value",A),j.attachEvent("onpropertychange",f)}function p(){j&&(delete j.value,j.detachEvent("onpropertychange",f),j=null,N=null,k=null,M=null)}function f(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==k&&(k=t,o(e))}}function d(e,t,n){return e===O.topInput?n:void 0}function h(e,t,n){e===O.topFocus?(p(),c(t,n)):e===O.topBlur&&p()}function m(e,t,n){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!j||j.value===k?void 0:(k=j.value,N)}function v(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===O.topClick?n:void 0}var y=n(247),b=n(248),_=n(290),x=n(226),P=n(271),C=n(294),w=n(298),R=n(257),E=n(299),T=n(296),O=y.topLevelTypes,S={change:{phasedRegistrationNames:{bubbled:T({onChange:null}),captured:T({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},j=null,N=null,k=null,M=null,D=!1;x.canUseDOM&&(D=R("change")&&(!("documentMode"in document)||document.documentMode>8));var I=!1;x.canUseDOM&&(I=R("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return M.get.call(this)},set:function(e){k=""+e,M.set.call(this,e)}},F={eventTypes:S,extractEvents:function(e,t,n,o,i){var a,s;if(r(t)?D?a=u:s=l:E(t)?I?a=d:(a=m,s=h):v(t)&&(a=g),a){var c=a(e,t,n);if(c){var p=C.getPooled(S.change,c,o,i);return p.type="change",_.accumulateTwoPhaseDispatches(p),p}}s&&s(e,t,n)}};e.exports=F},function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}e.exports=n},function(e,t){"use strict";function n(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&r[e.type]||"textarea"===t)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=n},function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};e.exports=r},function(e,t,n){"use strict";var r=n(296),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null})];e.exports=o},function(e,t,n){"use strict";var r=n(247),o=n(290),i=n(303),a=n(245),s=n(296),u=r.topLevelTypes,l=a.getFirstReactDOM,c={mouseEnter:{registrationName:s({onMouseEnter:null}),dependencies:[u.topMouseOut,u.topMouseOver]},mouseLeave:{registrationName:s({onMouseLeave:null}),dependencies:[u.topMouseOut,u.topMouseOver]}},p=[null,null],f={eventTypes:c,extractEvents:function(e,t,n,r,s){if(e===u.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==u.topMouseOut&&e!==u.topMouseOver)return null;var f;if(t.window===t)f=t;else{var d=t.ownerDocument;f=d?d.defaultView||d.parentWindow:window}var h,m,v="",g="";if(e===u.topMouseOut?(h=t,v=n,m=l(r.relatedTarget||r.toElement),m?g=a.getID(m):m=f,m=m||f):(h=f,m=t,g=n),h===m)return null;var y=i.getPooled(c.mouseLeave,v,r,s);y.type="mouseleave",y.target=h,y.relatedTarget=m;var b=i.getPooled(c.mouseEnter,g,r,s);return b.type="mouseenter",b.target=m,b.relatedTarget=h,o.accumulateEnterLeaveDispatches(y,b,v,g),p[0]=y,p[1]=b,p}};e.exports=f},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(304),i=n(255),a=n(305),s={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,s),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(294),i=n(298),a={view:function(e){if(e.view)return e.view;var t=i(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),e.exports=r},function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return r?!!n[r]:!1}function r(e){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=r},function(e,t,n){"use strict";var r,o=n(240),i=n(226),a=o.injection.MUST_USE_ATTRIBUTE,s=o.injection.MUST_USE_PROPERTY,u=o.injection.HAS_BOOLEAN_VALUE,l=o.injection.HAS_SIDE_EFFECTS,c=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,f=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var d=document.implementation;r=d&&d.hasFeature&&d.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var h={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:a|u,allowTransparency:a,alt:null,async:u,autoComplete:null,autoPlay:u,capture:a|u,cellPadding:null,cellSpacing:null,charSet:a,challenge:a,checked:s|u,classID:a,className:r?a:s,cols:a|p,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:s|u,coords:null,crossOrigin:null,data:null,dateTime:a,"default":u,defer:u,dir:null,disabled:a|u,download:f,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:u,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|u,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:s,inputMode:a,integrity:null,is:a,keyParams:a,keyType:a,kind:null,label:null,lang:null,list:a,loop:s|u,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,minLength:a,multiple:s|u,muted:s|u,name:null,nonce:a,noValidate:u,open:u,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:s|u,rel:null,required:u,reversed:u,role:a,rows:a|p,rowSpan:null,sandbox:null,scope:null,scoped:u,scrolling:null,seamless:a|u,selected:s|u,shape:null,size:a|p,sizes:a,span:p,spellCheck:null,src:null,srcDoc:s,srcLang:null,srcSet:a,start:c,step:null,style:null,summary:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:s|l,width:a,wmode:a,wrap:null,about:a,datatype:a,inlist:a,prefix:a,property:a,resource:a,"typeof":a,vocab:a,autoCapitalize:a,autoCorrect:a,autoSave:null,color:null,itemProp:a,itemScope:a|u,itemType:a,itemID:a,itemRef:a,results:null,security:a,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoComplete:"autocomplete",autoFocus:"autofocus",autoPlay:"autoplay",autoSave:"autosave",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};e.exports=h},function(e,t,n){"use strict";var r=(n(264),n(308)),o=(n(242),"_getDOMNodeDidWarn"),i={getDOMNode:function(){return this.constructor[o]=!0,r(this)}};e.exports=i},function(e,t,n){"use strict";function r(e){return null==e?null:1===e.nodeType?e:o.has(e)?i.getNodeFromInstance(e):(null!=e.render&&"function"==typeof e.render?a(!1):void 0,void a(!1))}var o=(n(222),n(264)),i=n(245),a=n(230);n(242);e.exports=r},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(271),i=n(274),a=n(256),s=n(232),u={initialize:s,close:function(){f.isBatchingUpdates=!1}},l={initialize:s,close:o.flushBatchedUpdates.bind(o)},c=[l,u];a(r.prototype,i.Mixin,{getTransactionWrappers:function(){return c}});var p=new r,f={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=f.isBatchingUpdates;f.isBatchingUpdates=!0,a?e(t,n,r,o,i):p.perform(e,null,t,n,r,o,i)}};e.exports=f},function(e,t,n){"use strict";function r(){return this}function o(){var e=this._reactInternalComponent;return!!e}function i(){}function a(e,t){var n=this._reactInternalComponent;n&&(k.enqueueSetPropsInternal(n,e),t&&k.enqueueCallbackInternal(n,t))}function s(e,t){var n=this._reactInternalComponent;n&&(k.enqueueReplacePropsInternal(n,e),t&&k.enqueueCallbackInternal(n,t))}function u(e,t){t&&(null!=t.dangerouslySetInnerHTML&&(null!=t.children?A(!1):void 0,"object"==typeof t.dangerouslySetInnerHTML&&Q in t.dangerouslySetInnerHTML?void 0:A(!1)),null!=t.style&&"object"!=typeof t.style?A(!1):void 0)}function l(e,t,n,r){var o=S.findReactContainerForID(e);if(o){var i=o.nodeType===z?o.ownerDocument:o;B(t,i)}r.getReactMountReady().enqueue(c,{id:e,registrationName:t,listener:n})}function c(){var e=this;P.putListener(e.id,e.registrationName,e.listener)}function p(){var e=this;e._rootNodeID?void 0:A(!1);var t=S.getNode(e._rootNodeID);switch(t?void 0:A(!1),e._tag){case"iframe":e._wrapperState.listeners=[P.trapBubbledEvent(x.topLevelTypes.topLoad,"load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in G)G.hasOwnProperty(n)&&e._wrapperState.listeners.push(P.trapBubbledEvent(x.topLevelTypes[n],G[n],t));break;case"img":e._wrapperState.listeners=[P.trapBubbledEvent(x.topLevelTypes.topError,"error",t),P.trapBubbledEvent(x.topLevelTypes.topLoad,"load",t)];break;case"form":e._wrapperState.listeners=[P.trapBubbledEvent(x.topLevelTypes.topReset,"reset",t),P.trapBubbledEvent(x.topLevelTypes.topSubmit,"submit",t)]}}function f(){R.mountReadyWrapper(this)}function d(){T.postUpdateWrapper(this)}function h(e){Z.call(X,e)||(J.test(e)?void 0:A(!1),X[e]=!0)}function m(e,t){return e.indexOf("-")>=0||null!=t.is}function v(e){h(e),this._tag=e.toLowerCase(),this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._rootNodeID=null,this._wrapperState=null,this._topLevelWrapper=null,this._nodeWithLegacyProperties=null}var g=n(311),y=n(313),b=n(240),_=n(239),x=n(247),P=n(246),C=n(243),w=n(321),R=n(322),E=n(326),T=n(329),O=n(330),S=n(245),j=n(331),N=n(235),k=n(270),M=n(256),D=n(260),I=n(238),A=n(230),F=(n(257),n(296)),L=n(236),U=n(237),H=(n(334),n(287),n(242),P.deleteListener),B=P.listenTo,q=P.registrationNameModules,V={string:!0,number:!0},W=F({children:null}),K=F({style:null}),Q=F({__html:null}),z=1,G={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},Y={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},$={listing:!0,pre:!0,textarea:!0},J=(M({menuitem:!0},Y),/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/),X={},Z={}.hasOwnProperty;v.displayName="ReactDOMComponent",v.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e;var r=this._currentElement.props;switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},t.getReactMountReady().enqueue(p,this);break;case"button":r=w.getNativeProps(this,r,n);break;case"input":R.mountWrapper(this,r,n),r=R.getNativeProps(this,r,n);break;case"option":E.mountWrapper(this,r,n),r=E.getNativeProps(this,r,n);break;case"select":T.mountWrapper(this,r,n),r=T.getNativeProps(this,r,n),n=T.processChildContext(this,r,n);break;case"textarea":O.mountWrapper(this,r,n),r=O.getNativeProps(this,r,n)}u(this,r);var o;if(t.useCreateElement){var i=n[S.ownerDocumentContextKey],a=i.createElement(this._currentElement.type);_.setAttributeForID(a,this._rootNodeID),S.getID(a),this._updateDOMProperties({},r,t,a),this._createInitialChildren(t,r,n,a),o=a}else{var s=this._createOpenTagMarkupAndPutListeners(t,r),l=this._createContentMarkup(t,r,n);o=!l&&Y[this._tag]?s+"/>":s+">"+l+"</"+this._currentElement.type+">"}switch(this._tag){case"input":t.getReactMountReady().enqueue(f,this);case"button":case"select":case"textarea":r.autoFocus&&t.getReactMountReady().enqueue(g.focusDOMComponent,this)}return o},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(q.hasOwnProperty(r))o&&l(this._rootNodeID,r,o,e);else{r===K&&(o&&(o=this._previousStyleCopy=M({},t.style)),o=y.createMarkupForStyles(o));var i=null;null!=this._tag&&m(this._tag,t)?r!==W&&(i=_.createMarkupForCustomAttribute(r,o)):i=_.createMarkupForProperty(r,o),i&&(n+=" "+i)}}if(e.renderToStaticMarkup)return n;var a=_.createMarkupForID(this._rootNodeID);return n+" "+a},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=V[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=I(i);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return $[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&L(r,o.__html);else{var i=V[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)U(r,i);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u<s.length;u++)r.appendChild(s[u])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,r){var o=t.props,i=this._currentElement.props;switch(this._tag){case"button":o=w.getNativeProps(this,o),i=w.getNativeProps(this,i);break;case"input":R.updateWrapper(this),o=R.getNativeProps(this,o),i=R.getNativeProps(this,i);break;case"option":o=E.getNativeProps(this,o),i=E.getNativeProps(this,i);break;case"select":o=T.getNativeProps(this,o),i=T.getNativeProps(this,i);break;case"textarea":O.updateWrapper(this),o=O.getNativeProps(this,o),i=O.getNativeProps(this,i)}u(this,i),this._updateDOMProperties(o,i,e,null),this._updateDOMChildren(o,i,e,r),!D&&this._nodeWithLegacyProperties&&(this._nodeWithLegacyProperties.props=i),"select"===this._tag&&e.getReactMountReady().enqueue(d,this)},_updateDOMProperties:function(e,t,n,r){var o,i,a;for(o in e)if(!t.hasOwnProperty(o)&&e.hasOwnProperty(o))if(o===K){var s=this._previousStyleCopy;for(i in s)s.hasOwnProperty(i)&&(a=a||{},a[i]="");this._previousStyleCopy=null}else q.hasOwnProperty(o)?e[o]&&H(this._rootNodeID,o):(b.properties[o]||b.isCustomAttribute(o))&&(r||(r=S.getNode(this._rootNodeID)),_.deleteValueForProperty(r,o));for(o in t){var u=t[o],c=o===K?this._previousStyleCopy:e[o];if(t.hasOwnProperty(o)&&u!==c)if(o===K)if(u?u=this._previousStyleCopy=M({},u):this._previousStyleCopy=null,c){for(i in c)!c.hasOwnProperty(i)||u&&u.hasOwnProperty(i)||(a=a||{},a[i]="");for(i in u)u.hasOwnProperty(i)&&c[i]!==u[i]&&(a=a||{},a[i]=u[i])}else a=u;else q.hasOwnProperty(o)?u?l(this._rootNodeID,o,u,n):c&&H(this._rootNodeID,o):m(this._tag,t)?(r||(r=S.getNode(this._rootNodeID)),o===W&&(u=null),_.setValueForAttribute(r,o,u)):(b.properties[o]||b.isCustomAttribute(o))&&(r||(r=S.getNode(this._rootNodeID)),null!=u?_.setValueForProperty(r,o,u):_.deleteValueForProperty(r,o))}a&&(r||(r=S.getNode(this._rootNodeID)),y.setValueForStyles(r,a))},_updateDOMChildren:function(e,t,n,r){var o=V[typeof e.children]?e.children:null,i=V[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,u=null!=o?null:e.children,l=null!=i?null:t.children,c=null!=o||null!=a,p=null!=i||null!=s;null!=u&&null==l?this.updateChildren(null,n,r):c&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=s?a!==s&&this.updateMarkup(""+s):null!=l&&this.updateChildren(l,n,r)},unmountComponent:function(){switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":var e=this._wrapperState.listeners;if(e)for(var t=0;t<e.length;t++)e[t].remove();break;case"input":R.unmountWrapper(this);break;case"html":case"head":case"body":A(!1)}if(this.unmountChildren(),P.deleteAllListeners(this._rootNodeID),C.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._wrapperState=null,this._nodeWithLegacyProperties){var n=this._nodeWithLegacyProperties;n._reactInternalComponent=null,this._nodeWithLegacyProperties=null}},getPublicInstance:function(){if(!this._nodeWithLegacyProperties){var e=S.getNode(this._rootNodeID);e._reactInternalComponent=this,e.getDOMNode=r,e.isMounted=o,e.setState=i,e.replaceState=i,e.forceUpdate=i,e.setProps=a,e.replaceProps=s,e.props=this._currentElement.props,this._nodeWithLegacyProperties=e}return this._nodeWithLegacyProperties}},N.measureMethods(v,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),M(v.prototype,v.Mixin,j.Mixin),e.exports=v},function(e,t,n){"use strict";var r=n(245),o=n(308),i=n(312),a={componentDidMount:function(){this.props.autoFocus&&i(o(this))}},s={Mixin:a,focusDOMComponent:function(){i(r.getNode(this._rootNodeID))}};e.exports=s},function(e,t){"use strict";function n(e){try{e.focus()}catch(t){}}e.exports=n},function(e,t,n){"use strict";var r=n(314),o=n(226),i=n(235),a=(n(315),n(317)),s=n(318),u=n(320),l=(n(242),u(function(e){return s(e)})),c=!1,p="cssFloat";if(o.canUseDOM){var f=document.createElement("div").style;try{f.font=""}catch(d){c=!0}void 0===document.documentElement.style.cssFloat&&(p="styleFloat")}var h={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=l(n)+":",t+=a(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var o in t)if(t.hasOwnProperty(o)){var i=a(o,t[o]);if("float"===o&&(o=p),i)n[o]=i;else{var s=c&&r.shorthandPropertyExpansions[o];if(s)for(var u in s)n[u]="";else n[o]=""}}}};i.measureMethods(h,"CSSPropertyOperations",{setValueForStyles:"setValueForStyles"}),e.exports=h},function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={animationIterationCount:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,stopOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};e.exports=a},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(316),i=/^-ms-/;e.exports=r},function(e,t){"use strict";function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;e.exports=n},function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=n(314),i=o.isUnitlessNumber;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(319),i=/^ms-/;e.exports=r},function(e,t){"use strict";function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;e.exports=n},function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=n},function(e,t){"use strict";var n={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},r={getNativeProps:function(e,t,r){if(!t.disabled)return t;var o={};for(var i in t)t.hasOwnProperty(i)&&!n[i]&&(o[i]=t[i]);return o}};e.exports=r},function(e,t,n){"use strict";function r(){this._rootNodeID&&f.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);u.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var i=s.getNode(this._rootNodeID),l=i;l.parentNode;)l=l.parentNode;for(var f=l.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),d=0;d<f.length;d++){var h=f[d];if(h!==i&&h.form===i.form){var m=s.getID(h);m?void 0:c(!1);var v=p[m];v?void 0:c(!1),u.asap(r,v)}}}return n}var i=n(244),a=n(323),s=n(245),u=n(271),l=n(256),c=n(230),p={},f={getNativeProps:function(e,t,n){var r=a.getValue(t),o=a.getChecked(t),i=l({},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=r?r:e._wrapperState.initialValue,checked:null!=o?o:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange});return i},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:t.defaultChecked||!1,initialValue:null!=n?n:null,onChange:o.bind(e)}},mountReadyWrapper:function(e){p[e._rootNodeID]=e},unmountWrapper:function(e){delete p[e._rootNodeID]},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&i.updatePropertyByID(e._rootNodeID,"checked",n||!1);var r=a.getValue(t);null!=r&&i.updatePropertyByID(e._rootNodeID,"value",""+r)}};e.exports=f},function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?l(!1):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?l(!1):void 0}function i(e){r(e),null!=e.checked||null!=e.onChange?l(!1):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=n(324),u=n(282),l=n(230),c=(n(242),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),p={value:function(e,t,n){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func},f={},d={checkPropTypes:function(e,t,n){for(var r in p){if(p.hasOwnProperty(r))var o=p[r](t,r,e,u.prop);if(o instanceof Error&&!(o.message in f)){f[o.message]=!0;a(n)}}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=d},function(e,t,n){"use strict";function r(e){function t(t,n,r,o,i,a){if(o=o||P,a=a||r,null==n[r]){var s=b[i];return t?new Error("Required "+s+" `"+a+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i,a)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o,i){var a=t[n],s=m(a);if(s!==e){var u=b[o],l=v(a);return new Error("Invalid "+u+" `"+i+"` of type "+("`"+l+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return r(t)}function i(){return r(_.thatReturns(null))}function a(e){function t(t,n,r,o,i){var a=t[n];if(!Array.isArray(a)){var s=b[o],u=m(a);return new Error("Invalid "+s+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var l=0;l<a.length;l++){var c=e(a,l,r,o,i+"["+l+"]");if(c instanceof Error)return c}return null}return r(t)}function s(){function e(e,t,n,r,o){if(!y.isValidElement(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return r(e)}function u(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=b[o],s=e.name||P,u=g(t[n]);return new Error("Invalid "+a+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected ")+("instance of `"+s+"`."))}return null}return r(t)}function l(e){function t(t,n,r,o,i){for(var a=t[n],s=0;s<e.length;s++)if(a===e[s])return null;var u=b[o],l=JSON.stringify(e);return new Error("Invalid "+u+" `"+i+"` of value `"+a+"` "+("supplied to `"+r+"`, expected one of "+l+"."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function c(e){function t(t,n,r,o,i){var a=t[n],s=m(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an object."))}for(var l in a)if(a.hasOwnProperty(l)){var c=e(a,l,r,o,i+"."+l);if(c instanceof Error)return c}return null}return r(t)}function p(e){function t(t,n,r,o,i){for(var a=0;a<e.length;a++){var s=e[a];if(null==s(t,n,r,o,i))return null}var u=b[o];return new Error("Invalid "+u+" `"+i+"` supplied to "+("`"+r+"`."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function f(){function e(e,t,n,r,o){if(!h(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function d(e){function t(t,n,r,o,i){var a=t[n],s=m(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type `"+s+"` "+("supplied to `"+r+"`, expected `object`."))}for(var l in e){var c=e[l];if(c){var p=c(a,l,r,o,i+"."+l);if(p)return p}}return null}return r(t)}function h(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(h);if(null===e||y.isValidElement(e))return!0;var t=x(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!h(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!h(o[1]))return!1}return!0;default:return!1}}function m(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function v(e){var t=m(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function g(e){return e.constructor&&e.constructor.name?e.constructor.name:"<<anonymous>>"}var y=n(259),b=n(283),_=n(232),x=n(325),P="<<anonymous>>",C={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:i(),arrayOf:a,element:s(),instanceOf:u,node:f(),objectOf:c,oneOf:l,oneOfType:p,shape:d};e.exports=C},function(e,t){"use strict";function n(e){var t=e&&(r&&e[r]||e[o]);return"function"==typeof t?t:void 0}var r="function"==typeof Symbol&&Symbol.iterator,o="@@iterator";e.exports=n},function(e,t,n){"use strict";var r=n(327),o=n(329),i=n(256),a=(n(242),o.valueContextKey),s={mountWrapper:function(e,t,n){var r=n[a],o=null;if(null!=r)if(o=!1,Array.isArray(r)){for(var i=0;i<r.length;i++)if(""+r[i]==""+t.value){o=!0;break}}else o=""+r==""+t.value;e._wrapperState={selected:o}},getNativeProps:function(e,t,n){var o=i({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(o.selected=e._wrapperState.selected);var a="";return r.forEach(t.children,function(e){null!=e&&("string"==typeof e||"number"==typeof e)&&(a+=e)}),a&&(o.children=a),o}};e.exports=s},function(e,t,n){"use strict";function r(e){return(""+e).replace(_,"//")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);g(e,i,r),o.release(r)}function s(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function u(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,s=e.context,u=a.call(s,t,e.count++);Array.isArray(u)?l(u,o,n,v.thatReturnsArgument):null!=u&&(m.isValidElement(u)&&(u=m.cloneAndReplaceKey(u,i+(u!==t?r(u.key||"")+"/":"")+n)),o.push(u))}function l(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var l=s.getPooled(t,a,o,i);g(e,u,l),s.release(l)}function c(e,t,n){if(null==e)return e;var r=[];return l(e,r,null,t,n),r}function p(e,t,n){return null}function f(e,t){return g(e,p,null)}function d(e){var t=[];return l(e,t,null,v.thatReturnsArgument),t}var h=n(273),m=n(259),v=n(232),g=n(328),y=h.twoArgumentPooler,b=h.fourArgumentPooler,_=/\/(?!\/)/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(o,y),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(s,b);var x={forEach:a,map:c,mapIntoWithKeyPrefixInternal:l,count:f,toArray:d};e.exports=x},function(e,t,n){"use strict";function r(e){return m[e]}function o(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(v,r)}function a(e){return"$"+i(e)}function s(e,t,n,r){var i=typeof e;if(("undefined"===i||"boolean"===i)&&(e=null),null===e||"string"===i||"number"===i||l.isValidElement(e))return n(r,e,""===t?d+o(e,0):t),1;var u,c,m=0,v=""===t?d:t+h;if(Array.isArray(e))for(var g=0;g<e.length;g++)u=e[g],c=v+o(u,g),m+=s(u,c,n,r);else{var y=p(e);if(y){var b,_=y.call(e);if(y!==e.entries)for(var x=0;!(b=_.next()).done;)u=b.value,c=v+o(u,x++),m+=s(u,c,n,r);else for(;!(b=_.next()).done;){var P=b.value;P&&(u=P[1],c=v+a(P[0])+h+o(u,0), m+=s(u,c,n,r))}}else if("object"===i){String(e);f(!1)}}return m}function u(e,t,n){return null==e?0:s(e,"",t,n)}var l=(n(222),n(259)),c=n(262),p=n(325),f=n(230),d=(n(242),c.SEPARATOR),h=":",m={"=":"=0",".":"=1",":":"=2"},v=/[=.:]/g;e.exports=u},function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=a.getValue(e);null!=t&&o(this,Boolean(e.multiple),t)}}function o(e,t,n){var r,o,i=s.getNode(e._rootNodeID).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<i.length;o++){var a=r.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(r=""+n,o=0;o<i.length;o++)if(i[o].value===r)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}function i(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);return this._wrapperState.pendingUpdate=!0,u.asap(r,this),n}var a=n(323),s=n(245),u=n(271),l=n(256),c=(n(242),"__ReactDOMSelect_value$"+Math.random().toString(36).slice(2)),p={valueContextKey:c,getNativeProps:function(e,t,n){return l({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=a.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)}},processChildContext:function(e,t,n){var r=l({},n);return r[c]=e._wrapperState.initialValue,r},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=a.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};e.exports=p},function(e,t,n){"use strict";function r(){this._rootNodeID&&c.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=i.executeOnChange(t,e);return s.asap(r,this),n}var i=n(323),a=n(244),s=n(271),u=n(256),l=n(230),c=(n(242),{getNativeProps:function(e,t,n){null!=t.dangerouslySetInnerHTML?l(!1):void 0;var r=u({},t,{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return r},mountWrapper:function(e,t){var n=t.defaultValue,r=t.children;null!=r&&(null!=n?l(!1):void 0,Array.isArray(r)&&(r.length<=1?void 0:l(!1),r=r[0]),n=""+r),null==n&&(n="");var a=i.getValue(t);e._wrapperState={initialValue:""+(null!=a?a:n),onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=i.getValue(t);null!=n&&a.updatePropertyByID(e._rootNodeID,"value",""+n)}});e.exports=c},function(e,t,n){"use strict";function r(e,t,n){v.push({parentID:e,parentNode:null,type:p.INSERT_MARKUP,markupIndex:g.push(t)-1,content:null,fromIndex:null,toIndex:n})}function o(e,t,n){v.push({parentID:e,parentNode:null,type:p.MOVE_EXISTING,markupIndex:null,content:null,fromIndex:t,toIndex:n})}function i(e,t){v.push({parentID:e,parentNode:null,type:p.REMOVE_NODE,markupIndex:null,content:null,fromIndex:t,toIndex:null})}function a(e,t){v.push({parentID:e,parentNode:null,type:p.SET_MARKUP,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function s(e,t){v.push({parentID:e,parentNode:null,type:p.TEXT_CONTENT,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function u(){v.length&&(c.processChildrenUpdates(v,g),l())}function l(){v.length=0,g.length=0}var c=n(281),p=n(233),f=(n(222),n(267)),d=n(332),h=n(333),m=0,v=[],g=[],y={Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return d.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r){var o;return o=h(t),d.updateChildren(e,o,n,r)},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=this._rootNodeID+a,l=f.mountComponent(s,u,t,n);s._mountIndex=i++,o.push(l)}return o},updateTextContent:function(e){m++;var t=!0;try{var n=this._renderedChildren;d.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChild(n[r]);this.setTextContent(e),t=!1}finally{m--,m||(t?l():u())}},updateMarkup:function(e){m++;var t=!0;try{var n=this._renderedChildren;d.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setMarkup(e),t=!1}finally{m--,m||(t?l():u())}},updateChildren:function(e,t,n){m++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{m--,m||(r?l():u())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=this._reconcilerUpdateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var i,a=0,s=0;for(i in o)if(o.hasOwnProperty(i)){var u=r&&r[i],l=o[i];u===l?(this.moveChild(u,s,a),a=Math.max(u._mountIndex,a),u._mountIndex=s):(u&&(a=Math.max(u._mountIndex,a),this._unmountChild(u)),this._mountChildByNameAtIndex(l,i,s,t,n)),s++}for(i in r)!r.hasOwnProperty(i)||o&&o.hasOwnProperty(i)||this._unmountChild(r[i])}},unmountChildren:function(){var e=this._renderedChildren;d.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){s(this._rootNodeID,e)},setMarkup:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var i=this._rootNodeID+t,a=f.mountComponent(e,i,r,o);e._mountIndex=n,this.createChild(e,a)},_unmountChild:function(e){this.removeChild(e),e._mountIndex=null}}};e.exports=y},function(e,t,n){"use strict";function r(e,t,n){var r=void 0===e[n];null!=t&&r&&(e[n]=i(t,null))}var o=n(267),i=n(279),a=n(284),s=n(328),u=(n(242),{instantiateChildren:function(e,t,n){if(null==e)return null;var o={};return s(e,r,o),o},updateChildren:function(e,t,n,r){if(!t&&!e)return null;var s;for(s in t)if(t.hasOwnProperty(s)){var u=e&&e[s],l=u&&u._currentElement,c=t[s];if(null!=u&&a(l,c))o.receiveComponent(u,c,n,r),t[s]=u;else{u&&o.unmountComponent(u,s);var p=i(c,null);t[s]=p}}for(s in e)!e.hasOwnProperty(s)||t&&t.hasOwnProperty(s)||o.unmountComponent(e[s]);return t},unmountChildren:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];o.unmountComponent(n)}}});e.exports=u},function(e,t,n){"use strict";function r(e,t,n){var r=e,o=void 0===r[n];o&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,r,t),t}var i=n(328);n(242);e.exports=o},function(e,t){"use strict";function n(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var i=r.bind(t),a=0;a<n.length;a++)if(!i(n[a])||e[n[a]]!==t[n[a]])return!1;return!0}var r=Object.prototype.hasOwnProperty;e.exports=n},function(e,t,n){"use strict";function r(e){var t=f.getID(e),n=p.getReactRootIDFromNodeID(t),r=f.findReactContainerForID(n),o=f.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){a(e)}function a(e){for(var t=f.getFirstReactDOM(m(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0;o<e.ancestors.length;o++){t=e.ancestors[o];var i=f.getID(t)||"";g._handleTopLevel(e.topLevelType,t,i,e.nativeEvent,m(e.nativeEvent))}}function s(e){var t=v(window);e(t)}var u=n(336),l=n(226),c=n(273),p=n(262),f=n(245),d=n(271),h=n(256),m=n(298),v=n(337);h(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),c.addPoolingTo(o,c.twoArgumentPooler);var g={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:l.canUseDOM?window:null,setHandleTopLevel:function(e){g._handleTopLevel=e},setEnabled:function(e){g._enabled=!!e},isEnabled:function(){return g._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?u.listen(r,t,g.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?u.capture(r,t,g.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=s.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(g._enabled){var n=o.getPooled(e,t);try{d.batchedUpdates(i,n)}finally{o.release(n)}}}};e.exports=g},function(e,t,n){"use strict";var r=n(232),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};e.exports=o},function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=n},function(e,t,n){"use strict";var r=n(240),o=n(248),i=n(281),a=n(339),s=n(285),u=n(246),l=n(286),c=n(235),p=n(263),f=n(271),d={Component:i.injection,Class:a.injection,DOMProperty:r.injection,EmptyComponent:s.injection,EventPluginHub:o.injection,EventEmitter:u.injection,NativeComponent:l.injection,Perf:c.injection,RootIndex:p.injection,Updates:f.injection};e.exports=d},function(e,t,n){"use strict";function r(e,t){var n=P.hasOwnProperty(t)?P[t]:null;w.hasOwnProperty(t)&&(n!==_.OVERRIDE_BASE?v(!1):void 0),e.hasOwnProperty(t)&&(n!==_.DEFINE_MANY&&n!==_.DEFINE_MANY_MERGED?v(!1):void 0)}function o(e,t){if(t){"function"==typeof t?v(!1):void 0,f.isValidElement(t)?v(!1):void 0;var n=e.prototype;t.hasOwnProperty(b)&&C.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==b){var i=t[o];if(r(n,o),C.hasOwnProperty(o))C[o](e,i);else{var a=P.hasOwnProperty(o),l=n.hasOwnProperty(o),c="function"==typeof i,p=c&&!a&&!l&&t.autobind!==!1;if(p)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[o]=i,n[o]=i;else if(l){var d=P[o];!a||d!==_.DEFINE_MANY_MERGED&&d!==_.DEFINE_MANY?v(!1):void 0,d===_.DEFINE_MANY_MERGED?n[o]=s(n[o],i):d===_.DEFINE_MANY&&(n[o]=u(n[o],i))}else n[o]=i}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in C;o?v(!1):void 0;var i=n in e;i?v(!1):void 0,e[n]=r}}}function a(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:v(!1);for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]?v(!1):void 0,e[n]=t[n]);return e}function s(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return a(o,n),a(o,r),o}}function u(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var n=t.bind(e);return n}function c(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=l(e,n)}}var p=n(340),f=n(259),d=(n(282),n(283),n(341)),h=n(256),m=n(275),v=n(230),g=n(234),y=n(296),b=(n(242),y({mixins:null})),_=g({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),x=[],P={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},C={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=h({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=h({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=s(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=h({},e.propTypes,t)},statics:function(e,t){i(e,t)},autobind:function(){}},w={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t)},isMounted:function(){return this.updater.isMounted(this)},setProps:function(e,t){this.updater.enqueueSetProps(this,e),t&&this.updater.enqueueCallback(this,t)},replaceProps:function(e,t){this.updater.enqueueReplaceProps(this,e),t&&this.updater.enqueueCallback(this,t)}},R=function(){};h(R.prototype,p.prototype,w);var E={createClass:function(e){var t=function(e,t,n){this.__reactAutoBindMap&&c(this),this.props=e,this.context=t,this.refs=m,this.updater=n||d,this.state=null;var r=this.getInitialState?this.getInitialState():null;"object"!=typeof r||Array.isArray(r)?v(!1):void 0,this.state=r};t.prototype=new R,t.prototype.constructor=t,x.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:v(!1);for(var n in P)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){x.push(e)}}};e.exports=E},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=i,this.updater=n||o}var o=n(341),i=(n(260),n(275)),a=n(230);n(242);r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?a(!1):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e)};e.exports=r},function(e,t,n){"use strict";function r(e,t){}var o=(n(242),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")},enqueueSetProps:function(e,t){r(e,"setProps")},enqueueReplaceProps:function(e,t){r(e,"replaceProps")}});e.exports=o},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.useCreateElement=!e&&s.useCreateElement}var o=n(272),i=n(273),a=n(246),s=n(258),u=n(343),l=n(274),c=n(256),p={initialize:u.getSelectionInformation,close:u.restoreSelection},f={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h=[p,f,d],m={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null}};c(r.prototype,l.Mixin,m),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=n(344),i=n(276),a=n(312),s=n(346),u={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:u.hasSelectionCapabilities(e)?u.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(u.hasSelectionCapabilities(n)&&u.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};e.exports=u},function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0);try{s.startContainer.nodeType,s.endContainer.nodeType}catch(u){return null}var l=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=l?0:s.toString().length,p=s.cloneRange();p.selectNodeContents(e),p.setEnd(s.startContainer,s.startOffset);var f=r(p.startContainer,p.startOffset,p.endContainer,p.endOffset),d=f?0:p.toString().length,h=d+c,m=document.createRange();m.setStart(n,o),m.setEnd(i,a);var v=m.collapsed;return{start:v?h:d,end:v?d:h}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=l(e,o),u=l(e,i);if(s&&u){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(u.node,u.offset)):(p.setEnd(u.node,u.offset),n.addRange(p))}}}var u=n(226),l=n(345),c=n(292),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),f={getOffsets:p?o:i,setOffsets:p?a:s};e.exports=f},function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3===o.nodeType){if(a=i+o.textContent.length,t>=i&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}e.exports=o},function(e,t){"use strict";function n(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=n},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(_||null==g||g!==c())return null;var n=r(g);if(!b||!d(b,n)){b=n;var o=l.getPooled(v.select,y,e,t);return o.type="select",o.target=g,a.accumulateTwoPhaseDispatches(o),o}return null}var i=n(247),a=n(290),s=n(226),u=n(343),l=n(294),c=n(346),p=n(299),f=n(296),d=n(334),h=i.topLevelTypes,m=s.canUseDOM&&"documentMode"in document&&document.documentMode<=11,v={select:{phasedRegistrationNames:{bubbled:f({onSelect:null}),captured:f({onSelectCapture:null})},dependencies:[h.topBlur,h.topContextMenu,h.topFocus,h.topKeyDown,h.topMouseDown,h.topMouseUp,h.topSelectionChange]}},g=null,y=null,b=null,_=!1,x=!1,P=f({onSelect:null}),C={eventTypes:v,extractEvents:function(e,t,n,r,i){if(!x)return null;switch(e){case h.topFocus:(p(t)||"true"===t.contentEditable)&&(g=t,y=n,b=null);break;case h.topBlur:g=null,y=null,b=null;break;case h.topMouseDown:_=!0;break;case h.topContextMenu:case h.topMouseUp:return _=!1,o(r,i);case h.topSelectionChange:if(m)break;case h.topKeyDown:case h.topKeyUp:return o(r,i)}return null},didPutListener:function(e,t,n){t===P&&(x=!0)}};e.exports=C},function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};e.exports=r},function(e,t,n){"use strict";var r=n(247),o=n(336),i=n(290),a=n(245),s=n(350),u=n(294),l=n(351),c=n(352),p=n(303),f=n(355),d=n(356),h=n(304),m=n(357),v=n(232),g=n(353),y=n(230),b=n(296),_=r.topLevelTypes,x={abort:{phasedRegistrationNames:{bubbled:b({onAbort:!0}),captured:b({onAbortCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:b({onBlur:!0}),captured:b({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:b({onCanPlay:!0}),captured:b({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:b({onCanPlayThrough:!0}),captured:b({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:b({onClick:!0}),captured:b({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:b({onContextMenu:!0}),captured:b({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:b({onCopy:!0}),captured:b({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:b({onCut:!0}),captured:b({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:b({onDoubleClick:!0}),captured:b({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:b({onDrag:!0}),captured:b({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:b({onDragEnd:!0}),captured:b({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:b({onDragEnter:!0}),captured:b({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:b({onDragExit:!0}),captured:b({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:b({onDragLeave:!0}),captured:b({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:b({onDragOver:!0}),captured:b({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:b({onDragStart:!0}),captured:b({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:b({onDrop:!0}),captured:b({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:b({onDurationChange:!0}),captured:b({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:b({onEmptied:!0}),captured:b({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:b({onEncrypted:!0}),captured:b({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:b({onEnded:!0}),captured:b({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:b({onError:!0}),captured:b({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:b({onFocus:!0}),captured:b({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:b({onInput:!0}),captured:b({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:b({onKeyDown:!0}),captured:b({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:b({onKeyPress:!0}),captured:b({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:b({onKeyUp:!0}),captured:b({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:b({onLoad:!0}),captured:b({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:b({onLoadedData:!0}),captured:b({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:b({onLoadedMetadata:!0}),captured:b({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:b({onLoadStart:!0}),captured:b({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:b({onMouseDown:!0}),captured:b({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:b({onMouseMove:!0}),captured:b({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:b({onMouseOut:!0}),captured:b({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:b({onMouseOver:!0}),captured:b({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:b({onMouseUp:!0}),captured:b({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:b({onPaste:!0}),captured:b({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:b({onPause:!0}),captured:b({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:b({onPlay:!0}),captured:b({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:b({onPlaying:!0}),captured:b({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:b({onProgress:!0}),captured:b({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:b({onRateChange:!0}),captured:b({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:b({onReset:!0}),captured:b({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:b({onScroll:!0}),captured:b({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:b({onSeeked:!0}),captured:b({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:b({onSeeking:!0}),captured:b({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:b({onStalled:!0}),captured:b({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:b({onSubmit:!0}),captured:b({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:b({onSuspend:!0}),captured:b({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:b({onTimeUpdate:!0}),captured:b({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:b({onTouchCancel:!0}),captured:b({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:b({onTouchEnd:!0}),captured:b({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:b({onTouchMove:!0}),captured:b({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:b({onTouchStart:!0}),captured:b({onTouchStartCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:b({onVolumeChange:!0}),captured:b({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:b({onWaiting:!0}),captured:b({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:b({onWheel:!0}),captured:b({onWheelCapture:!0})}}},P={topAbort:x.abort,topBlur:x.blur,topCanPlay:x.canPlay,topCanPlayThrough:x.canPlayThrough,topClick:x.click,topContextMenu:x.contextMenu,topCopy:x.copy,topCut:x.cut,topDoubleClick:x.doubleClick,topDrag:x.drag,topDragEnd:x.dragEnd,topDragEnter:x.dragEnter,topDragExit:x.dragExit,topDragLeave:x.dragLeave,topDragOver:x.dragOver,topDragStart:x.dragStart,topDrop:x.drop,topDurationChange:x.durationChange,topEmptied:x.emptied,topEncrypted:x.encrypted,topEnded:x.ended,topError:x.error,topFocus:x.focus,topInput:x.input,topKeyDown:x.keyDown,topKeyPress:x.keyPress,topKeyUp:x.keyUp,topLoad:x.load,topLoadedData:x.loadedData,topLoadedMetadata:x.loadedMetadata,topLoadStart:x.loadStart,topMouseDown:x.mouseDown,topMouseMove:x.mouseMove,topMouseOut:x.mouseOut,topMouseOver:x.mouseOver,topMouseUp:x.mouseUp,topPaste:x.paste,topPause:x.pause,topPlay:x.play,topPlaying:x.playing,topProgress:x.progress,topRateChange:x.rateChange,topReset:x.reset,topScroll:x.scroll,topSeeked:x.seeked,topSeeking:x.seeking,topStalled:x.stalled,topSubmit:x.submit,topSuspend:x.suspend,topTimeUpdate:x.timeUpdate,topTouchCancel:x.touchCancel,topTouchEnd:x.touchEnd,topTouchMove:x.touchMove,topTouchStart:x.touchStart,topVolumeChange:x.volumeChange,topWaiting:x.waiting,topWheel:x.wheel};for(var C in P)P[C].dependencies=[C];var w=b({onClick:null}),R={},E={eventTypes:x,extractEvents:function(e,t,n,r,o){var a=P[e];if(!a)return null;var v;switch(e){case _.topAbort:case _.topCanPlay:case _.topCanPlayThrough:case _.topDurationChange:case _.topEmptied:case _.topEncrypted:case _.topEnded:case _.topError:case _.topInput:case _.topLoad:case _.topLoadedData:case _.topLoadedMetadata:case _.topLoadStart:case _.topPause:case _.topPlay:case _.topPlaying:case _.topProgress:case _.topRateChange:case _.topReset:case _.topSeeked:case _.topSeeking:case _.topStalled:case _.topSubmit:case _.topSuspend:case _.topTimeUpdate:case _.topVolumeChange:case _.topWaiting:v=u;break;case _.topKeyPress:if(0===g(r))return null;case _.topKeyDown:case _.topKeyUp:v=c;break;case _.topBlur:case _.topFocus:v=l;break;case _.topClick:if(2===r.button)return null;case _.topContextMenu:case _.topDoubleClick:case _.topMouseDown:case _.topMouseMove:case _.topMouseOut:case _.topMouseOver:case _.topMouseUp:v=p;break;case _.topDrag:case _.topDragEnd:case _.topDragEnter:case _.topDragExit:case _.topDragLeave:case _.topDragOver:case _.topDragStart:case _.topDrop:v=f;break;case _.topTouchCancel:case _.topTouchEnd:case _.topTouchMove:case _.topTouchStart:v=d;break;case _.topScroll:v=h;break;case _.topWheel:v=m;break;case _.topCopy:case _.topCut:case _.topPaste:v=s}v?void 0:y(!1);var b=v.getPooled(a,n,r,o);return i.accumulateTwoPhaseDispatches(b),b},didPutListener:function(e,t,n){if(t===w){var r=a.getNode(e);R[e]||(R[e]=o.listen(r,"click",v))}},willDeleteListener:function(e,t){t===w&&(R[e].remove(),delete R[e])}};e.exports=E},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(294),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(304),i={relatedTarget:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(304),i=n(353),a=n(354),s=n(305),u={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,u),e.exports=r},function(e,t){"use strict";function n(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}e.exports=n},function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=n(353),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(303),i={dataTransfer:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(304),i=n(305),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(303),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";var r=n(240),o=r.injection.MUST_USE_ATTRIBUTE,i={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},a={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,xlinkActuate:o,xlinkArcrole:o,xlinkHref:o,xlinkRole:o,xlinkShow:o,xlinkTitle:o,xlinkType:o,xmlBase:o,xmlLang:o,xmlSpace:o,y1:o,y2:o,y:o},DOMAttributeNamespaces:{xlinkActuate:i.xlink,xlinkArcrole:i.xlink,xlinkHref:i.xlink,xlinkRole:i.xlink,xlinkShow:i.xlink, xlinkTitle:i.xlink,xlinkType:i.xlink,xmlBase:i.xml,xmlLang:i.xml,xmlSpace:i.xml},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xml:space"}};e.exports=a},function(e,t){"use strict";e.exports="0.14.7"},function(e,t,n){"use strict";var r=n(245);e.exports=r.renderSubtreeIntoContainer},function(e,t,n){"use strict";var r=n(288),o=n(362),i=n(359);r.inject();var a={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:i};e.exports=a},function(e,t,n){"use strict";function r(e){a.isValidElement(e)?void 0:h(!1);var t;try{p.injection.injectBatchingStrategy(l);var n=s.createReactRootID();return t=c.getPooled(!1),t.perform(function(){var r=d(e,null),o=r.mountComponent(n,t,f);return u.addChecksumToMarkup(o)},null)}finally{c.release(t),p.injection.injectBatchingStrategy(i)}}function o(e){a.isValidElement(e)?void 0:h(!1);var t;try{p.injection.injectBatchingStrategy(l);var n=s.createReactRootID();return t=c.getPooled(!0),t.perform(function(){var r=d(e,null);return r.mountComponent(n,t,f)},null)}finally{c.release(t),p.injection.injectBatchingStrategy(i)}}var i=n(309),a=n(259),s=n(262),u=n(265),l=n(363),c=n(364),p=n(271),f=n(275),d=n(279),h=n(230);e.exports={renderToString:r,renderToStaticMarkup:o}},function(e,t){"use strict";var n={isBatchingUpdates:!1,batchedUpdates:function(e){}};e.exports=n},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null),this.useCreateElement=!1}var o=n(273),i=n(272),a=n(274),s=n(256),u=n(232),l={initialize:function(){this.reactMountReady.reset()},close:u},c=[l],p={getTransactionWrappers:function(){return c},getReactMountReady:function(){return this.reactMountReady},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};s(r.prototype,a.Mixin,p),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(327),o=n(340),i=n(339),a=n(366),s=n(259),u=(n(367),n(324)),l=n(359),c=n(256),p=n(369),f=s.createElement,d=s.createFactory,h=s.cloneElement,m={Children:{map:r.map,forEach:r.forEach,count:r.count,toArray:r.toArray,only:p},Component:o,createElement:f,cloneElement:h,isValidElement:s.isValidElement,PropTypes:u,createClass:i.createClass,createFactory:d,createMixin:function(e){return e},DOM:a,version:l,__spread:c};e.exports=m},function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=n(259),i=(n(367),n(368)),a=i({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hgroup:"hgroup",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",image:"image",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);e.exports=a},function(e,t,n){"use strict";function r(){if(p.current){var e=p.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;i("uniqueKey",e,t)}}function i(e,t,n){var o=r();if(!o){var i="string"==typeof n?n:n.displayName||n.name;i&&(o=" Check the top-level render call using <"+i+">.")}var a=h[e]||(h[e]={});if(a[o])return null;a[o]=!0;var s={parentOrOwner:o,url:" See https://fb.me/react-warning-keys for more information.",childOwner:null};return t&&t._owner&&t._owner!==p.current&&(s.childOwner=" It was passed a child from "+t._owner.getName()+"."),s}function a(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];l.isValidElement(r)&&o(r,t)}else if(l.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var i=f(e);if(i&&i!==e.entries)for(var a,s=i.call(e);!(a=s.next()).done;)l.isValidElement(a.value)&&o(a.value,t)}}function s(e,t,n,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{"function"!=typeof t[i]?d(!1):void 0,a=t[i](n,i,e,o)}catch(s){a=s}if(a instanceof Error&&!(a.message in m)){m[a.message]=!0;r()}}}function u(e){var t=e.type;if("function"==typeof t){var n=t.displayName||t.name;t.propTypes&&s(n,t.propTypes,e.props,c.prop),"function"==typeof t.getDefaultProps}}var l=n(259),c=n(282),p=(n(283),n(222)),f=(n(260),n(325)),d=n(230),h=(n(242),{}),m={},v={createElement:function(e,t,n){var r="string"==typeof e||"function"==typeof e,o=l.createElement.apply(this,arguments);if(null==o)return o;if(r)for(var i=2;i<arguments.length;i++)a(arguments[i],e);return u(o),o},createFactory:function(e){var t=v.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=l.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)a(arguments[o],r.type);return u(r),r}};e.exports=v},function(e,t){"use strict";function n(e,t,n){if(!e)return null;var o={};for(var i in e)r.call(e,i)&&(o[i]=t.call(n,e[i],i,e));return o}var r=Object.prototype.hasOwnProperty;e.exports=n},function(e,t,n){"use strict";function r(e){return o.isValidElement(e)?void 0:i(!1),e}var o=n(259),i=n(230);e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r,o){return o}n(256),n(242);e.exports=r},function(e,t,n){(function(t){e.exports=t.ReactDOM=n(372)}).call(t,function(){return this}())},function(e,t,n){"use strict";e.exports=n(221)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function i(e){var t="string"==typeof e,n=void 0;if(n=t?document.querySelector(e):e,!a(n)){var r="Container must be `string` or `HTMLElement`.";throw t&&(r+=" Unable to find "+e),new Error(r)}return n}function a(e){return e instanceof HTMLElement||!!e&&e.nodeType>0}function s(e){var t=1===e.button;return t||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey}function u(e){return function(t,n){return t||n?t&&!n?e+"--"+t:t&&n?e+"--"+t+"__"+n:!t&&n?e+"__"+n:void 0:e}}function l(e){var t=e.transformData,n=e.defaultTemplates,r=e.templates,o=e.templatesConfig,i=c(n,r);return m({transformData:t,templatesConfig:o},i)}function c(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=(0,S["default"])([].concat(o((0,T["default"])(e)),o((0,T["default"])(t))));return(0,g["default"])(n,function(n,r){var o=e[r],i=t[r],a=void 0!==i&&i!==o;return n.templates[r]=a?i:o,n.useCustomCompileOptions[r]=a,n},{templates:{},useCustomCompileOptions:{}})}function p(e,t,n,r,o){var i={type:t,attributeName:n,name:r},a=(0,x["default"])(o,{name:n}),s=void 0;if("hierarchical"===t){var u=e.getHierarchicalFacetByName(n),l=r.split(u.separator);i.name=l[l.length-1];for(var c=0;void 0!==a&&c<l.length;++c)a=(0,x["default"])(a.data,{name:l[c]});s=(0,C["default"])(a,"count")}else s=(0,C["default"])(a,'data["'+i.name+'"]');var p=(0,C["default"])(a,"exhaustive");return void 0!==s&&(i.count=s),void 0!==p&&(i.exhaustive=p),i}function f(e,t){var n=[];return(0,b["default"])(t.facetsRefinements,function(r,o){(0,b["default"])(r,function(r){n.push(p(t,"facet",o,r,e.facets))})}),(0,b["default"])(t.facetsExcludes,function(e,t){(0,b["default"])(e,function(e){n.push({type:"exclude",attributeName:t,name:e,exclude:!0})})}),(0,b["default"])(t.disjunctiveFacetsRefinements,function(r,o){(0,b["default"])(r,function(r){n.push(p(t,"disjunctive",o,r,e.disjunctiveFacets))})}),(0,b["default"])(t.hierarchicalFacetsRefinements,function(r,o){(0,b["default"])(r,function(r){n.push(p(t,"hierarchical",o,r,e.hierarchicalFacets))})}),(0,b["default"])(t.numericRefinements,function(e,t){(0,b["default"])(e,function(e,r){(0,b["default"])(e,function(e){e+="",n.push({type:"numeric",attributeName:t,name:e,operator:r})})})}),(0,b["default"])(t.tagRefinements,function(e){n.push({type:"tag",attributeName:"_tags",name:e})}),n}function d(e,t){return(0,R["default"])(t)?(e=e.clearTags(),e=e.clearRefinements()):((0,b["default"])(t,function(t){e="_tags"===t?e.clearTags():e.clearRefinements(t)}),e)}function h(e,t){e.setState(d(e.state,t)).search()}Object.defineProperty(t,"__esModule",{value:!0});var m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},v=n(111),g=r(v),y=n(14),b=r(y),_=n(128),x=r(_),P=n(374),C=r(P),w=n(124),R=r(w),E=n(22),T=r(E),O=n(375),S=r(O),j={getContainerNode:i,bemHelper:u,prepareTemplateProps:l,isSpecialClick:s,isDomElement:a,getRefinements:f,clearRefinementsFromState:d,clearRefinementsAndSearch:h};t["default"]=j,e.exports=t["default"]},function(e,t,n){function r(e,t,n){var r=null==e?void 0:o(e,i(t),t+"");return void 0===r?n:r}var o=n(69),i=n(73);e.exports=r},function(e,t,n){function r(e,t,n,r){var u=e?e.length:0;return u?(null!=t&&"boolean"!=typeof t&&(r=n,n=a(e,t,r)?void 0:t,t=!1),n=null==n?n:o(n,r,3),t?s(e,n):i(e,n)):[]}var o=n(55),i=n(212),a=n(52),s=n(376);e.exports=r},function(e,t){function n(e,t){for(var n,r=-1,o=e.length,i=-1,a=[];++r<o;){var s=e[r],u=t?t(s,r,e):s;r&&n===u||(n=u,a[++i]=s)}return a}e.exports=n},function(e,t,n){var r,o;!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var a in r)i.call(r,a)&&r[a]&&e.push(a)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t,n){"use strict";function r(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 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 a(e){var t=function(t){function n(){o(this,n),u(Object.getPrototypeOf(n.prototype),"constructor",this).apply(this,arguments)}return i(n,t),s(n,[{key:"componentDidMount",value:function(){this._hideOrShowContainer(this.props)}},{key:"componentWillReceiveProps",value:function(e){this._hideOrShowContainer(e)}},{key:"_hideOrShowContainer",value:function(e){var t=f["default"].findDOMNode(this).parentNode;t.style.display=e.shouldAutoHideContainer===!0?"none":""}},{key:"render",value:function(){return this.props.shouldAutoHideContainer===!0?c["default"].createElement("div",null):c["default"].createElement(e,this.props)}}]),n}(c["default"].Component);return t.propTypes={shouldAutoHideContainer:c["default"].PropTypes.bool.isRequired},t.displayName=e.name+"-AutoHide",t}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},l=n(218),c=r(l),p=n(371),f=r(p);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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 a(e){var t=function(t){function n(){o(this,n),l(Object.getPrototypeOf(n.prototype),"constructor",this).apply(this,arguments)}return i(n,t),u(n,[{key:"getTemplate",value:function(e){var t=this.props.templateProps.templates;if(!t||!t[e])return null;var n=(0,d["default"])(this.props.cssClasses[e],"ais-"+e);return p["default"].createElement(m["default"],s({},this.props.templateProps,{cssClass:n,templateKey:e,transformData:null}))}},{key:"render",value:function(){var t={root:(0,d["default"])(this.props.cssClasses.root),body:(0,d["default"])(this.props.cssClasses.body)},n=this.getTemplate("header"),r=this.getTemplate("footer");return p["default"].createElement("div",{className:t.root},n,p["default"].createElement("div",{className:t.body},p["default"].createElement(e,this.props)),r)}}]),n}(p["default"].Component);return t.propTypes={cssClasses:p["default"].PropTypes.shape({root:p["default"].PropTypes.string,header:p["default"].PropTypes.string,body:p["default"].PropTypes.string,footer:p["default"].PropTypes.string}),templateProps:p["default"].PropTypes.object},t.defaultProps={cssClasses:{}},t.displayName=e.name+"-HeaderFooter",t}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},c=n(218),p=r(c),f=n(377),d=r(f),h=n(380),m=r(h);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.useCustomCompileOptions[e.templateKey],n=t?e.templatesConfig.compileOptions:{},r=a({templates:e.templates,templateKey:e.templateKey,compileOptions:n,helpers:e.templatesConfig.helpers,data:i(e.transformData,e.templateKey,e.data)});if(null===r)return null;var s=(0,y["default"])(e,(0,v["default"])(o.propTypes));return c["default"].createElement("div",u({},s,{className:e.cssClass,dangerouslySetInnerHTML:{__html:r}}))}function i(e,t,n){if(!e)return n;var r=(0,h["default"])(n),o=void 0,i=typeof e;if("function"===i)o=e(r);else{if("object"!==i)throw new Error("transformData must be a function or an object, was "+i+" (key : "+t+")");o=e[t]?e[t](r):n}var a=typeof o,s=typeof n;if(a!==s)throw new Error("`transformData` must return a `"+s+"`, got `"+a+"`.");return o}function a(e){var t=e.templates,n=e.templateKey,r=e.compileOptions,o=e.helpers,i=e.data,a=t[n],l=typeof a,c="string"===l,p="function"===l;if(c||p){if(p)return a(i);var f=s(o,r,i),d=u({},i,{helpers:f});return P["default"].compile(a,r).render(d)}throw new Error("Template must be 'string' or 'function', was '"+l+"' (key: "+n+")")}function s(e,t,n){return(0,_["default"])(e,function(e){return(0,f["default"])(function(r){var o=this,i=function(e){return P["default"].compile(e,t).render(o)};return e.call(n,r,i)})})}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(218),c=r(l),p=n(381),f=r(p),d=n(93),h=r(d),m=n(22),v=r(m),g=n(115),y=r(g),b=n(209),_=r(b),x=n(383),P=r(x);o.propTypes={cssClass:c["default"].PropTypes.string,data:c["default"].PropTypes.object,templateKey:c["default"].PropTypes.string,templates:c["default"].PropTypes.objectOf(c["default"].PropTypes.oneOfType([c["default"].PropTypes.string,c["default"].PropTypes.func])),templatesConfig:c["default"].PropTypes.shape({helpers:c["default"].PropTypes.objectOf(c["default"].PropTypes.func),compileOptions:c["default"].PropTypes.shape({asString:c["default"].PropTypes.bool,sectionTags:c["default"].PropTypes.arrayOf(c["default"].PropTypes.shape({o:c["default"].PropTypes.string,c:c["default"].PropTypes.string})),delimiters:c["default"].PropTypes.string,disableLambda:c["default"].PropTypes.bool})}),transformData:c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,c["default"].PropTypes.objectOf(c["default"].PropTypes.func)]),useCustomCompileOptions:c["default"].PropTypes.objectOf(c["default"].PropTypes.bool)},o.defaultProps={data:{},useCustomCompileOptions:{},templates:{},templatesConfig:{}},t["default"]=o,e.exports=t["default"]},function(e,t,n){var r=n(382),o=8,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){function r(e){function t(n,r,a){a&&i(n,r,a)&&(r=void 0);var s=o(n,e,void 0,void 0,void 0,void 0,void 0,r);return s.placeholder=t.placeholder,s}return t}var o=n(160),i=n(52);e.exports=r},function(e,t,n){var r=n(384);r.Template=n(385).Template,r.template=r.Template,e.exports=r},function(e,t,n){!function(e){function t(e){"}"===e.n.substr(e.n.length-1)&&(e.n=e.n.substring(0,e.n.length-1))}function n(e){return e.trim?e.trim():e.replace(/^\s*|\s*$/g,"")}function r(e,t,n){if(t.charAt(n)!=e.charAt(0))return!1;for(var r=1,o=e.length;o>r;r++)if(t.charAt(n+r)!=e.charAt(r))return!1;return!0}function o(t,n,r,s){var u=[],l=null,c=null,p=null;for(c=r[r.length-1];t.length>0;){if(p=t.shift(),c&&"<"==c.tag&&!(p.tag in x))throw new Error("Illegal content in < super tag.");if(e.tags[p.tag]<=e.tags.$||i(p,s))r.push(p),p.nodes=o(t,p.tag,r,s);else{if("/"==p.tag){if(0===r.length)throw new Error("Closing tag without opener: /"+p.n);if(l=r.pop(),p.n!=l.n&&!a(p.n,l.n,s))throw new Error("Nesting error: "+l.n+" vs. "+p.n);return l.end=p.i,u}"\n"==p.tag&&(p.last=0==t.length||"\n"==t[0].tag)}u.push(p)}if(r.length>0)throw new Error("missing closing tag: "+r.pop().n);return u}function i(e,t){for(var n=0,r=t.length;r>n;n++)if(t[n].o==e.n)return e.tag="#",!0}function a(e,t,n){for(var r=0,o=n.length;o>r;r++)if(n[r].c==e&&n[r].o==t)return!0}function s(e){var t=[];for(var n in e)t.push('"'+l(n)+'": function(c,p,t,i) {'+e[n]+"}");return"{ "+t.join(",")+" }"}function u(e){var t=[];for(var n in e.partials)t.push('"'+l(n)+'":{name:"'+l(e.partials[n].name)+'", '+u(e.partials[n])+"}");return"partials: {"+t.join(",")+"}, subs: "+s(e.subs)}function l(e){return e.replace(y,"\\\\").replace(m,'\\"').replace(v,"\\n").replace(g,"\\r").replace(b,"\\u2028").replace(_,"\\u2029")}function c(e){return~e.indexOf(".")?"d":"f"}function p(e,t){var n="<"+(t.prefix||""),r=n+e.n+P++;return t.partials[r]={name:e.n,partials:{}},t.code+='t.b(t.rp("'+l(r)+'",c,p,"'+(e.indent||"")+'"));',r}function f(e,t){t.code+="t.b(t.t(t."+c(e.n)+'("'+l(e.n)+'",c,p,0)));'}function d(e){return"t.b("+e+");"}var h=/\S/,m=/\"/g,v=/\n/g,g=/\r/g,y=/\\/g,b=/\u2028/,_=/\u2029/;e.tags={"#":1,"^":2,"<":3,$:4,"/":5,"!":6,">":7,"=":8,_v:9,"{":10,"&":11,_t:12},e.scan=function(o,i){function a(){y.length>0&&(b.push({tag:"_t",text:new String(y)}),y="")}function s(){for(var t=!0,n=P;n<b.length;n++)if(t=e.tags[b[n].tag]<e.tags._v||"_t"==b[n].tag&&null===b[n].text.match(h),!t)return!1;return t}function u(e,t){if(a(),e&&s())for(var n,r=P;r<b.length;r++)b[r].text&&((n=b[r+1])&&">"==n.tag&&(n.indent=b[r].text.toString()),b.splice(r,1));else t||b.push({tag:"\n"});_=!1,P=b.length}function l(e,t){var r="="+w,o=e.indexOf(r,t),i=n(e.substring(e.indexOf("=",t)+1,o)).split(" ");return C=i[0],w=i[i.length-1],o+r.length-1}var c=o.length,p=0,f=1,d=2,m=p,v=null,g=null,y="",b=[],_=!1,x=0,P=0,C="{{",w="}}";for(i&&(i=i.split(" "),C=i[0],w=i[1]),x=0;c>x;x++)m==p?r(C,o,x)?(--x,a(),m=f):"\n"==o.charAt(x)?u(_):y+=o.charAt(x):m==f?(x+=C.length-1,g=e.tags[o.charAt(x+1)],v=g?o.charAt(x+1):"_v","="==v?(x=l(o,x),m=p):(g&&x++,m=d),_=x):r(w,o,x)?(b.push({tag:v,n:n(y),otag:C,ctag:w,i:"/"==v?_-C.length:x+w.length}),y="",x+=w.length-1,m=p,"{"==v&&("}}"==w?x++:t(b[b.length-1]))):y+=o.charAt(x);return u(_,!0),b};var x={_t:!0,"\n":!0,$:!0,"/":!0};e.stringify=function(t,n,r){return"{code: function (c,p,i) { "+e.wrapMain(t.code)+" },"+u(t)+"}"};var P=0;e.generate=function(t,n,r){P=0;var o={code:"",subs:{},partials:{}};return e.walk(t,o),r.asString?this.stringify(o,n,r):this.makeTemplate(o,n,r)},e.wrapMain=function(e){return'var t=this;t.b(i=i||"");'+e+"return t.fl();"},e.template=e.Template,e.makeTemplate=function(e,t,n){var r=this.makePartials(e);return r.code=new Function("c","p","i",this.wrapMain(e.code)),new this.template(r,t,this,n)},e.makePartials=function(e){var t,n={subs:{},partials:e.partials,name:e.name};for(t in n.partials)n.partials[t]=this.makePartials(n.partials[t]);for(t in e.subs)n.subs[t]=new Function("c","p","t","i",e.subs[t]);return n},e.codegen={"#":function(t,n){n.code+="if(t.s(t."+c(t.n)+'("'+l(t.n)+'",c,p,1),c,p,0,'+t.i+","+t.end+',"'+t.otag+" "+t.ctag+'")){t.rs(c,p,function(c,p,t){',e.walk(t.nodes,n),n.code+="});c.pop();}"},"^":function(t,n){n.code+="if(!t.s(t."+c(t.n)+'("'+l(t.n)+'",c,p,1),c,p,1,0,0,"")){',e.walk(t.nodes,n),n.code+="};"},">":p,"<":function(t,n){var r={partials:{},code:"",subs:{},inPartial:!0};e.walk(t.nodes,r);var o=n.partials[p(t,n)];o.subs=r.subs,o.partials=r.partials},$:function(t,n){var r={subs:{},code:"",partials:n.partials,prefix:t.n};e.walk(t.nodes,r),n.subs[t.n]=r.code,n.inPartial||(n.code+='t.sub("'+l(t.n)+'",c,p,i);')},"\n":function(e,t){t.code+=d('"\\n"'+(e.last?"":" + i"))},_v:function(e,t){t.code+="t.b(t.v(t."+c(e.n)+'("'+l(e.n)+'",c,p,0)));'},_t:function(e,t){t.code+=d('"'+l(e.text)+'"')},"{":f,"&":f},e.walk=function(t,n){for(var r,o=0,i=t.length;i>o;o++)r=e.codegen[t[o].tag],r&&r(t[o],n);return n},e.parse=function(e,t,n){return n=n||{},o(e,"",[],n.sectionTags||[])},e.cache={},e.cacheKey=function(e,t){return[e,!!t.asString,!!t.disableLambda,t.delimiters,!!t.modelGet].join("||")},e.compile=function(t,n){n=n||{};var r=e.cacheKey(t,n),o=this.cache[r];if(o){var i=o.partials;for(var a in i)delete i[a].instance;return o}return o=this.generate(this.parse(this.scan(t,n.delimiters),t,n),t,n),this.cache[r]=o}}(t)},function(e,t,n){!function(e){function t(e,t,n){var r;return t&&"object"==typeof t&&(void 0!==t[e]?r=t[e]:n&&t.get&&"function"==typeof t.get&&(r=t.get(e))),r}function n(e,t,n,r,o,i){function a(){}function s(){}a.prototype=e,s.prototype=e.subs;var u,l=new a;l.subs=new s,l.subsText={},l.buf="",r=r||{},l.stackSubs=r,l.subsText=i;for(u in t)r[u]||(r[u]=t[u]);for(u in r)l.subs[u]=r[u];o=o||{},l.stackPartials=o;for(u in n)o[u]||(o[u]=n[u]);for(u in o)l.partials[u]=o[u];return l}function r(e){return String(null===e||void 0===e?"":e)}function o(e){return e=r(e),c.test(e)?e.replace(i,"&amp;").replace(a,"&lt;").replace(s,"&gt;").replace(u,"&#39;").replace(l,"&quot;"):e}e.Template=function(e,t,n,r){e=e||{},this.r=e.code||this.r,this.c=n,this.options=r||{},this.text=t||"",this.partials=e.partials||{},this.subs=e.subs||{},this.buf=""},e.Template.prototype={r:function(e,t,n){return""},v:o,t:r,render:function(e,t,n){return this.ri([e],t||{},n)},ri:function(e,t,n){return this.r(e,t,n)},ep:function(e,t){var r=this.partials[e],o=t[r.name];if(r.instance&&r.base==o)return r.instance;if("string"==typeof o){if(!this.c)throw new Error("No compiler available.");o=this.c.compile(o,this.options)}if(!o)return null;if(this.partials[e].base=o,r.subs){t.stackText||(t.stackText={});for(key in r.subs)t.stackText[key]||(t.stackText[key]=void 0!==this.activeSub&&t.stackText[this.activeSub]?t.stackText[this.activeSub]:this.text);o=n(o,r.subs,r.partials,this.stackSubs,this.stackPartials,t.stackText)}return this.partials[e].instance=o,o},rp:function(e,t,n,r){var o=this.ep(e,n);return o?o.ri(t,n,r):""},rs:function(e,t,n){var r=e[e.length-1];if(!p(r))return void n(e,t,this);for(var o=0;o<r.length;o++)e.push(r[o]),n(e,t,this),e.pop()},s:function(e,t,n,r,o,i,a){var s;return p(e)&&0===e.length?!1:("function"==typeof e&&(e=this.ms(e,t,n,r,o,i,a)),s=!!e,!r&&s&&t&&t.push("object"==typeof e?e:t[t.length-1]),s)},d:function(e,n,r,o){var i,a=e.split("."),s=this.f(a[0],n,r,o),u=this.options.modelGet,l=null;if("."===e&&p(n[n.length-2]))s=n[n.length-1];else for(var c=1;c<a.length;c++)i=t(a[c],s,u),void 0!==i?(l=s,s=i):s="";return o&&!s?!1:(o||"function"!=typeof s||(n.push(l),s=this.mv(s,n,r),n.pop()),s)},f:function(e,n,r,o){for(var i=!1,a=null,s=!1,u=this.options.modelGet,l=n.length-1;l>=0;l--)if(a=n[l],i=t(e,a,u),void 0!==i){s=!0;break}return s?(o||"function"!=typeof i||(i=this.mv(i,n,r)),i):o?!1:""},ls:function(e,t,n,o,i){var a=this.options.delimiters;return this.options.delimiters=i,this.b(this.ct(r(e.call(t,o)),t,n)),this.options.delimiters=a,!1},ct:function(e,t,n){if(this.options.disableLambda)throw new Error("Lambda features disabled.");return this.c.compile(e,this.options).render(t,n)},b:function(e){this.buf+=e},fl:function(){var e=this.buf;return this.buf="",e},ms:function(e,t,n,r,o,i,a){var s,u=t[t.length-1],l=e.call(u);return"function"==typeof l?r?!0:(s=this.activeSub&&this.subsText&&this.subsText[this.activeSub]?this.subsText[this.activeSub]:this.text,this.ls(l,u,n,s.substring(o,i),a)):l},mv:function(e,t,n){var o=t[t.length-1],i=e.call(o);return"function"==typeof i?this.ct(r(i.call(o)),o,n):i},sub:function(e,t,n,r){var o=this.subs[e];o&&(this.activeSub=e,o(t,n,this,r),this.activeSub=!1)}};var i=/&/g,a=/</g,s=/>/g,u=/\'/g,l=/\"/g,c=/[&<>\"\']/,p=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}}(t)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",link:"Clear all",footer:""},e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},l=n(218),c=r(l),p=n(380),f=r(p),d=n(373),h=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"handleClick",value:function(e){(0,d.isSpecialClick)(e)||(e.preventDefault(),this.props.clearAll())}},{key:"render",value:function(){var e=this.props.cssClasses.link,t={hasRefinements:this.props.hasRefinements};return c["default"].createElement("a",{className:e,href:this.props.url,onClick:this.handleClick.bind(this)},c["default"].createElement(f["default"],a({data:t,templateKey:"link"},this.props.templateProps)))}}]),t}(c["default"].Component);h.propTypes={clearAll:c["default"].PropTypes.func.isRequired,cssClasses:c["default"].PropTypes.shape({link:c["default"].PropTypes.string}),hasRefinements:c["default"].PropTypes.bool.isRequired,templateProps:c["default"].PropTypes.object.isRequired,url:c["default"].PropTypes.string.isRequired},t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.container,r=e.attributes,o=void 0===r?[]:r,i=e.onlyListedAttributes,a=void 0===i?!1:i,c=e.clearAll,f=void 0===c?"before":c,m=e.templates,g=void 0===m?q["default"]:m,b=e.transformData,x=e.autoHideContainer,C=void 0===x?!0:x,R=e.cssClasses,T=void 0===R?{}:R,S=(0,w["default"])(o)&&(0,D["default"])(o,function(e,t){return e&&(0,E["default"])(t)&&(0,P["default"])(t.name)&&((0,y["default"])(t.label)||(0,P["default"])(t.label))&&((0,y["default"])(t.template)||(0,P["default"])(t.template)||(0,O["default"])(t.template))&&((0,y["default"])(t.transformData)||(0,O["default"])(t.transformData))},!0),j=["header","item","clearAll","footer"],N=(0,E["default"])(g)&&(0,D["default"])(g,function(e,t,n){return e&&-1!==j.indexOf(n)&&((0,P["default"])(t)||(0,O["default"])(t))},!0),M=["root","header","body","clearAll","list","item","link","count","footer"],I=(0,E["default"])(T)&&(0,D["default"])(T,function(e,t,n){return e&&-1!==M.indexOf(n)&&(0,P["default"])(t)||(0,w["default"])(t)},!0),A=!(((0,P["default"])(t)||(0,h.isDomElement)(t))&&(0,w["default"])(o)&&S&&(0,_["default"])(a)&&-1!==[!1,"before","after"].indexOf(f)&&(0,E["default"])(g)&&N&&((0,y["default"])(b)||(0,O["default"])(b))&&(0,_["default"])(C)&&I);if(A)throw new Error(W);var F=(0,h.getContainerNode)(t),U=(0,L["default"])(n(391));C===!0&&(U=(0,H["default"])(U));var B=(0,k["default"])(o,function(e){return e.name}),K=a?B:[],Q=(0,D["default"])(o,function(e,t){return e[t.name]=t,e},{});return{render:function(e){var t=e.results,n=e.helper,r=e.state,o=e.templatesConfig,i=e.createURL,c={root:(0,v["default"])(V(null),T.root),header:(0,v["default"])(V("header"),T.header),body:(0,v["default"])(V("body"),T.body),clearAll:(0,v["default"])(V("clear-all"),T.clearAll),list:(0,v["default"])(V("list"),T.list),item:(0,v["default"])(V("item"),T.item),link:(0,v["default"])(V("link"),T.link),count:(0,v["default"])(V("count"),T.count),footer:(0,v["default"])(V("footer"),T.footer)},m=(0,h.prepareTemplateProps)({defaultTemplates:q["default"], templatesConfig:o,templates:g}),y=i((0,h.clearRefinementsFromState)(r,K)),b=h.clearRefinementsAndSearch.bind(null,n,K),_=s(t,r,B,a),x=_.map(function(e){return i(u(r,e))}),P=_.map(function(e){return l.bind(null,n,e)}),C=0===_.length;d["default"].render(p["default"].createElement(U,{attributes:Q,clearAllClick:b,clearAllPosition:f,clearAllURL:y,clearRefinementClicks:P,clearRefinementURLs:x,cssClasses:c,refinements:_,shouldAutoHideContainer:C,templateProps:m}),F)}}}function i(e,t,n){var r=e.indexOf(n);return-1!==r?r:e.length+t.indexOf(n)}function a(e,t,n,r){var o=i(e,t,n.attributeName),a=i(e,t,r.attributeName);return o===a?n.name===r.name?0:n.name<r.name?-1:1:a>o?-1:1}function s(e,t,n,r){var o=(0,h.getRefinements)(e,t),i=(0,D["default"])(o,function(e,t){return-1===n.indexOf(t.attributeName)&&e.indexOf(-1===t.attributeName)&&e.push(t.attributeName),e},[]);return o=o.sort(a.bind(null,n,i)),r&&!(0,j["default"])(n)&&(o=(0,A["default"])(o,function(e){return-1!==n.indexOf(e.attributeName)})),o}function u(e,t){switch(t.type){case"facet":return e.removeFacetRefinement(t.attributeName,t.name);case"disjunctive":return e.removeDisjunctiveFacetRefinement(t.attributeName,t.name);case"hierarchical":return e.clearRefinements(t.attributeName);case"exclude":return e.removeExcludeRefinement(t.attributeName,t.name);case"numeric":return e.removeNumericRefinement(t.attributeName,t.operator,t.name);case"tag":return e.removeTagRefinement(t.name);default:throw new Error("clearRefinement: type "+t.type+"isn't handled")}}function l(e,t){e.setState(u(e.state,t)).search()}Object.defineProperty(t,"__esModule",{value:!0});var c=n(218),p=r(c),f=n(371),d=r(f),h=n(373),m=n(377),v=r(m),g=n(126),y=r(g),b=n(389),_=r(b),x=n(125),P=r(x),C=n(33),w=r(C),R=n(81),E=r(R),T=n(25),O=r(T),S=n(124),j=r(S),N=n(53),k=r(N),M=n(111),D=r(M),I=n(108),A=r(I),F=n(379),L=r(F),U=n(378),H=r(U),B=n(390),q=r(B),V=(0,h.bemHelper)("ais-current-refined-values"),W="Usage:\ncurrentRefinedValues({\n container,\n [ attributes: [{name[, label, template, transformData]}] ],\n [ onlyListedAttributes = false ],\n [ clearAll = 'before' ] // One of ['before', 'after', false]\n [ templates.{header = '', item, clearAll, footer = ''} ],\n [ transformData ],\n [ autoHideContainer = true ],\n [ cssClasses.{root, header, body, clearAll, list, item, link, count, footer} = {} ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t,n){function r(e){return e===!0||e===!1||o(e)&&s.call(e)==i}var o=n(26),i="[object Boolean]",a=Object.prototype,s=a.toString;e.exports=r},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:'{{#label}}{{label}}{{^operator}}:{{/operator}} {{/label}}{{#operator}}{{{displayOperator}}} {{/operator}}{{#exclude}}-{{/exclude}}{{name}} <span class="{{cssClasses.count}}">{{count}}</span>',clearAll:"Clear all",footer:""},e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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 a(e){var t={};return void 0!==e.template&&(t.templates={item:e.template}),void 0!==e.transformData&&(t.transformData=e.transformData),t}function s(e,t,n){var r=(0,_["default"])(t);return r.cssClasses=n,void 0!==e.label&&(r.label=e.label),void 0!==r.operator&&(r.displayOperator=r.operator,">="===r.operator&&(r.displayOperator="&ge;"),"<="===r.operator&&(r.displayOperator="&le;")),r}function u(e){return function(t){(0,v.isSpecialClick)(t)||(t.preventDefault(),e())}}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),p=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},f=n(218),d=r(f),h=n(380),m=r(h),v=n(373),g=n(53),y=r(g),b=n(93),_=r(b),x=function(e){function t(){o(this,t),p(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),c(t,[{key:"_clearAllElement",value:function(e,t){return t===e?d["default"].createElement("a",{className:this.props.cssClasses.clearAll,href:this.props.clearAllURL,onClick:u(this.props.clearAllClick)},d["default"].createElement(m["default"],l({templateKey:"clearAll"},this.props.templateProps))):void 0}},{key:"_refinementElement",value:function(e,t){var n=this.props.attributes[e.attributeName]||{},r=s(n,e,this.props.cssClasses),o=a(n),i=e.attributeName+(e.operator?e.operator:":")+(e.exclude?e.exclude:"")+e.name;return d["default"].createElement("div",{className:this.props.cssClasses.item,key:i},d["default"].createElement("a",{className:this.props.cssClasses.link,href:this.props.clearRefinementURLs[t],onClick:u(this.props.clearRefinementClicks[t])},d["default"].createElement(m["default"],l({data:r,templateKey:"item"},this.props.templateProps,o))))}},{key:"render",value:function(){return d["default"].createElement("div",null,this._clearAllElement("before",this.props.clearAllPosition),d["default"].createElement("div",{className:this.props.cssClasses.list},(0,y["default"])(this.props.refinements,this._refinementElement,this)),this._clearAllElement("after",this.props.clearAllPosition))}}]),t}(d["default"].Component);x.propTypes={attributes:d["default"].PropTypes.object,clearAllClick:d["default"].PropTypes.func,clearAllPosition:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.bool]),clearAllURL:d["default"].PropTypes.string,clearRefinementClicks:d["default"].PropTypes.arrayOf(d["default"].PropTypes.func),clearRefinementURLs:d["default"].PropTypes.arrayOf(d["default"].PropTypes.string),cssClasses:d["default"].PropTypes.shape({clearAll:d["default"].PropTypes.string,list:d["default"].PropTypes.string,item:d["default"].PropTypes.string,link:d["default"].PropTypes.string,count:d["default"].PropTypes.string}).isRequired,refinements:d["default"].PropTypes.array,templateProps:d["default"].PropTypes.object.isRequired},t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.attributes,o=e.separator,s=void 0===o?" > ":o,u=e.rootPath,c=void 0===u?null:u,f=e.showParentLevel,h=void 0===f?!0:f,v=e.limit,y=void 0===v?1e3:v,_=e.sortBy,w=void 0===_?["name:asc"]:_,R=e.cssClasses,E=void 0===R?{}:R,T=e.autoHideContainer,O=void 0===T?!0:T,S=e.templates,j=void 0===S?x["default"]:S,N=e.transformData;if(!t||!r||!r.length)throw new Error(C);var k=d["default"].getContainerNode(t),M=(0,b["default"])(n(394));O===!0&&(M=(0,g["default"])(M));var D=r[0];return{getConfiguration:function(){return{hierarchicalFacets:[{name:D,attributes:r,separator:s,rootPath:c,showParentLevel:h}]}},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,o=e.createURL,s=e.state,u=a(t,D,w,y),c=0===u.length,f=d["default"].prepareTemplateProps({transformData:N,defaultTemplates:x["default"],templatesConfig:r,templates:j}),h={root:(0,m["default"])(P(null),E.root),header:(0,m["default"])(P("header"),E.header),body:(0,m["default"])(P("body"),E.body),footer:(0,m["default"])(P("footer"),E.footer),list:(0,m["default"])(P("list"),E.list),depth:P("list","lvl"),item:(0,m["default"])(P("item"),E.item),active:(0,m["default"])(P("item","active"),E.active),link:(0,m["default"])(P("link"),E.link),count:(0,m["default"])(P("count"),E.count)};p["default"].render(l["default"].createElement(M,{attributeNameKey:"path",createURL:function(e){return o(s.toggleRefinement(D,e))},cssClasses:h,facetValues:u,shouldAutoHideContainer:c,templateProps:f,toggleRefinement:i.bind(null,n,D)}),k)}}}function i(e,t,n){e.toggleRefinement(t,n).search()}function a(e,t,n,r){var o=e.getFacetValues(t,{sortBy:n}).data||[];return s(o,r)}function s(e,t){return e.slice(0,t).map(function(e){return Array.isArray(e.data)&&(e.data=s(e.data,t)),e})}Object.defineProperty(t,"__esModule",{value:!0});var u=n(218),l=r(u),c=n(371),p=r(c),f=n(373),d=r(f),h=n(377),m=r(h),v=n(378),g=r(v),y=n(379),b=r(y),_=n(393),x=r(_),P=d["default"].bemHelper("ais-hierarchical-menu"),C="Usage:\nhierarchicalMenu({\n container,\n attributes,\n [ separator=' > ' ],\n [ rootPath ],\n [ showParentLevel=true ],\n [ limit=1000 ],\n [ sortBy=['name:asc'] ],\n [ cssClasses.{root , header, body, footer, list, depth, item, active, link}={} ],\n [ templates.{header, item, footer} ],\n [ transformData ],\n [ autoHideContainer=true ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:'<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span></a>',footer:""},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},c=n(218),p=r(c),f=n(377),d=r(f),h=n(373),m=n(380),v=r(m),g=function(e){function t(e){i(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={isShowMoreOpen:!1}}return a(t,e),u(t,[{key:"refine",value:function(e){this.props.toggleRefinement(e)}},{key:"_generateFacetItem",value:function(e){var n=void 0,r=e.data&&e.data.length>0;r&&(n=p["default"].createElement(t,s({},this.props,{depth:this.props.depth+1,facetValues:e.data})));var i=e;this.props.createURL&&(i.url=this.props.createURL(e[this.props.attributeNameKey]));var a=s({},e,{cssClasses:this.props.cssClasses}),u=(0,d["default"])(this.props.cssClasses.item,o({},this.props.cssClasses.active,e.isRefined)),l=e[this.props.attributeNameKey];return void 0!==e.isRefined&&(l+="/"+e.isRefined),void 0!==e.count&&(l+="/"+e.count),p["default"].createElement("div",{className:u,key:l,onClick:this.handleItemClick.bind(this,e[this.props.attributeNameKey])},p["default"].createElement(v["default"],s({data:a,templateKey:"item"},this.props.templateProps)),n)}},{key:"handleItemClick",value:function(e,t){if(!(0,h.isSpecialClick)(t)){if("INPUT"===t.target.tagName)return void this.refine(e);for(var n=t.target;n!==t.currentTarget;){if("LABEL"===n.tagName&&(n.querySelector('input[type="checkbox"]')||n.querySelector('input[type="radio"]')))return;"A"===n.tagName&&n.href&&t.preventDefault(),n=n.parentNode}t.stopPropagation(),this.refine(e)}}},{key:"handleClickShowMore",value:function(){var e=!this.state.isShowMoreOpen;this.setState({isShowMoreOpen:e})}},{key:"render",value:function(){var e=this,t=[this.props.cssClasses.list];this.props.cssClasses.depth&&t.push(""+this.props.cssClasses.depth+this.props.depth);var n=this.state.isShowMoreOpen?this.props.limitMax:this.props.limitMin,r=this.props.showMore?p["default"].createElement(v["default"],s({onClick:function(){return e.handleClickShowMore()},templateKey:"show-more-"+(this.state.isShowMoreOpen?"active":"inactive")},this.props.templateProps)):void 0;return p["default"].createElement("div",{className:(0,d["default"])(t)},this.props.facetValues.map(this._generateFacetItem,this).slice(0,n),r)}}]),t}(p["default"].Component);g.propTypes={Template:p["default"].PropTypes.func,attributeNameKey:p["default"].PropTypes.string,createURL:p["default"].PropTypes.func.isRequired,cssClasses:p["default"].PropTypes.shape({active:p["default"].PropTypes.string,depth:p["default"].PropTypes.string,item:p["default"].PropTypes.string,list:p["default"].PropTypes.string}),depth:p["default"].PropTypes.number,facetValues:p["default"].PropTypes.array,limitMax:p["default"].PropTypes.number,limitMin:p["default"].PropTypes.number,showMore:p["default"].PropTypes.bool,templateProps:p["default"].PropTypes.object.isRequired,toggleRefinement:p["default"].PropTypes.func.isRequired},g.defaultProps={cssClasses:{},depth:0,attributeNameKey:"name"},t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,n=e.cssClasses,r=void 0===n?{}:n,o=e.templates,i=void 0===o?v["default"]:o,s=e.transformData,l=e.hitsPerPage,p=void 0===l?20:l;if(!t)throw new Error("Must provide a container."+y);if(i.item&&i.allItems)throw new Error("Must contain only allItems OR item template."+y);var d=c["default"].getContainerNode(t),m={root:(0,f["default"])(g(null),r.root),item:(0,f["default"])(g("item"),r.item),empty:(0,f["default"])(g(null,"empty"),r.empty)};return{getConfiguration:function(){return{hitsPerPage:p}},render:function(e){var t=e.results,n=e.templatesConfig,r=c["default"].prepareTemplateProps({transformData:s,defaultTemplates:v["default"],templatesConfig:n,templates:i});u["default"].render(a["default"].createElement(h["default"],{cssClasses:m,hits:t.hits,results:t,templateProps:r}),d)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=r(l),p=n(377),f=r(p),d=n(396),h=r(d),m=n(397),v=r(m),g=c["default"].bemHelper("ais-hits"),y="\nUsage:\nhits({\n container,\n [ cssClasses.{root,empty,item}={} ],\n [ templates.{empty,item} | templates.{empty, allItems} ],\n [ transformData.{empty=identity,item=identity} | transformData.{empty, allItems} ],\n [ hitsPerPage=20 ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},l=n(218),c=r(l),p=n(53),f=r(p),d=n(380),h=r(d),m=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"renderWithResults",value:function(){var e=this,t=(0,f["default"])(this.props.results.hits,function(t){return c["default"].createElement(h["default"],a({cssClass:e.props.cssClasses.item,data:t,key:t.objectID,templateKey:"item"},e.props.templateProps))});return c["default"].createElement("div",{className:this.props.cssClasses.root},t)}},{key:"renderAllResults",value:function(){return c["default"].createElement(h["default"],a({cssClass:this.props.cssClasses.allItems,data:this.props.results,templateKey:"allItems"},this.props.templateProps))}},{key:"renderNoResults",value:function(){var e=this.props.cssClasses.root+" "+this.props.cssClasses.empty;return c["default"].createElement(h["default"],a({cssClass:e,data:this.props.results,templateKey:"empty"},this.props.templateProps))}},{key:"render",value:function(){if(this.props.results.hits.length>0){var e=this.props.templateProps&&this.props.templateProps.templates&&this.props.templateProps.templates.allItems;return e?this.renderAllResults():this.renderWithResults()}return this.renderNoResults()}}]),t}(c["default"].Component);m.propTypes={cssClasses:c["default"].PropTypes.shape({root:c["default"].PropTypes.string,item:c["default"].PropTypes.string,allItems:c["default"].PropTypes.string,empty:c["default"].PropTypes.string}),results:c["default"].PropTypes.object,templateProps:c["default"].PropTypes.object.isRequired},m.defaultProps={results:{hits:[]}},t["default"]=m,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={empty:"No results",item:function(e){return JSON.stringify(e,null,2)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.options,o=e.cssClasses,i=void 0===o?{}:o,s=e.autoHideContainer,l=void 0===s?!1:s;if(!t||!r)throw new Error(y);var p=c["default"].getContainerNode(t),d=n(402);return l===!0&&(d=(0,v["default"])(d)),{init:function(e){var t=e.state,n=(0,f["default"])(r,function(e){return+t.hitsPerPage===+e.value});n||(void 0===t.hitsPerPage?window.console&&window.console.log("[Warning][hitsPerPageSelector] hitsPerPage not defined. You should probably used a `hits` widget or set the value `hitsPerPage` using the searchParameters attribute of the instantsearch constructor."):window.console&&window.console.log("[Warning][hitsPerPageSelector] No option in `options` with `value: hitsPerPage` (hitsPerPage: "+t.hitsPerPage+")"),r=[{value:void 0,label:""}].concat(r))},setHitsPerPage:function(e,t){e.setQueryParameter("hitsPerPage",+t),e.search()},render:function(e){var t=e.helper,n=e.state,o=e.results,s=n.hitsPerPage,l=0===o.nbHits,c=this.setHitsPerPage.bind(this,t),f={root:(0,h["default"])(g(null),i.root),item:(0,h["default"])(g("item"),i.item)};u["default"].render(a["default"].createElement(d,{cssClasses:f,currentValue:s,options:r,setValue:c,shouldAutoHideContainer:l}),p)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=r(l),p=n(399),f=r(p),d=n(377),h=r(d),m=n(378),v=r(m),g=c["default"].bemHelper("ais-hits-per-page-selector"),y="Usage:\nhitsPerPageSelector({\n container,\n options,\n [ cssClasses.{root,item}={} ],\n [ autoHideContainer=false ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t,n){e.exports=n(400)},function(e,t,n){function r(e,t,n){var r=s(e)?o:a;return n&&u(e,t,n)&&(t=void 0),("function"!=typeof t||void 0!==n)&&(t=i(t,n,3)),r(e,t)}var o=n(61),i=n(55),a=n(401),s=n(33),u=n(52);e.exports=r},function(e,t,n){function r(e,t){var n;return o(e,function(e,r,o){return n=t(e,r,o),!n}),!!n}var o=n(16);e.exports=r},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},u=n(218),l=r(u),c=function(e){function t(){o(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),a(t,[{key:"handleChange",value:function(e){this.props.setValue(e.target.value)}},{key:"render",value:function(){var e=this,t=this.props,n=t.currentValue,r=t.options,o=this.handleChange.bind(this);return l["default"].createElement("select",{className:this.props.cssClasses.root,defaultValue:n,onChange:o},r.map(function(t){return l["default"].createElement("option",{className:e.props.cssClasses.item,key:t.value,value:t.value},t.label)}))}}]),t}(l["default"].Component);c.propTypes={cssClasses:l["default"].PropTypes.shape({root:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.arrayOf(l["default"].PropTypes.string)]),item:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.arrayOf(l["default"].PropTypes.string)])}),currentValue:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.number]).isRequired,options:l["default"].PropTypes.arrayOf(l["default"].PropTypes.shape({value:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.number]).isRequired,label:l["default"].PropTypes.string.isRequired})).isRequired,setValue:l["default"].PropTypes.func.isRequired},t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.attributeName,o=e.sortBy,s=void 0===o?["count:desc"]:o,l=e.limit,p=void 0===l?100:l,d=e.cssClasses,m=void 0===d?{}:d,g=e.templates,b=void 0===g?_["default"]:g,C=e.transformData,w=e.autoHideContainer,R=void 0===w?!0:w;if(!t||!r)throw new Error(P);var E=f["default"].getContainerNode(t),T=(0,y["default"])(n(394));R===!0&&(T=(0,v["default"])(T));var O=r;return{getConfiguration:function(){return{hierarchicalFacets:[{name:O,attributes:[r]}]}},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,o=e.state,l=e.createURL,d=a(t,O,s,p),v=0===d.length,g=f["default"].prepareTemplateProps({transformData:C,defaultTemplates:_["default"],templatesConfig:r,templates:b}),y={root:(0,h["default"])(x(null),m.root),header:(0,h["default"])(x("header"),m.header),body:(0,h["default"])(x("body"),m.body),footer:(0,h["default"])(x("footer"),m.footer),list:(0,h["default"])(x("list"),m.list),item:(0,h["default"])(x("item"),m.item),active:(0,h["default"])(x("item","active"),m.active),link:(0,h["default"])(x("link"),m.link),count:(0,h["default"])(x("count"),m.count)};c["default"].render(u["default"].createElement(T,{createURL:function(e){return l(o.toggleRefinement(O,e))},cssClasses:y,facetValues:d,shouldAutoHideContainer:v,templateProps:g,toggleRefinement:i.bind(null,n,O)}),E)}}}function i(e,t,n){e.toggleRefinement(t,n).search()}function a(e,t,n,r){var o=e.getFacetValues(t,{sortBy:n});return o.data&&o.data.slice(0,r)||[]}Object.defineProperty(t,"__esModule",{value:!0});var s=n(218),u=r(s),l=n(371),c=r(l),p=n(373),f=r(p),d=n(377),h=r(d),m=n(378),v=r(m),g=n(379),y=r(g),b=n(404),_=r(b),x=f["default"].bemHelper("ais-menu"),P="Usage:\nmenu({\n container,\n attributeName,\n [sortBy],\n [limit],\n [cssClasses.{root,list,item}],\n [templates.{header,item,footer}],\n [transformData],\n [autoHideContainer]\n})";t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:'<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span></a>',footer:""},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=e.container,r=e.attributeName,i=e.operator,l=void 0===i?"or":i,p=e.sortBy,d=void 0===p?["count:desc"]:p,h=e.limit,m=void 0===h?10:h,g=e.cssClasses,b=void 0===g?{}:g,x=e.templates,C=void 0===x?w["default"]:x,R=e.transformData,E=e.autoHideContainer,S=void 0===E?!0:E,j=e.showMore,N=a(j);if(N&&N.limit<m)throw new Error("showMore.limit configuration should be > than the limit in the main configuration");var k=N&&N.limit||m,M=n(394);if(!t||!r)throw new Error(O);M=(0,P["default"])(M),S===!0&&(M=(0,_["default"])(M));var D=v["default"].getContainerNode(t);if(l&&(l=l.toLowerCase(),"and"!==l&&"or"!==l))throw new Error(O);var I=N&&s("show-more-",N.templates),A=I?u({},C,I):C;return{getConfiguration:function(e){var t=o({},"and"===l?"facets":"disjunctiveFacets",[r]),n=e.maxValuesPerFacet||0;return t.maxValuesPerFacet=Math.max(n,k),t},toggleRefinement:function(e,t){e.toggleRefinement(r,t).search()},render:function(e){var t=e.results,n=e.helper,o=e.templatesConfig,i=e.state,a=e.createURL,s=v["default"].prepareTemplateProps({transformData:R,defaultTemplates:w["default"],templatesConfig:o,templates:A}),u=t.getFacetValues(r,{sortBy:d}),l=0===u.length,p={root:(0,y["default"])(T(null),b.root),header:(0,y["default"])(T("header"),b.header),body:(0,y["default"])(T("body"),b.body),footer:(0,y["default"])(T("footer"),b.footer),list:(0,y["default"])(T("list"),b.list),item:(0,y["default"])(T("item"),b.item),active:(0,y["default"])(T("item","active"),b.active),label:(0,y["default"])(T("label"),b.label),checkbox:(0,y["default"])(T("checkbox"),b.checkbox),count:(0,y["default"])(T("count"),b.count)},h=this.toggleRefinement.bind(this,n);f["default"].render(c["default"].createElement(M,{createURL:function(e){return a(i.toggleRefinement(r,e))},cssClasses:p,facetValues:u,limitMax:k,limitMin:m,shouldAutoHideContainer:l,showMore:null!==N,templateProps:s,toggleRefinement:h}),D)}}}function a(e){if(e===!0)return S;if(e){var t=u({},e);return e.templates||(t.templates=S.templates),e.limit||(t.limit=S.limit),t}return null}function s(e,t){return t?(0,h["default"])(t,function(t,n){return e+n}):void 0}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(218),c=r(l),p=n(371),f=r(p),d=n(207),h=r(d),m=n(373),v=r(m),g=n(377),y=r(g),b=n(378),_=r(b),x=n(379),P=r(x),C=n(406),w=r(C),R=n(407),E=r(R),T=v["default"].bemHelper("ais-refinement-list"),O="Usage:\nrefinementList({\n container,\n attributeName,\n [ operator='or' ],\n [ sortBy=['count:desc'] ],\n [ limit=10 ],\n [ cssClasses.{root, header, body, footer, list, item, active, label, checkbox, count}],\n [ templates.{header,item,footer} ],\n [ transformData ],\n [ autoHideContainer=true ],\n [ showMore.{templates: {active, inactive}, limit} ]\n})",S={templates:E["default"],limit:100};t["default"]=i,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>\n</label>',footer:""},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={active:'<a class="ais-show-more ais-show-more__active">Show less</a>',inactive:'<a class="ais-show-more ais-show-more__inactive">Show more</a>'},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.container,r=e.attributeName,o=e.options,s=e.cssClasses,u=void 0===s?{}:s,c=e.templates,f=void 0===c?R["default"]:c,h=e.transformData,v=e.autoHideContainer,g=void 0===v?!0:v;if(!t||!r||!o)throw new Error(T);var y=d["default"].getContainerNode(t),b=(0,C["default"])(n(394));return g===!0&&(b=(0,x["default"])(b)),{getConfiguration:function(){return{}},render:function(e){var t=e.helper,n=e.results,s=e.templatesConfig,c=e.state,v=e.createURL,g=d["default"].prepareTemplateProps({transformData:h,defaultTemplates:R["default"],templatesConfig:s,templates:f}),_=o.map(function(e){return e.isRefined=i(t.state,r,e),e.attributeName=r,e}),x=0===n.nbHits,P={root:(0,m["default"])(E(null),u.root),header:(0,m["default"])(E("header"),u.header),body:(0,m["default"])(E("body"),u.body),footer:(0,m["default"])(E("footer"),u.footer),list:(0,m["default"])(E("list"),u.list),item:(0,m["default"])(E("item"),u.item),label:(0,m["default"])(E("label"),u.label),radio:(0,m["default"])(E("radio"),u.radio),active:(0,m["default"])(E("item","active"),u.active)};p["default"].render(l["default"].createElement(b,{createURL:function(e){return v(a(c,r,o,e))},cssClasses:P,facetValues:_,shouldAutoHideContainer:x,templateProps:g,toggleRefinement:this._toggleRefinement.bind(null,t)}),y)},_toggleRefinement:function(e,t){var n=a(e.state,r,o,t);e.setState(n),e.search()}}}function i(e,t,n){var r=e.getNumericRefinements(t);return void 0!==n.start&&void 0!==n.end&&n.start===n.end?s(r,"=",n.start):void 0!==n.start?s(r,">=",n.start):void 0!==n.end?s(r,"<=",n.end):void 0===n.start&&void 0===n.end?0===Object.keys(r).length:void 0}function a(e,t,n,r){var o=(0,g["default"])(n,{name:r}),a=e.getNumericRefinements(t);if(void 0===o.start&&void 0===o.end)return e.clearRefinements(t);if(i(e,t,o)||(e=e.clearRefinements(t)),void 0!==o.start&&void 0!==o.end){if(o.start>o.end)throw new Error("option.start should be > to option.end");if(o.start===o.end)return e=s(a,"=",o.start)?e.removeNumericRefinement(t,"=",o.start):e.addNumericRefinement(t,"=",o.start)}return void 0!==o.start&&(e=s(a,">=",o.start)?e.removeNumericRefinement(t,">=",o.start):e.addNumericRefinement(t,">=",o.start)),void 0!==o.end&&(e=s(a,"<=",o.end)?e.removeNumericRefinement(t,"<=",o.end):e.addNumericRefinement(t,"<=",o.end)),e}function s(e,t,n){var r=void 0!==e[t],o=(0,b["default"])(e[t],n);return r&&o}Object.defineProperty(t,"__esModule",{value:!0});var u=n(218),l=r(u),c=n(371),p=r(c),f=n(373),d=r(f),h=n(377),m=r(h),v=n(128),g=r(v),y=n(152),b=r(y),_=n(378),x=r(_),P=n(379),C=r(P),w=n(409),R=r(w),E=d["default"].bemHelper("ais-refinement-list"),T="Usage:\nnumericRefinementList({\n container,\n attributeName,\n options,\n [ sortBy ],\n [ limit ],\n [ cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count} ],\n [ templates.{header,item,footer} ],\n [ transformData ],\n [ autoHideContainer ]\n})"; t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="radio" class="{{cssClasses.checkbox}}" name="{{attributeName}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n</label>',footer:""},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.container,r=e.operator,o=void 0===r?"=":r,i=e.attributeName,s=e.options,l=e.cssClasses,p=void 0===l?{}:l,d=e.autoHideContainer,m=void 0===d?!1:d,y=c["default"].getContainerNode(t),b="Usage: numericSelector({container, attributeName, options[, cssClasses.{root,item}, autoHideContainer]})",_=n(402);if(m===!0&&(_=(0,v["default"])(_)),!t||!s||0===s.length||!i)throw new Error(b);return{init:function(e){var t=e.helper,n=this._getRefinedValue(t)||s[0].value;void 0!==n&&t.addNumericRefinement(i,o,n)},render:function(e){var t=e.helper,n=e.results,r=this._getRefinedValue(t),o=0===n.nbHits,i={root:(0,f["default"])(g(null),p.root),item:(0,f["default"])(g("item"),p.item)};u["default"].render(a["default"].createElement(_,{cssClasses:i,currentValue:r,options:s,setValue:this._refine.bind(this,t),shouldAutoHideContainer:o}),y)},_refine:function(e,t){e.clearRefinements(i),void 0!==t&&e.addNumericRefinement(i,o,t),e.search()},_getRefinedValue:function(e){var t=e.getRefinements(i),n=(0,h["default"])(t,{operator:o});return n&&void 0!==n.value&&void 0!==n.value[0]?n.value[0]:void 0}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=r(l),p=n(377),f=r(p),d=n(128),h=r(d),m=n(378),v=r(m),g=c["default"].bemHelper("ais-numeric-selector");t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.cssClasses,o=void 0===r?{}:r,i=e.labels,s=void 0===i?{}:i,l=e.maxPages,p=e.padding,d=void 0===p?3:p,m=e.showFirstLast,_=void 0===m?!0:m,x=e.autoHideContainer,P=void 0===x?!0:x,C=e.scrollTo,w=void 0===C?"body":C;if(!t)throw new Error(b);w===!0&&(w="body");var R=h["default"].getContainerNode(t),E=w!==!1?h["default"].getContainerNode(w):!1,T=n(412);return P===!0&&(T=(0,v["default"])(T)),s=(0,c["default"])(s,y),{setCurrentPage:function(e,t){e.setCurrentPage(t),E!==!1&&E.scrollIntoView(),e.search()},getMaxPage:function(e){return void 0!==l?Math.min(l,e.nbPages):e.nbPages},render:function(e){var t=e.results,n=e.helper,r=e.createURL,i=e.state,l=t.page,c=t.nbHits,p=0===c,h={root:(0,f["default"])(g(null),o.root),item:(0,f["default"])(g("item"),o.item),link:(0,f["default"])(g("link"),o.link),page:(0,f["default"])(g("item","page"),o.page),previous:(0,f["default"])(g("item","previous"),o.previous),next:(0,f["default"])(g("item","next"),o.next),first:(0,f["default"])(g("item","first"),o.first),last:(0,f["default"])(g("item","last"),o.last),active:(0,f["default"])(g("item","active"),o.active),disabled:(0,f["default"])(g("item","disabled"),o.disabled)};u["default"].render(a["default"].createElement(T,{createURL:function(e){return r(i.setPage(e))},cssClasses:h,currentPage:l,labels:s,nbHits:c,nbPages:this.getMaxPage(t),padding:d,setCurrentPage:this.setCurrentPage.bind(this,n),shouldAutoHideContainer:p,showFirstLast:_}),R)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(133),c=r(l),p=n(377),f=r(p),d=n(373),h=r(d),m=n(378),v=r(m),g=h["default"].bemHelper("ais-pagination"),y={previous:"‹",next:"›",first:"«",last:"»"},b="Usage:\npagination({\n container,\n [ cssClasses.{root,item,page,previous,next,first,last,active,disabled}={} ],\n [ labels.{previous,next,first,last} ],\n [ maxPages ],\n [ padding=3 ],\n [ showFirstLast=true ],\n [ autoHideContainer=true ],\n [ scrollTo='body' ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},u=n(218),l=r(u),c=n(14),p=r(c),f=n(413),d=r(f),h=n(373),m=n(415),v=r(m),g=n(417),y=r(g),b=n(377),_=r(b),x=function(e){function t(e){o(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,(0,d["default"])(e,t.defaultProps))}return i(t,e),a(t,[{key:"handleClick",value:function(e,t){(0,h.isSpecialClick)(t)||(t.preventDefault(),this.props.setCurrentPage(e))}},{key:"pageLink",value:function(e){var t=e.label,n=e.ariaLabel,r=e.pageNumber,o=e.additionalClassName,i=void 0===o?null:o,a=e.isDisabled,s=void 0===a?!1:a,u=e.isActive,c=void 0===u?!1:u,p=e.createURL,f=this.handleClick.bind(this,r),d={item:(0,_["default"])(this.props.cssClasses.item,i),link:(0,_["default"])(this.props.cssClasses.link)};s?d.item=(0,_["default"])(d.item,this.props.cssClasses.disabled):c&&(d.item=(0,_["default"])(d.item,this.props.cssClasses.active));var h=p&&!s?p(r):"#";return l["default"].createElement(y["default"],{ariaLabel:n,cssClasses:d,handleClick:f,key:t,label:t,url:h})}},{key:"previousPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Previous",additionalClassName:this.props.cssClasses.previous,isDisabled:e.isFirstPage(),label:this.props.labels.previous,pageNumber:e.currentPage-1,createURL:t})}},{key:"nextPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Next",additionalClassName:this.props.cssClasses.next,isDisabled:e.isLastPage(),label:this.props.labels.next,pageNumber:e.currentPage+1,createURL:t})}},{key:"firstPageLink",value:function(e,t){return this.pageLink({ariaLabel:"First",additionalClassName:this.props.cssClasses.first,isDisabled:e.isFirstPage(),label:this.props.labels.first,pageNumber:0,createURL:t})}},{key:"lastPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Last",additionalClassName:this.props.cssClasses.last,isDisabled:e.isLastPage(),label:this.props.labels.last,pageNumber:e.total-1,createURL:t})}},{key:"pages",value:function n(e,t){var r=this,n=[];return(0,p["default"])(e.pages(),function(o){var i=o===e.currentPage;n.push(r.pageLink({ariaLabel:o+1,additionalClassName:r.props.cssClasses.page,isActive:i,label:o+1,pageNumber:o,createURL:t}))}),n}},{key:"render",value:function(){var e=new v["default"]({currentPage:this.props.currentPage,total:this.props.nbPages,padding:this.props.padding}),t=this.props.createURL;return l["default"].createElement("ul",{className:this.props.cssClasses.root},this.props.showFirstLast?this.firstPageLink(e,t):null,this.previousPageLink(e,t),this.pages(e,t),this.nextPageLink(e,t),this.props.showFirstLast?this.lastPageLink(e,t):null)}}]),t}(l["default"].Component);x.propTypes={createURL:l["default"].PropTypes.func,cssClasses:l["default"].PropTypes.shape({root:l["default"].PropTypes.string,item:l["default"].PropTypes.string,link:l["default"].PropTypes.string,page:l["default"].PropTypes.string,previous:l["default"].PropTypes.string,next:l["default"].PropTypes.string,first:l["default"].PropTypes.string,last:l["default"].PropTypes.string,active:l["default"].PropTypes.string,disabled:l["default"].PropTypes.string}),currentPage:l["default"].PropTypes.number,labels:l["default"].PropTypes.shape({first:l["default"].PropTypes.string,last:l["default"].PropTypes.string,next:l["default"].PropTypes.string,previous:l["default"].PropTypes.string}),nbHits:l["default"].PropTypes.number,nbPages:l["default"].PropTypes.number,padding:l["default"].PropTypes.number,setCurrentPage:l["default"].PropTypes.func.isRequired,showFirstLast:l["default"].PropTypes.bool},x.defaultProps={nbHits:0,currentPage:0,nbPages:0},t["default"]=x,e.exports=t["default"]},function(e,t,n){var r=n(137),o=n(78),i=n(414),a=r(o,i);e.exports=a},function(e,t,n){function r(e,t){return void 0===e?t:o(e,t,r)}var o=n(78);e.exports=r},function(e,t,n){"use strict";function r(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")}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=n(416),s=r(a),u=function(){function e(t){o(this,e),this.currentPage=t.currentPage,this.total=t.total,this.padding=t.padding}return i(e,[{key:"pages",value:function(){var e=this.total,t=this.currentPage,n=this.padding,r=this.nbPagesDisplayed(n,e);if(r===e)return(0,s["default"])(0,e);var o=this.calculatePaddingLeft(t,n,e,r),i=r-o,a=t-o,u=t+i;return(0,s["default"])(a,u)}},{key:"nbPagesDisplayed",value:function(e,t){return Math.min(2*e+1,t)}},{key:"calculatePaddingLeft",value:function(e,t,n,r){return t>=e?e:e>=n-t?r-(n-e):t}},{key:"isLastPage",value:function(){return this.currentPage===this.total-1}},{key:"isFirstPage",value:function(){return 0===this.currentPage}}]),e}();t["default"]=u,e.exports=t["default"]},function(e,t,n){function r(e,t,n){n&&o(e,t,n)&&(t=n=void 0),e=+e||0,n=null==n?1:+n||0,null==t?(t=e,e=0):t=+t||0;for(var r=-1,s=a(i((t-e)/(n||1)),0),u=Array(s);++r<s;)u[r]=e,e+=n;return u}var o=n(52),i=Math.ceil,a=Math.max;e.exports=r},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},u=n(218),l=r(u),c=function(e){function t(){o(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),a(t,[{key:"render",value:function(){var e=this.props,t=e.cssClasses,n=e.label,r=e.ariaLabel,o=e.handleClick,i=e.url;return l["default"].createElement("li",{className:t.item},l["default"].createElement("a",{ariaLabel:r,className:t.link,dangerouslySetInnerHTML:{__html:n},href:i,onClick:o}))}}]),t}(l["default"].Component);c.propTypes={ariaLabel:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.number]).isRequired,cssClasses:l["default"].PropTypes.shape({item:l["default"].PropTypes.string,link:l["default"].PropTypes.string}),handleClick:l["default"].PropTypes.func.isRequired,label:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.number]).isRequired,url:l["default"].PropTypes.string},t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.attributeName,o=e.cssClasses,a=void 0===o?{}:o,u=e.templates,c=void 0===u?m["default"]:u,f=e.labels,h=void 0===f?{}:f,v=e.currency,y=void 0===v?"$":v,_=e.autoHideContainer,w=void 0===_?!0:_;if(!t||!r)throw new Error(C);var R=p["default"].getContainerNode(t),E=(0,b["default"])(n(421));return w===!0&&(E=(0,g["default"])(E)),{getConfiguration:function(){return{facets:[r]}},_generateRanges:function(e){var t=e.getFacetStats(r);return(0,d["default"])(t)},_extractRefinedRange:function(e){var t=e.getRefinements(r),n=void 0,o=void 0;return 0===t.length?[]:(t.forEach(function(e){-1!==e.operator.indexOf(">")?n=Math.floor(e.value[0]):-1!==e.operator.indexOf("<")&&(o=Math.ceil(e.value[0]))}),[{from:n,to:o,isRefined:!0}])},_refine:function(e,t,n){var o=this._extractRefinedRange(e);e.clearRefinements(r),(0===o.length||o[0].from!==t||o[0].to!==n)&&("undefined"!=typeof t&&e.addNumericRefinement(r,">=",Math.floor(t)),"undefined"!=typeof n&&e.addNumericRefinement(r,"<=",Math.ceil(n))),e.search()},render:function(e){var t=e.results,n=e.helper,o=e.templatesConfig,u=e.state,f=e.createURL,d=void 0,v=i({button:"Go",separator:"to"},h);void 0!==h.currency&&h.currency!==y&&(y=h.currency),t.hits.length>0?(d=this._extractRefinedRange(n),0===d.length&&(d=this._generateRanges(t))):d=[];var g=p["default"].prepareTemplateProps({defaultTemplates:m["default"],templatesConfig:o,templates:c}),b=0===d.length,_={root:(0,x["default"])(P(null),a.root),header:(0,x["default"])(P("header"),a.header),body:(0,x["default"])(P("body"),a.body),list:(0,x["default"])(P("list"),a.list),link:(0,x["default"])(P("link"),a.link),item:(0,x["default"])(P("item"),a.item),active:(0,x["default"])(P("item","active"),a.active),form:(0,x["default"])(P("form"),a.form),label:(0,x["default"])(P("label"),a.label),input:(0,x["default"])(P("input"),a.input),currency:(0,x["default"])(P("currency"),a.currency),button:(0,x["default"])(P("button"),a.button),separator:(0,x["default"])(P("separator"),a.separator),footer:(0,x["default"])(P("footer"),a.footer)};l["default"].render(s["default"].createElement(E,{createURL:function(e,t,n){var o=u.clearRefinements(r);return n||("undefined"!=typeof e&&(o=o.addNumericRefinement(r,">=",Math.floor(e))),"undefined"!=typeof t&&(o=o.addNumericRefinement(r,"<=",Math.ceil(t)))),f(o)},cssClasses:_,currency:y,facetValues:d,labels:v,refine:this._refine.bind(this,n),shouldAutoHideContainer:b,templateProps:g}),R)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(218),s=r(a),u=n(371),l=r(u),c=n(373),p=r(c),f=n(419),d=r(f),h=n(420),m=r(h),v=n(378),g=r(v),y=n(379),b=r(y),_=n(377),x=r(_),P=p["default"].bemHelper("ais-price-ranges"),C="Usage:\npriceRanges({\n container,\n attributeName,\n [ currency=$ ],\n [ cssClasses.{root,header,body,list,item,active,link,form,label,input,currency,separator,button,footer} ],\n [ templates.{header,item,footer} ],\n [ labels.{currency,separator,button} ],\n [ autoHideContainer=true ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=Math.round(e/t)*t;return 1>n&&(n=1),n}function r(e){var t=void 0;t=e.avg<100?1:e.avg<1e3?10:100;for(var r=n(Math.round(e.avg),t),o=Math.ceil(e.min),i=n(Math.floor(e.max),t);i>e.max;)i-=t;var a=void 0,s=void 0,u=[];if(o!==i){for(a=o,u.push({to:a});r>a;)s=u[u.length-1].to,a=n(s+(r-o)/3,t),s>=a&&(a=s+1),u.push({from:s,to:a});for(;i>a;)s=u[u.length-1].to,a=n(s+(i-r)/3,t),s>=a&&(a=s+1),u.push({from:s,to:a});1===u.length&&a!==r&&(u.push({from:a,to:r}),a=r),1===u.length?(u[0].from=e.min,u[0].to=e.max):delete u[u.length-1].to}return u}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:"\n {{#from}}\n {{^to}}\n &ge;\n {{/to}}\n {{currency}}{{from}}\n {{/from}}\n {{#to}}\n {{#from}}\n -\n {{/from}}\n {{^from}}\n &le;\n {{/from}}\n {{to}}\n {{/to}}\n ",footer:""},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},c=n(218),p=r(c),f=n(380),d=r(f),h=n(422),m=r(h),v=n(377),g=r(v),y=function(e){function t(){i(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return a(t,e),u(t,[{key:"getForm",value:function(){var e=s({currency:this.props.currency},this.props.labels);return p["default"].createElement(m["default"],{cssClasses:this.props.cssClasses,labels:e,refine:this.refine.bind(this)})}},{key:"getURLFromFacetValue",value:function(e){return this.props.createURL?this.props.createURL(e.from,e.to,e.isRefined):"#"}},{key:"getItemFromFacetValue",value:function(e){var t=(0,g["default"])(this.props.cssClasses.item,o({},this.props.cssClasses.active,e.isRefined)),n=this.getURLFromFacetValue(e),r=e.from+"_"+e.to,i=this.refine.bind(this,e.from,e.to),a=s({currency:this.props.currency},e);return p["default"].createElement("div",{className:t,key:r},p["default"].createElement("a",{className:this.props.cssClasses.link,href:n,onClick:i},p["default"].createElement(d["default"],s({data:a,templateKey:"item"},this.props.templateProps))))}},{key:"refine",value:function(e,t,n){n.preventDefault(),this.setState({formFromValue:null,formToValue:null}),this.props.refine(e,t)}},{key:"render",value:function(){var e=this,t=this.getForm();return p["default"].createElement("div",null,p["default"].createElement("div",{className:this.props.cssClasses.list},this.props.facetValues.map(function(t){return e.getItemFromFacetValue(t)})),t)}}]),t}(p["default"].Component);y.propTypes={createURL:p["default"].PropTypes.func.isRequired,cssClasses:p["default"].PropTypes.shape({active:p["default"].PropTypes.string,button:p["default"].PropTypes.string,form:p["default"].PropTypes.string,input:p["default"].PropTypes.string,item:p["default"].PropTypes.string,label:p["default"].PropTypes.string,link:p["default"].PropTypes.string,list:p["default"].PropTypes.string,separator:p["default"].PropTypes.string}),currency:p["default"].PropTypes.string,facetValues:p["default"].PropTypes.array,labels:p["default"].PropTypes.shape({button:p["default"].PropTypes.string,to:p["default"].PropTypes.string}),refine:p["default"].PropTypes.func.isRequired,templateProps:p["default"].PropTypes.object.isRequired},y.defaultProps={cssClasses:{}},t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},u=n(218),l=r(u),c=function(e){function t(){o(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),a(t,[{key:"getInput",value:function(e){return l["default"].createElement("label",{className:this.props.cssClasses.label},l["default"].createElement("span",{className:this.props.cssClasses.currency},this.props.labels.currency," "),l["default"].createElement("input",{className:this.props.cssClasses.input,ref:e,type:"number"}))}},{key:"handleSubmit",value:function(e){var t=+this.refs.from.value||void 0,n=+this.refs.to.value||void 0;this.props.refine(t,n,e)}},{key:"render",value:function(){var e=this.getInput("from"),t=this.getInput("to"),n=this.handleSubmit.bind(this);return l["default"].createElement("form",{className:this.props.cssClasses.form,onSubmit:n,ref:"form"},e,l["default"].createElement("span",{className:this.props.cssClasses.separator}," ",this.props.labels.separator," "),t,l["default"].createElement("button",{className:this.props.cssClasses.button,type:"submit"},this.props.labels.button))}}]),t}(l["default"].Component);c.propTypes={cssClasses:l["default"].PropTypes.shape({button:l["default"].PropTypes.string,currency:l["default"].PropTypes.string,form:l["default"].PropTypes.string,input:l["default"].PropTypes.string,label:l["default"].PropTypes.string,separator:l["default"].PropTypes.string}),labels:l["default"].PropTypes.shape({button:l["default"].PropTypes.string,currency:l["default"].PropTypes.string,separator:l["default"].PropTypes.string}),refine:l["default"].PropTypes.func.isRequired},c.defaultProps={cssClasses:{},labels:{}},t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.container,r=e.placeholder,o=void 0===r?"":r,i=e.cssClasses,s=void 0===i?{}:i,l=e.poweredBy,p=void 0===l?!1:l,d=e.wrapInput,b=void 0===d?!0:d,_=e.autofocus,x=void 0===_?"auto":_,P=e.searchOnEnterKeyPressOnly,C=void 0===P?!1:P;if(!t)throw new Error(y);return t=c["default"].getContainerNode(t),"boolean"!=typeof x&&(x="auto"),{getInput:function(){return"INPUT"===t.tagName?t:document.createElement("input")},wrapInput:function(e){var t=document.createElement("div"),n=(0,h["default"])(m(null),s.root).split(" ");return t.classList.add.apply(t.classList,n),t.appendChild(e),t},addDefaultAttributesToInput:function(e,t){var n={autocapitalize:"off",autocomplete:"off",autocorrect:"off",placeholder:o,role:"textbox",spellcheck:"false",type:"text",value:t};(0,f["default"])(n,function(t,n){e.hasAttribute(n)||e.setAttribute(n,t)});var r=(0,h["default"])(m("input"),s.input).split(" ");e.classList.add.apply(e.classList,r)},addPoweredBy:function(e){var t=n(424),r=document.createElement("div");e.parentNode.insertBefore(r,e.nextSibling);var o={root:(0,h["default"])(m("powered-by"),s.poweredBy),link:m("powered-by-link")},i="https://www.algolia.com/?utm_source=instantsearch.js&utm_medium=website&"+("utm_content="+location.hostname+"&")+"utm_campaign=poweredby";u["default"].render(a["default"].createElement(t,{cssClasses:o,link:i}),r)},init:function(e){function n(e){var t=e.currentTarget?e.currentTarget:e.srcElement;o.setQuery(t.value),C||o.search()}var r=e.state,o=e.helper,i=e.onHistoryChange,a="INPUT"===t.tagName,s=this.getInput();if(this.addDefaultAttributesToInput(s,r.query),s.addEventListener("keyup",function(e){o.setQuery(s.value),C&&e.keyCode===v&&o.search(),window.attachEvent&&e.keyCode===g&&o.search()}),window.attachEvent?s.attachEvent("onpropertychange",n):s.addEventListener("input",n,!1),a){var u=document.createElement("div");s.parentNode.insertBefore(u,s);var l=s.parentNode,c=b?this.wrapInput(s):s;l.replaceChild(c,u)}else{var c=b?this.wrapInput(s):s;t.appendChild(c)}p&&this.addPoweredBy(s),i(function(e){s.value=e.query||""}),(x===!0||"auto"===x&&""===o.state.query)&&s.focus()}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=r(l),p=n(14),f=r(p),d=n(377),h=r(d),m=n(373).bemHelper("ais-search-box"),v=13,g=8,y="Usage:\nsearchBox({\n container,\n [ placeholder ],\n [ cssClasses.{input,poweredBy} ],\n [ poweredBy ],\n [ wrapInput ],\n [ autofocus ],\n [ searchOnEnterKeyPressOnly ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},u=n(218),l=r(u),c=function(e){function t(){o(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),a(t,[{key:"render",value:function(){return l["default"].createElement("div",{className:this.props.cssClasses.root},"Search by",l["default"].createElement("a",{className:this.props.cssClasses.link,href:this.props.link,target:"_blank"},"Algolia"))}}]),t}(l["default"].Component);c.propTypes={cssClasses:l["default"].PropTypes.shape({root:l["default"].PropTypes.string,link:l["default"].PropTypes.string}),link:l["default"].PropTypes.string.isRequired},t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.attributeName,o=e.tooltips,i=void 0===o?!0:o,s=e.templates,l=void 0===s?_:s,p=e.cssClasses,d=void 0===p?{}:p,m=e.step,g=void 0===m?1:m,P=e.pips,C=void 0===P?!0:P,w=e.autoHideContainer,R=void 0===w?!0:w;if(!t||!r)throw new Error(x);var E=c["default"].getContainerNode(t),T=(0,v["default"])(n(426));return R===!0&&(T=(0,h["default"])(T)),{getConfiguration:function(){return{disjunctiveFacets:[r]}},_getCurrentRefinement:function(e){var t=e.state.getNumericRefinement(r,">="),n=e.state.getNumericRefinement(r,"<=");return t=t&&t.length?t[0]:-(1/0),n=n&&n.length?n[0]:1/0,{min:t,max:n}},_refine:function(e,t,n){e.clearRefinements(r),n[0]>t.min&&e.addNumericRefinement(r,">=",Math.round(n[0])),n[1]<t.max&&e.addNumericRefinement(r,"<=",Math.round(n[1])),e.search()},render:function(e){var t=e.results,n=e.helper,o=e.templatesConfig,s={root:(0,y["default"])(b(null),d.root),header:(0,y["default"])(b("header"),d.header),body:(0,y["default"])(b("body"),d.body),footer:(0,y["default"])(b("footer"),d.footer)},p=(0,f["default"])(t.disjunctiveFacets,{name:r}),h=void 0!==p?p.stats:void 0,m=this._getCurrentRefinement(n);void 0===h&&(h={min:null,max:null});var v=h.min===h.max,x=c["default"].prepareTemplateProps({defaultTemplates:_,templatesConfig:o,templates:l});u["default"].render(a["default"].createElement(T,{cssClasses:s,onChange:this._refine.bind(this,n,h),pips:C,range:{min:Math.floor(h.min),max:Math.ceil(h.max)},shouldAutoHideContainer:v,start:[m.min,m.max],step:g,templateProps:x,tooltips:i}),E)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=r(l),p=n(128),f=r(p),d=n(378),h=r(d),m=n(379),v=r(m),g=n(377),y=r(g),b=n(373).bemHelper("ais-range-slider"),_={header:"",footer:""},x="Usage:\nrangeSlider({\n container,\n attributeName,\n [ tooltips=true ],\n [ templates.{header, footer} ],\n [ cssClasses.{root, header, body, footer} ],\n [ step=1 ],\n [ pips=true ],\n [ autoHideContainer=true ]\n});\n";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},l=n(218),c=r(l),p=n(427),f=r(p),d="ais-range-slider--",h=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"handleChange",value:function(e,t,n){this.props.onChange(n)}},{key:"render",value:function(){var e=void 0;return e=this.props.pips===!1?void 0:this.props.pips===!0||"undefined"==typeof this.props.pips?{mode:"positions",density:3,values:[0,50,100],stepped:!0,format:{to:function(e){return Number(e).toLocaleString()}}}:this.props.pips,c["default"].createElement(f["default"],a({},this.props,{animate:!1,behaviour:"snap",connect:!0,cssPrefix:d,onChange:this.handleChange.bind(this),pips:e}))}}]),t}(c["default"].Component);h.propTypes={onChange:c["default"].PropTypes.func,onSlide:c["default"].PropTypes.func,pips:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.object]),range:c["default"].PropTypes.object.isRequired,start:c["default"].PropTypes.arrayOf(c["default"].PropTypes.number).isRequired,tooltips:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.object])},t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},l=n(218),c=r(l),p=n(428),f=r(p),d=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"componentDidMount",value:function(){this.createSlider()}},{key:"componentDidUpdate",value:function(){this.slider.destroy(),this.createSlider()}},{key:"componentWillUnmount",value:function(){this.slider.destroy()}},{key:"createSlider",value:function(){var e=this.slider=f["default"].create(this.sliderContainer,a({},this.props));this.props.onUpdate&&e.on("update",this.props.onUpdate),this.props.onChange&&e.on("change",this.props.onChange),this.props.onSlide&&e.on("slide",this.props.onSlide)}},{key:"render",value:function(){var e=this;return c["default"].createElement("div",{ref:function(t){e.sliderContainer=t}})}}]),t}(c["default"].Component);d.propTypes={animate:c["default"].PropTypes.bool,connect:c["default"].PropTypes.oneOfType([c["default"].PropTypes.oneOf(["lower","upper"]),c["default"].PropTypes.bool]),cssPrefix:c["default"].PropTypes.string,direction:c["default"].PropTypes.oneOf(["ltr","rtl"]),limit:c["default"].PropTypes.number,margin:c["default"].PropTypes.number,onChange:c["default"].PropTypes.func,onSlide:c["default"].PropTypes.func,onUpdate:c["default"].PropTypes.func,orientation:c["default"].PropTypes.oneOf(["horizontal","vertical"]),pips:c["default"].PropTypes.object,range:c["default"].PropTypes.object.isRequired,start:c["default"].PropTypes.arrayOf(c["default"].PropTypes.number).isRequired,step:c["default"].PropTypes.number,tooltips:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.object])},e.exports=d},function(e,t,n){var r,o,i;!function(n){o=[],r=n,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i))}(function(){"use strict";function e(e){return e.filter(function(e){return this[e]?!1:this[e]=!0},{})}function t(e,t){return Math.round(e/t)*t}function n(e){var t=e.getBoundingClientRect(),n=e.ownerDocument,r=n.documentElement,o=f();return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(o.x=0),{top:t.top+o.y-r.clientTop,left:t.left+o.x-r.clientLeft}}function r(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}function o(e){var t=Math.pow(10,7);return Number((Math.round(e*t)/t).toFixed(7))}function i(e,t,n){l(e,t),setTimeout(function(){c(e,t)},n)}function a(e){return Math.max(Math.min(e,100),0)}function s(e){return Array.isArray(e)?e:[e]}function u(e){var t=e.split(".");return t.length>1?t[1].length:0}function l(e,t){e.classList?e.classList.add(t):e.className+=" "+t}function c(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")}function p(e,t){e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)}function f(){var e=void 0!==window.pageXOffset,t="CSS1Compat"===(document.compatMode||""),n=e?window.pageXOffset:t?document.documentElement.scrollLeft:document.body.scrollLeft,r=e?window.pageYOffset:t?document.documentElement.scrollTop:document.body.scrollTop;return{x:n,y:r}}function d(e){return function(t){return e+t}}function h(e,t){return 100/(t-e)}function m(e,t){return 100*t/(e[1]-e[0])}function v(e,t){return m(e,e[0]<0?t+Math.abs(e[0]):t-e[0])}function g(e,t){return t*(e[1]-e[0])/100+e[0]}function y(e,t){for(var n=1;e>=t[n];)n+=1;return n}function b(e,t,n){if(n>=e.slice(-1)[0])return 100;var r,o,i,a,s=y(n,e);return r=e[s-1],o=e[s],i=t[s-1],a=t[s],i+v([r,o],n)/h(i,a)}function _(e,t,n){if(n>=100)return e.slice(-1)[0];var r,o,i,a,s=y(n,t);return r=e[s-1],o=e[s],i=t[s-1],a=t[s],g([r,o],(n-i)*h(i,a))}function x(e,n,r,o){if(100===o)return o;var i,a,s=y(o,e);return r?(i=e[s-1],a=e[s],o-i>(a-i)/2?a:i):n[s-1]?e[s-1]+t(o-e[s-1],n[s-1]):o}function P(e,t,n){var o;if("number"==typeof t&&(t=[t]),"[object Array]"!==Object.prototype.toString.call(t))throw new Error("noUiSlider: 'range' contains invalid value.");if(o="min"===e?0:"max"===e?100:parseFloat(e),!r(o)||!r(t[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");n.xPct.push(o),n.xVal.push(t[0]),o?n.xSteps.push(isNaN(t[1])?!1:t[1]):isNaN(t[1])||(n.xSteps[0]=t[1])}function C(e,t,n){return t?void(n.xSteps[e]=m([n.xVal[e],n.xVal[e+1]],t)/h(n.xPct[e],n.xPct[e+1])):!0}function w(e,t,n,r){this.xPct=[],this.xVal=[],this.xSteps=[r||!1],this.xNumSteps=[!1],this.snap=t,this.direction=n;var o,i=[];for(o in e)e.hasOwnProperty(o)&&i.push([e[o],o]);for(i.length&&"object"==typeof i[0][0]?i.sort(function(e,t){return e[0][0]-t[0][0]}):i.sort(function(e,t){return e[0]-t[0]}),o=0;o<i.length;o++)P(i[o][1],i[o][0],this);for(this.xNumSteps=this.xSteps.slice(0),o=0;o<this.xNumSteps.length;o++)C(o,this.xNumSteps[o],this)}function R(e,t){if(!r(t))throw new Error("noUiSlider: 'step' is not numeric.");e.singleStep=t}function E(e,t){if("object"!=typeof t||Array.isArray(t))throw new Error("noUiSlider: 'range' is not an object.");if(void 0===t.min||void 0===t.max)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");e.spectrum=new w(t,e.snap,e.dir,e.singleStep)}function T(e,t){if(t=s(t),!Array.isArray(t)||!t.length||t.length>2)throw new Error("noUiSlider: 'start' option is incorrect.");e.handles=t.length,e.start=t}function O(e,t){if(e.snap=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'snap' option must be a boolean.")}function S(e,t){if(e.animate=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'animate' option must be a boolean.")}function j(e,t){if("lower"===t&&1===e.handles)e.connect=1;else if("upper"===t&&1===e.handles)e.connect=2;else if(t===!0&&2===e.handles)e.connect=3;else{if(t!==!1)throw new Error("noUiSlider: 'connect' option doesn't match handle count.");e.connect=0}}function N(e,t){switch(t){case"horizontal":e.ort=0;break;case"vertical":e.ort=1;break;default:throw new Error("noUiSlider: 'orientation' option is invalid.")}}function k(e,t){if(!r(t))throw new Error("noUiSlider: 'margin' option must be numeric.");if(e.margin=e.spectrum.getMargin(t),!e.margin)throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.")}function M(e,t){if(!r(t))throw new Error("noUiSlider: 'limit' option must be numeric.");if(e.limit=e.spectrum.getMargin(t),!e.limit)throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.")}function D(e,t){switch(t){case"ltr":e.dir=0;break;case"rtl":e.dir=1,e.connect=[0,2,1,3][e.connect];break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}function I(e,t){if("string"!=typeof t)throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var n=t.indexOf("tap")>=0,r=t.indexOf("drag")>=0,o=t.indexOf("fixed")>=0,i=t.indexOf("snap")>=0;if(r&&!e.connect)throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true.");e.events={tap:n||i,drag:r,fixed:o,snap:i}}function A(e,t){if(t===!0&&(e.tooltips=!0),t&&t.format){if("function"!=typeof t.format)throw new Error("noUiSlider: 'tooltips.format' must be an object.");e.tooltips={format:t.format}}}function F(e,t){if(e.format=t,"function"==typeof t.to&&"function"==typeof t.from)return!0;throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.")}function L(e,t){if(void 0!==t&&"string"!=typeof t)throw new Error("noUiSlider: 'cssPrefix' must be a string.");e.cssPrefix=t}function U(e){var t,n={margin:0,limit:0,animate:!0,format:W};t={step:{r:!1,t:R},start:{r:!0,t:T},connect:{r:!0,t:j},direction:{r:!0,t:D},snap:{r:!1,t:O},animate:{r:!1,t:S},range:{r:!0,t:E},orientation:{r:!1,t:N},margin:{r:!1,t:k},limit:{r:!1,t:M},behaviour:{r:!0,t:I},format:{r:!1,t:F},tooltips:{r:!1,t:A},cssPrefix:{r:!1,t:L}};var r={connect:!1,direction:"ltr",behaviour:"tap",orientation:"horizontal"};return Object.keys(r).forEach(function(t){void 0===e[t]&&(e[t]=r[t])}),Object.keys(t).forEach(function(r){var o=t[r];if(void 0===e[r]){if(o.r)throw new Error("noUiSlider: '"+r+"' is required.");return!0}o.t(n,e[r])}),n.pips=e.pips,n.style=n.ort?"top":"left",n}function H(t,r){function o(e,t,n){var r=e+t[0],o=e+t[1];return n?(0>r&&(o+=Math.abs(r)),o>100&&(r-=o-100),[a(r),a(o)]):[r,o]}function h(e,t){e.preventDefault();var n,r,o=0===e.type.indexOf("touch"),i=0===e.type.indexOf("mouse"),a=0===e.type.indexOf("pointer"),s=e;return 0===e.type.indexOf("MSPointer")&&(a=!0),o&&(n=e.changedTouches[0].pageX,r=e.changedTouches[0].pageY),t=t||f(),(i||a)&&(n=e.clientX+t.x,r=e.clientY+t.y),s.pageOffset=t,s.points=[n,r],s.cursor=i||a,s}function m(e,t){var n=document.createElement("div"),r=document.createElement("div"),o=["-lower","-upper"];return e&&o.reverse(),l(r,ee[3]),l(r,ee[3]+o[t]),l(n,ee[2]),n.appendChild(r),n}function v(e,t,n){switch(e){case 1:l(t,ee[7]),l(n[0],ee[6]);break;case 3:l(n[1],ee[6]);case 2:l(n[0],ee[7]);case 0:l(t,ee[6])}}function g(e,t,n){var r,o=[];for(r=0;e>r;r+=1)o.push(n.appendChild(m(t,r)));return o}function y(e,t,n){l(n,ee[0]),l(n,ee[8+e]),l(n,ee[4+t]);var r=document.createElement("div");return l(r,ee[1]),n.appendChild(r),r}function b(e){return e}function _(e){var t=document.createElement("div");return t.className=ee[18],e.firstChild.appendChild(t)}function x(e){var t=e.format?e.format:b,n=G.map(_);W("update",function(e,r,o){n[r].innerHTML=t(e[r],o[r])})}function P(e,t,n){if("range"===e||"steps"===e)return J.xVal;if("count"===e){var r,o=100/(t-1),i=0;for(t=[];(r=i++*o)<=100;)t.push(r);e="positions"}return"positions"===e?t.map(function(e){return J.fromStepping(n?J.getStep(e):e)}):"values"===e?n?t.map(function(e){return J.fromStepping(J.getStep(J.toStepping(e)))}):t:void 0}function C(t,n,r){function o(e,t){return(e+t).toFixed(7)/1}var i=J.direction,a={},s=J.xVal[0],u=J.xVal[J.xVal.length-1],l=!1,c=!1,p=0;return J.direction=0,r=e(r.slice().sort(function(e,t){return e-t})),r[0]!==s&&(r.unshift(s),l=!0),r[r.length-1]!==u&&(r.push(u),c=!0),r.forEach(function(e,i){var s,u,f,d,h,m,v,g,y,b,_=e,x=r[i+1];if("steps"===n&&(s=J.xNumSteps[i]),s||(s=x-_),_!==!1&&void 0!==x)for(u=_;x>=u;u=o(u,s)){for(d=J.toStepping(u),h=d-p,g=h/t,y=Math.round(g),b=h/y,f=1;y>=f;f+=1)m=p+f*b,a[m.toFixed(5)]=["x",0];v=r.indexOf(u)>-1?1:"steps"===n?2:0,!i&&l&&(v=0),u===x&&c||(a[d.toFixed(5)]=[u,v]),p=d}}),J.direction=i,a}function w(e,t,n){function o(e){return["-normal","-large","-sub"][e]}function i(e,t,n){return'class="'+t+" "+t+"-"+s+" "+t+o(n[1])+'" style="'+r.style+": "+e+'%"'}function a(e,r){J.direction&&(e=100-e),r[1]=r[1]&&t?t(r[0],r[1]):r[1],u.innerHTML+="<div "+i(e,ee[21],r)+"></div>",r[1]&&(u.innerHTML+="<div "+i(e,ee[22],r)+">"+n.to(r[0])+"</div>")}var s=["horizontal","vertical"][r.ort],u=document.createElement("div");return l(u,ee[20]),l(u,ee[20]+"-"+s),Object.keys(e).forEach(function(t){a(t,e[t])}),u}function R(e){var t=e.mode,n=e.density||1,r=e.filter||!1,o=e.values||!1,i=e.stepped||!1,a=P(t,o,i),s=C(n,t,a),u=e.format||{to:Math.round};return Y.appendChild(w(s,r,u))}function E(){return z["offset"+["Width","Height"][r.ort]]}function T(e,t){void 0!==t&&1!==r.handles&&(t=Math.abs(t-r.dir)),Object.keys(Z).forEach(function(n){var r=n.split(".")[0];e===r&&Z[n].forEach(function(e){e(s(L()),t,O(Array.prototype.slice.call(X)))})})}function O(e){return 1===e.length?e[0]:r.dir?e.reverse():e}function S(e,t,n,o){var i=function(t){return Y.hasAttribute("disabled")?!1:p(Y,ee[14])?!1:(t=h(t,o.pageOffset),e===q.start&&void 0!==t.buttons&&t.buttons>1?!1:(t.calcPoint=t.points[r.ort],void n(t,o)))},a=[];return e.split(" ").forEach(function(e){t.addEventListener(e,i,!1),a.push([e,i])}),a}function j(e,t){if(0===e.buttons&&0===e.which&&0!==t.buttonsProperty)return N(e,t);var n,r,i=t.handles||G,a=!1,s=100*(e.calcPoint-t.start)/t.baseSize,u=i[0]===G[0]?0:1;if(n=o(s,t.positions,i.length>1),a=I(i[0],n[u],1===i.length),i.length>1){if(a=I(i[1],n[u?0:1],!1)||a)for(r=0;r<t.handles.length;r++)T("slide",r)}else a&&T("slide",u)}function N(e,t){var n=z.querySelector("."+ee[15]),r=t.handles[0]===G[0]?0:1;null!==n&&c(n,ee[15]),e.cursor&&(document.body.style.cursor="",document.body.removeEventListener("selectstart",document.body.noUiListener));var o=document.documentElement;o.noUiListeners.forEach(function(e){o.removeEventListener(e[0],e[1])}),c(Y,ee[12]),T("set",r),T("change",r)}function k(e,t){var n=document.documentElement;if(1===t.handles.length&&(l(t.handles[0].children[0],ee[15]),t.handles[0].hasAttribute("disabled")))return!1;e.stopPropagation();var r=S(q.move,n,j,{start:e.calcPoint,baseSize:E(),pageOffset:e.pageOffset,handles:t.handles,buttonsProperty:e.buttons,positions:[$[0],$[G.length-1]]}),o=S(q.end,n,N,{handles:t.handles});if(n.noUiListeners=r.concat(o),e.cursor){document.body.style.cursor=getComputedStyle(e.target).cursor,G.length>1&&l(Y,ee[12]);var i=function(){return!1};document.body.noUiListener=i,document.body.addEventListener("selectstart",i,!1)}}function M(e){var t,o,a=e.calcPoint,s=0;return e.stopPropagation(),G.forEach(function(e){s+=n(e)[r.style]}),t=s/2>a||1===G.length?0:1,a-=n(z)[r.style],o=100*a/E(),r.events.snap||i(Y,ee[14],300),G[t].hasAttribute("disabled")?!1:(I(G[t],o),T("slide",t),T("set",t),T("change",t),void(r.events.snap&&k(e,{handles:[G[t]]})))}function D(e){var t,n;if(!e.fixed)for(t=0;t<G.length;t+=1)S(q.start,G[t].children[0],k,{handles:[G[t]]});e.tap&&S(q.start,z,M,{handles:G}),e.drag&&(n=[z.querySelector("."+ee[7])],l(n[0],ee[10]),e.fixed&&n.push(G[n[0]===G[0]?1:0].children[0]),n.forEach(function(e){S(q.start,e,k,{handles:G})}))}function I(e,t,n){var o=e!==G[0]?1:0,i=$[0]+r.margin,s=$[1]-r.margin,u=$[0]+r.limit,p=$[1]-r.limit,f=J.fromStepping(t);return G.length>1&&(t=o?Math.max(t,i):Math.min(t,s)),n!==!1&&r.limit&&G.length>1&&(t=o?Math.min(t,u):Math.max(t,p)),t=J.getStep(t),t=a(parseFloat(t.toFixed(7))),t===$[o]&&f===X[o]?!1:(window.requestAnimationFrame?window.requestAnimationFrame(function(){e.style[r.style]=t+"%"}):e.style[r.style]=t+"%",e.previousSibling||(c(e,ee[17]),t>50&&l(e,ee[17])),$[o]=t,X[o]=J.fromStepping(t),T("update",o),!0)}function A(e,t){var n,o,i;for(r.limit&&(e+=1),n=0;e>n;n+=1)o=n%2,i=t[o],null!==i&&i!==!1&&("number"==typeof i&&(i=String(i)),i=r.format.from(i),(i===!1||isNaN(i)||I(G[o],J.toStepping(i),n===3-r.dir)===!1)&&T("update",o))}function F(e){var t,n,o=s(e);for(r.dir&&r.handles>1&&o.reverse(),r.animate&&-1!==$[0]&&i(Y,ee[14],300),t=G.length>1?3:1,1===o.length&&(t=1),A(t,o),n=0;n<G.length;n++)T("set",n)}function L(){var e,t=[];for(e=0;e<r.handles;e+=1)t[e]=r.format.to(X[e]);return O(t)}function H(){ee.forEach(function(e){e&&c(Y,e)}),Y.innerHTML="",delete Y.noUiSlider}function B(){var e=$.map(function(e,t){var n=J.getApplicableStep(e),r=u(String(n[2])),o=X[t],i=100===e?null:n[2],a=Number((o-n[2]).toFixed(r)),s=0===e?null:a>=n[1]?n[2]:n[0]||!1;return[s,i]});return O(e)}function W(e,t){Z[e]=Z[e]||[],Z[e].push(t),"update"===e.split(".")[0]&&G.forEach(function(e,t){T("update",t)})}function K(e){var t=e.split(".")[0],n=e.substring(t.length);Object.keys(Z).forEach(function(e){var r=e.split(".")[0],o=e.substring(r.length);t&&t!==r||n&&n!==o||delete Z[e]})}function Q(e){var t=U({start:[0,0],margin:e.margin,limit:e.limit,step:e.step,range:e.range,animate:e.animate});r.margin=t.margin,r.limit=t.limit,r.step=t.step,r.range=t.range,r.animate=t.animate,J=t.spectrum}var z,G,Y=t,$=[-1,-1],J=r.spectrum,X=[],Z={},ee=["target","base","origin","handle","horizontal","vertical","background","connect","ltr","rtl","draggable","","state-drag","","state-tap","active","","stacking","tooltip","","pips","marker","value"].map(d(r.cssPrefix||V));if(Y.noUiSlider)throw new Error("Slider was already initialized.");return z=y(r.dir,r.ort,Y),G=g(r.handles,r.dir,z),v(r.connect,Y,G),D(r.events),r.pips&&R(r.pips),r.tooltips&&x(r.tooltips),{destroy:H,steps:B,on:W,off:K,get:L,set:F,updateOptions:Q}}function B(e,t){if(!e.nodeName)throw new Error("noUiSlider.create requires a single element.");var n=U(t,e),r=H(e,n);return r.set(n.start),e.noUiSlider=r,r}var q=window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"},V="noUi-";w.prototype.getMargin=function(e){return 2===this.xPct.length?m(this.xVal,e):!1},w.prototype.toStepping=function(e){return e=b(this.xVal,this.xPct,e),this.direction&&(e=100-e),e},w.prototype.fromStepping=function(e){return this.direction&&(e=100-e),o(_(this.xVal,this.xPct,e))},w.prototype.getStep=function(e){return this.direction&&(e=100-e),e=x(this.xPct,this.xSteps,this.snap,e),this.direction&&(e=100-e),e},w.prototype.getApplicableStep=function(e){var t=y(e,this.xPct),n=100===e?2:1;return[this.xNumSteps[t-2],this.xVal[t-n],this.xNumSteps[t-n]]},w.prototype.convert=function(e){return this.getStep(this.toStepping(e))};var W={to:function(e){return void 0!==e&&e.toFixed(2)},from:Number};return{create:B}})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.indices,o=e.cssClasses,i=void 0===o?{}:o,s=e.autoHideContainer,l=void 0===s?!1:s;if(!t||!r)throw new Error(_);var p=h["default"].getContainerNode(t),d=n(402);l===!0&&(d=(0,y["default"])(d));var m=(0,f["default"])(r,function(e){return{label:e.label,value:e.name}});return{init:function(e){var t=e.helper,n=t.getIndex(),o=-1!==(0,c["default"])(r,{name:n});if(!o)throw new Error("[sortBySelector]: Index "+n+" not present in `indices`")},setIndex:function(e,t){e.setIndex(t),e.search()},render:function(e){var t=e.helper,n=e.results,r=t.getIndex(),o=0===n.nbHits,s=this.setIndex.bind(this,t),l={root:(0,v["default"])(b(null),i.root),item:(0,v["default"])(b("item"),i.item)};u["default"].render(a["default"].createElement(d,{cssClasses:l,currentValue:r,options:m,setValue:s,shouldAutoHideContainer:o}),p)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(143),c=r(l),p=n(53),f=r(p),d=n(373),h=r(d),m=n(377),v=r(m),g=n(378),y=r(g),b=h["default"].bemHelper("ais-sort-by-selector"),_="Usage:\nsortBySelector({\n container,\n indices,\n [cssClasses.{root,item}={}],\n [autoHideContainer=false]\n})";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.container,r=e.attributeName,o=e.max,i=void 0===o?5:o,s=e.cssClasses,l=void 0===s?{}:s,p=e.labels,d=void 0===p?_["default"]:p,m=e.templates,g=void 0===m?y["default"]:m,b=e.transformData,C=e.autoHideContainer,w=void 0===C?!0:C,R=c["default"].getContainerNode(t),E=(0,v["default"])(n(394));if(w===!0&&(E=(0,h["default"])(E)),!t||!r)throw new Error(P);return{getConfiguration:function(){return{disjunctiveFacets:[r]}},render:function(e){for(var t=e.helper,n=e.results,o=e.templatesConfig,s=e.state,p=e.createURL,h=c["default"].prepareTemplateProps({transformData:b,defaultTemplates:y["default"],templatesConfig:o,templates:g}),m=[],v={},_=i-1;_>=0;--_)v[_]=0;n.getFacetValues(r).forEach(function(e){var t=Math.round(e.name);if(t&&!(t>i-1))for(var n=t;n>=1;--n)v[n]+=e.count});for(var P=this._getRefinedStar(t),C=i-1;C>=1;--C){var w=v[C];if(!P||C===P||0!==w){for(var T=[],O=1;i>=O;++O)T.push(C>=O);m.push({stars:T,name:""+C,count:w,isRefined:P===C,labels:d})}}var S={root:(0,f["default"])(x(null),l.root),header:(0,f["default"])(x("header"),l.header),body:(0,f["default"])(x("body"),l.body),footer:(0,f["default"])(x("footer"),l.footer),list:(0,f["default"])(x("list"),l.list),item:(0,f["default"])(x("item"),l.item),link:(0,f["default"])(x("link"),l.link),disabledLink:(0,f["default"])(x("link","disabled"),l.disabledLink),count:(0,f["default"])(x("count"),l.count),star:(0,f["default"])(x("star"),l.star),emptyStar:(0,f["default"])(x("star","empty"),l.emptyStar),active:(0,f["default"])(x("item","active"),l.active)};u["default"].render(a["default"].createElement(E,{createURL:function(e){return p(s.toggleRefinement(r,e))},cssClasses:S,facetValues:m,shouldAutoHideContainer:0===n.nbHits,templateProps:h,toggleRefinement:this._toggleRefinement.bind(this,t)}),R)},_toggleRefinement:function(e,t){var n=this._getRefinedStar(e)===+t;if(e.clearRefinements(r),!n)for(var o=+t;i>=o;++o)e.addDisjunctiveFacetRefinement(r,o);e.search()},_getRefinedStar:function(e){var t=void 0,n=e.getRefinements(r);return n.forEach(function(e){(!t||+e.value<t)&&(t=+e.value)}),t}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=r(l),p=n(377),f=r(p),d=n(378),h=r(d),m=n(379),v=r(m),g=n(431),y=r(g),b=n(432),_=r(b),x=c["default"].bemHelper("ais-star-rating"),P="Usage:\nstarRating({\n container,\n attributeName,\n [ max=5 ],\n [ cssClasses.{root,header,body,footer,list,item,active,link,disabledLink,star,emptyStar,count} ],\n [ templates.{header,item,footer} ],\n [ labels.{andUp} ],\n [ transformData ],\n [ autoHideContainer=true ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:'<a class="{{cssClasses.link}}{{^count}} {{cssClasses.disabledLink}}{{/count}}" {{#count}}href="{{href}}"{{/count}}>\n {{#stars}}<span class="{{#.}}{{cssClasses.star}}{{/.}}{{^.}}{{cssClasses.emptyStar}}{{/.}}"></span>{{/stars}}\n {{labels.andUp}}\n {{#count}}<span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>{{/count}}\n</a>',footer:""},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={andUp:"& Up"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.cssClasses,o=void 0===r?{}:r,i=e.autoHideContainer,s=void 0===i?!0:i,l=e.templates,p=void 0===l?y["default"]:l,d=e.transformData;if(!t)throw new Error(_);var m=c["default"].getContainerNode(t),g=(0,h["default"])(n(435));if(s===!0&&(g=(0,f["default"])(g)),!m)throw new Error(_);return{render:function(e){var t=e.results,n=e.templatesConfig,r=0===t.nbHits,i=c["default"].prepareTemplateProps({transformData:d,defaultTemplates:y["default"],templatesConfig:n,templates:p}),s={body:(0,v["default"])(b("body"),o.body),footer:(0,v["default"])(b("footer"),o.footer),header:(0,v["default"])(b("header"),o.header),root:(0,v["default"])(b(null),o.root),time:(0,v["default"])(b("time"),o.time)};u["default"].render(a["default"].createElement(g,{cssClasses:s,hitsPerPage:t.hitsPerPage,nbHits:t.nbHits,nbPages:t.nbPages,page:t.page,processingTimeMS:t.processingTimeMS,query:t.query,shouldAutoHideContainer:r,templateProps:i}),m)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(218),a=r(i),s=n(371),u=r(s),l=n(373),c=r(l),p=n(378),f=r(p),d=n(379),h=r(d),m=n(377),v=r(m),g=n(434),y=r(g),b=n(373).bemHelper("ais-stats"),_="Usage:\nstats({\n container,\n [ template ],\n [ transformData ],\n [ autoHideContainer]\n})";t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",body:'{{#hasNoResults}}No results{{/hasNoResults}}\n {{#hasOneResult}}1 result{{/hasOneResult}}\n {{#hasManyResults}}{{#helpers.formatNumber}}{{nbHits}}{{/helpers.formatNumber}} results{{/hasManyResults}}\n <span class="{{cssClasses.time}}">found in {{processingTimeMS}}ms</span>',footer:""},e.exports=t["default"]},function(e,t,n){"use strict";function r(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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var l=Object.getPrototypeOf(o);if(null===l)return;e=l,t=i,n=a,r=!0,s=l=void 0}},l=n(218),c=r(l),p=n(380),f=r(p),d=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"render",value:function(){var e={hasManyResults:this.props.nbHits>1,hasNoResults:0===this.props.nbHits,hasOneResult:1===this.props.nbHits,hitsPerPage:this.props.hitsPerPage,nbHits:this.props.nbHits,nbPages:this.props.nbPages,page:this.props.page,processingTimeMS:this.props.processingTimeMS,query:this.props.query,cssClasses:this.props.cssClasses};return c["default"].createElement(f["default"],a({data:e,templateKey:"body"},this.props.templateProps))}}]),t}(c["default"].Component);d.propTypes={cssClasses:c["default"].PropTypes.shape({time:c["default"].PropTypes.string}),hitsPerPage:c["default"].PropTypes.number,nbHits:c["default"].PropTypes.number,nbPages:c["default"].PropTypes.number,page:c["default"].PropTypes.number,processingTimeMS:c["default"].PropTypes.number,query:c["default"].PropTypes.string,templateProps:c["default"].PropTypes.object.isRequired},t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.attributeName,o=e.label,i=e.values,s=void 0===i?{on:!0,off:void 0}:i,l=e.templates,p=void 0===l?_["default"]:l,d=e.cssClasses,m=void 0===d?{}:d,g=e.transformData,b=e.autoHideContainer,C=void 0===b?!0:b,w=f["default"].getContainerNode(t),R=(0,y["default"])(n(394));if(C===!0&&(R=(0,v["default"])(R)),!t||!r||!o)throw new Error(P);var E=void 0!==s.off;return{getConfiguration:function(){return{facets:[r]}},init:function(e){var t=e.state,n=e.helper;if(void 0!==s.off){var o=t.isFacetRefined(r,s.on);o||n.addFacetRefinement(r,s.off)}},toggleRefinement:function(e,t){var n=s.on,o=s.off;t?(e.removeFacetRefinement(r,n),E&&e.addFacetRefinement(r,o)):(E&&e.removeFacetRefinement(r,o),e.addFacetRefinement(r,n)),e.search()},render:function(e){var t=e.helper,n=e.results,i=e.templatesConfig,l=e.state,d=e.createURL,v=t.state.isFacetRefined(r,s.on),y=(0,a["default"])(n.getFacetValues(r),{name:v.toString()}),b=0===n.nbHits,P=f["default"].prepareTemplateProps({transformData:g,defaultTemplates:_["default"],templatesConfig:i,templates:p}),C={name:o,isRefined:v,count:y&&y.count||null},E={root:(0,h["default"])(x(null),m.root),header:(0,h["default"])(x("header"),m.header),body:(0,h["default"])(x("body"),m.body),footer:(0,h["default"])(x("footer"),m.footer),list:(0,h["default"])(x("list"),m.list),item:(0,h["default"])(x("item"),m.item),active:(0,h["default"])(x("item","active"),m.active),label:(0,h["default"])(x("label"),m.label),checkbox:(0,h["default"])(x("checkbox"),m.checkbox),count:(0,h["default"])(x("count"),m.count)},T=this.toggleRefinement.bind(this,t,v);c["default"].render(u["default"].createElement(R,{createURL:function(){return d(l.toggleRefinement(r,C.isRefined))},cssClasses:E,facetValues:[C],shouldAutoHideContainer:b,templateProps:P,toggleRefinement:T}),w)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(128),a=r(i),s=n(218),u=r(s),l=n(371),c=r(l),p=n(373),f=r(p),d=n(377),h=r(d),m=n(378),v=r(m),g=n(379),y=r(g),b=n(437),_=r(b),x=f["default"].bemHelper("ais-toggle"),P="Usage:\ntoggle({\n container,\n attributeName,\n label,\n [ userValues={on: true, off: undefined} ],\n [ cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count} ],\n [ templates.{header,item,footer} ],\n [ transformData ],\n [ autoHideContainer=true ]\n})";t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>\n</label>',footer:""},e.exports=t["default"]}])}); //# sourceMappingURL=instantsearch.min.js.map
(function ($) { /** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { for (var base in settings.tableDrag) { $('#' + base, context).once('tabledrag', function () { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]); }); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (var group in tableSettings) { for (var n in tableSettings[group]) { if (tableSettings[group][n].relationship == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .click(function () { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { self.hideColumns(); } else { self.showColumns(); } return false; }) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function (event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function (event) { return self.dropRow(event, self); }); }; /** * Initialize columns containing form elements to be hidden by default, * according to the settings for this tableDrag instance. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' cookie. */ Drupal.tableDrag.prototype.initColumns = function () { for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d].target + ':first', this.table); if (field.length && this.tableSettings[group][d].hidden) { var hidden = this.tableSettings[group][d].hidden; var cell = field.closest('td'); break; } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function () { // Get the columnIndex and adjust for any colspans in this row. var index = columnIndex; var cells = $(this).children(); cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }); } } // Now hide cells and reduce colspans unless cookie indicates previous choice. // Set a cookie if it is not already present. if ($.cookie('Drupal.tableDrag.showWeight') === null) { $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); this.hideColumns(); } // Check cookie value and show/hide weight columns accordingly. else { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { this.showColumns(); } else { this.hideColumns(); } } }; /** * Hide the columns containing weight/parent form elements. * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { // Hide weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none'); // Show TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', ''); // Reduce the colspan of any effected multi-span columns. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'hide'); }; /** * Show the columns containing weight/parent form elements * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { // Show weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', ''); // Hide TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 1, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'show'); }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $('.' + group, row); for (var delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).length) { $('td:first .indentation:last', item).after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).length, self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function () { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function () { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function (event) { // Create a new dragObject recording the event information. self.dragObject = {}; self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function () { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function () { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function (event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).length) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will suppress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function (event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (var n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function (event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Given a target element and a mouse event, get the mouse offset from that * element. To do this we need the element's position and the mouse position. */ Drupal.tableDrag.prototype.getMouseOffset = function (target, event) { var docPos = $(target).offset(); var mousePos = this.mouseCoords(event); return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top }; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var indentDiff = 0; var rowY = $(row).offset().top; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight == 0) { var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { var rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (var n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row == this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as its own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).length == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).length == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $('option', targetElement).each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function () { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0; $(targetClass, siblings).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table) .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $('.indentation', tableRow).length; this.changed = false; this.table = $(tableRow).closest('table').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function (indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { Drupal.detachBehaviors(this.group, Drupal.settings, 'move'); $(row)[position](this.group); Drupal.attachBehaviors(this.group, Drupal.settings); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).length : 0; // Maximum indentation: if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return { 'min': minIndent, 'max': maxIndent }; }; /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed-in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length; } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>'; }; })(jQuery);
// This code was written by Tyler Akins and has been placed in the // public domain. It would be nice if you left this header intact. // Base64 code from Tyler Akins -- http://rumkin.com var Base64 = (function () { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var obj = { /** * Encodes a string in base64 * @param {String} input The string to encode in base64. */ encode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } while (i < input.length); return output; }, /** * Decodes a base64 string. * @param {String} input The string to decode. */ decode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } while (i < input.length); return output; } }; return obj; })(); /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ /* Some functions and variables have been stripped for use with Strophe */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * 8));} function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * 8));} function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));} function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));} /* * Calculate the SHA-1 of an array of big-endian words, and a bit length */ function core_sha1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = new Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; var i, j, t, olda, oldb, oldc, oldd, olde; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; olde = e; for (j = 0; j < 80; j++) { if (j < 16) { w[j] = x[i + j]; } else { w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); } t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return [a, b, c, d, e]; } /* * Perform the appropriate triplet combination function for the current * iteration */ function sha1_ft(t, b, c, d) { if (t < 20) { return (b & c) | ((~b) & d); } if (t < 40) { return b ^ c ^ d; } if (t < 60) { return (b & c) | (b & d) | (c & d); } return b ^ c ^ d; } /* * Determine the appropriate additive constant for the current iteration */ function sha1_kt(t) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } /* * Calculate the HMAC-SHA1 of a key and some data */ function core_hmac_sha1(key, data) { var bkey = str2binb(key); if (bkey.length > 16) { bkey = core_sha1(bkey, key.length * 8); } var ipad = new Array(16), opad = new Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8); return core_sha1(opad.concat(hash), 512 + 160); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert an 8-bit or 16-bit string to an array of big-endian words * In 8-bit function, characters >255 have their hi-byte silently ignored. */ function str2binb(str) { var bin = []; var mask = 255; for (var i = 0; i < str.length * 8; i += 8) { bin[i>>5] |= (str.charCodeAt(i / 8) & mask) << (24 - i%32); } return bin; } /* * Convert an array of big-endian words to a string */ function binb2str(bin) { var str = ""; var mask = 255; for (var i = 0; i < bin.length * 32; i += 8) { str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask); } return str; } /* * Convert an array of big-endian words to a base-64 string */ function binb2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; var triplet, j; for (var i = 0; i < binarray.length * 4; i += 3) { triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF); for (j = 0; j < 4; j++) { if (i * 8 + j * 6 > binarray.length * 32) { str += "="; } else { str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } } return str; } /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Everything that isn't used by Strophe has been stripped here! */ var MD5 = (function () { /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ var safe_add = function (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; /* * Bitwise rotate a 32-bit number to the left. */ var bit_rol = function (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); }; /* * Convert a string to an array of little-endian words */ var str2binl = function (str) { var bin = []; for(var i = 0; i < str.length * 8; i += 8) { bin[i>>5] |= (str.charCodeAt(i / 8) & 255) << (i%32); } return bin; }; /* * Convert an array of little-endian words to a string */ var binl2str = function (bin) { var str = ""; for(var i = 0; i < bin.length * 32; i += 8) { str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & 255); } return str; }; /* * Convert an array of little-endian words to a hex string. */ var binl2hex = function (binarray) { var hex_tab = "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; }; /* * These functions implement the four basic operations the algorithm uses. */ var md5_cmn = function (q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b); }; var md5_ff = function (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); }; var md5_gg = function (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); }; var md5_hh = function (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); }; var md5_ii = function (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); }; /* * Calculate the MD5 of an array of little-endian words, and a bit length */ var core_md5 = function (x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var olda, oldb, oldc, oldd; for (var i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; }; var obj = { /* * These are the functions you'll usually want to call. * They take string arguments and return either hex or base-64 encoded * strings. */ hexdigest: function (s) { return binl2hex(core_md5(str2binl(s), s.length * 8)); }, hash: function (s) { return binl2str(core_md5(str2binl(s), s.length * 8)); } }; return obj; })(); /* This program is distributed under the terms of the MIT license. Please see the LICENSE file for details. Copyright 2006-2008, OGG, LLC */ /* jshint undef: true, unused: true:, noarg: true, latedef: true */ /*global document, window, setTimeout, clearTimeout, console, ActiveXObject, Base64, MD5, DOMParser */ // from sha1.js /*global core_hmac_sha1, binb2str, str_hmac_sha1, str_sha1, b64_hmac_sha1*/ /** File: strophe.js * A JavaScript library for XMPP BOSH/XMPP over Websocket. * * This is the JavaScript version of the Strophe library. Since JavaScript * had no facilities for persistent TCP connections, this library uses * Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate * a persistent, stateful, two-way connection to an XMPP server. More * information on BOSH can be found in XEP 124. * * This version of Strophe also works with WebSockets. * For more information on XMPP-over WebSocket see this RFC draft: * http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00 */ /** PrivateFunction: Function.prototype.bind * Bind a function to an instance. * * This Function object extension method creates a bound method similar * to those in Python. This means that the 'this' object will point * to the instance you want. See * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and * <a href='http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/'>Bound Functions and Function Imports in JavaScript</a> * for a complete explanation. * * This extension already exists in some browsers (namely, Firefox 3), but * we provide it to support those that don't. * * Parameters: * (Object) obj - The object that will become 'this' in the bound function. * (Object) argN - An option argument that will be prepended to the * arguments given for the function call * * Returns: * The bound function. */ if (!Function.prototype.bind) { Function.prototype.bind = function (obj /*, arg1, arg2, ... */) { var func = this; var _slice = Array.prototype.slice; var _concat = Array.prototype.concat; var _args = _slice.call(arguments, 1); return function () { return func.apply(obj ? obj : this, _concat.call(_args, _slice.call(arguments, 0))); }; }; } /** PrivateFunction: Array.prototype.indexOf * Return the index of an object in an array. * * This function is not supplied by some JavaScript implementations, so * we provide it if it is missing. This code is from: * http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf * * Parameters: * (Object) elt - The object to look for. * (Integer) from - The index from which to start looking. (optional). * * Returns: * The index of elt in the array or -1 if not found. */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) { from += len; } for (; from < len; from++) { if (from in this && this[from] === elt) { return from; } } return -1; }; } /* All of the Strophe globals are defined in this special function below so * that references to the globals become closures. This will ensure that * on page reload, these references will still be available to callbacks * that are still executing. */ (function (callback) { var Strophe; /** Function: $build * Create a Strophe.Builder. * This is an alias for 'new Strophe.Builder(name, attrs)'. * * Parameters: * (String) name - The root element name. * (Object) attrs - The attributes for the root element in object notation. * * Returns: * A new Strophe.Builder object. */ function $build(name, attrs) { return new Strophe.Builder(name, attrs); } /** Function: $msg * Create a Strophe.Builder with a <message/> element as the root. * * Parmaeters: * (Object) attrs - The <message/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $msg(attrs) { return new Strophe.Builder("message", attrs); } /** Function: $iq * Create a Strophe.Builder with an <iq/> element as the root. * * Parameters: * (Object) attrs - The <iq/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $iq(attrs) { return new Strophe.Builder("iq", attrs); } /** Function: $pres * Create a Strophe.Builder with a <presence/> element as the root. * * Parameters: * (Object) attrs - The <presence/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $pres(attrs) { return new Strophe.Builder("presence", attrs); } /** Class: Strophe * An object container for all Strophe library functions. * * This class is just a container for all the objects and constants * used in the library. It is not meant to be instantiated, but to * provide a namespace for library objects, constants, and functions. */ Strophe = { /** Constant: VERSION * The version of the Strophe library. Unreleased builds will have * a version of head-HASH where HASH is a partial revision. */ VERSION: "1.1.3", /** Constants: XMPP Namespace Constants * Common namespace constants from the XMPP RFCs and XEPs. * * NS.HTTPBIND - HTTP BIND namespace from XEP 124. * NS.BOSH - BOSH namespace from XEP 206. * NS.CLIENT - Main XMPP client namespace. * NS.AUTH - Legacy authentication namespace. * NS.ROSTER - Roster operations namespace. * NS.PROFILE - Profile namespace. * NS.DISCO_INFO - Service discovery info namespace from XEP 30. * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30. * NS.MUC - Multi-User Chat namespace from XEP 45. * NS.SASL - XMPP SASL namespace from RFC 3920. * NS.STREAM - XMPP Streams namespace from RFC 3920. * NS.BIND - XMPP Binding namespace from RFC 3920. * NS.SESSION - XMPP Session namespace from RFC 3920. * NS.XHTML_IM - XHTML-IM namespace from XEP 71. * NS.XHTML - XHTML body namespace from XEP 71. */ NS: { HTTPBIND: "http://jabber.org/protocol/httpbind", BOSH: "urn:xmpp:xbosh", CLIENT: "jabber:client", AUTH: "jabber:iq:auth", ROSTER: "jabber:iq:roster", PROFILE: "jabber:iq:profile", DISCO_INFO: "http://jabber.org/protocol/disco#info", DISCO_ITEMS: "http://jabber.org/protocol/disco#items", MUC: "http://jabber.org/protocol/muc", SASL: "urn:ietf:params:xml:ns:xmpp-sasl", STREAM: "http://etherx.jabber.org/streams", BIND: "urn:ietf:params:xml:ns:xmpp-bind", SESSION: "urn:ietf:params:xml:ns:xmpp-session", VERSION: "jabber:iq:version", STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas", XHTML_IM: "http://jabber.org/protocol/xhtml-im", XHTML: "http://www.w3.org/1999/xhtml" }, /** Constants: XHTML_IM Namespace * contains allowed tags, tag attributes, and css properties. * Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset. * See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended * allowed tags and their attributes. */ XHTML: { tags: ['a','blockquote','br','cite','em','img','li','ol','p','span','strong','ul','body'], attributes: { 'a': ['href'], 'blockquote': ['style'], 'br': [], 'cite': ['style'], 'em': [], 'img': ['src', 'alt', 'style', 'height', 'width'], 'li': ['style'], 'ol': ['style'], 'p': ['style'], 'span': ['style'], 'strong': [], 'ul': ['style'], 'body': [] }, css: ['background-color','color','font-family','font-size','font-style','font-weight','margin-left','margin-right','text-align','text-decoration'], validTag: function(tag) { for(var i = 0; i < Strophe.XHTML.tags.length; i++) { if(tag == Strophe.XHTML.tags[i]) { return true; } } return false; }, validAttribute: function(tag, attribute) { if(typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) { for(var i = 0; i < Strophe.XHTML.attributes[tag].length; i++) { if(attribute == Strophe.XHTML.attributes[tag][i]) { return true; } } } return false; }, validCSS: function(style) { for(var i = 0; i < Strophe.XHTML.css.length; i++) { if(style == Strophe.XHTML.css[i]) { return true; } } return false; } }, /** Constants: Connection Status Constants * Connection status constants for use by the connection handler * callback. * * Status.ERROR - An error has occurred * Status.CONNECTING - The connection is currently being made * Status.CONNFAIL - The connection attempt failed * Status.AUTHENTICATING - The connection is authenticating * Status.AUTHFAIL - The authentication attempt failed * Status.CONNECTED - The connection has succeeded * Status.DISCONNECTED - The connection has been terminated * Status.DISCONNECTING - The connection is currently being terminated * Status.ATTACHED - The connection has been attached */ Status: { ERROR: 0, CONNECTING: 1, CONNFAIL: 2, AUTHENTICATING: 3, AUTHFAIL: 4, CONNECTED: 5, DISCONNECTED: 6, DISCONNECTING: 7, ATTACHED: 8 }, /** Constants: Log Level Constants * Logging level indicators. * * LogLevel.DEBUG - Debug output * LogLevel.INFO - Informational output * LogLevel.WARN - Warnings * LogLevel.ERROR - Errors * LogLevel.FATAL - Fatal errors */ LogLevel: { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, FATAL: 4 }, /** PrivateConstants: DOM Element Type Constants * DOM element types. * * ElementType.NORMAL - Normal element. * ElementType.TEXT - Text data element. * ElementType.FRAGMENT - XHTML fragment element. */ ElementType: { NORMAL: 1, TEXT: 3, CDATA: 4, FRAGMENT: 11 }, /** PrivateConstants: Timeout Values * Timeout values for error states. These values are in seconds. * These should not be changed unless you know exactly what you are * doing. * * TIMEOUT - Timeout multiplier. A waiting request will be considered * failed after Math.floor(TIMEOUT * wait) seconds have elapsed. * This defaults to 1.1, and with default wait, 66 seconds. * SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where * Strophe can detect early failure, it will consider the request * failed if it doesn't return after * Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed. * This defaults to 0.1, and with default wait, 6 seconds. */ TIMEOUT: 1.1, SECONDARY_TIMEOUT: 0.1, /** Function: addNamespace * This function is used to extend the current namespaces in * Strophe.NS. It takes a key and a value with the key being the * name of the new namespace, with its actual value. * For example: * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub"); * * Parameters: * (String) name - The name under which the namespace will be * referenced under Strophe.NS * (String) value - The actual namespace. */ addNamespace: function (name, value) { Strophe.NS[name] = value; }, /** Function: forEachChild * Map a function over some or all child elements of a given element. * * This is a small convenience function for mapping a function over * some or all of the children of an element. If elemName is null, all * children will be passed to the function, otherwise only children * whose tag names match elemName will be passed. * * Parameters: * (XMLElement) elem - The element to operate on. * (String) elemName - The child element tag name filter. * (Function) func - The function to apply to each child. This * function should take a single argument, a DOM element. */ forEachChild: function (elem, elemName, func) { var i, childNode; for (i = 0; i < elem.childNodes.length; i++) { childNode = elem.childNodes[i]; if (childNode.nodeType == Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) { func(childNode); } } }, /** Function: isTagEqual * Compare an element's tag name with a string. * * This function is case insensitive. * * Parameters: * (XMLElement) el - A DOM element. * (String) name - The element name. * * Returns: * true if the element's tag name matches _el_, and false * otherwise. */ isTagEqual: function (el, name) { return el.tagName.toLowerCase() == name.toLowerCase(); }, /** PrivateVariable: _xmlGenerator * _Private_ variable that caches a DOM document to * generate elements. */ _xmlGenerator: null, /** PrivateFunction: _makeGenerator * _Private_ function that creates a dummy XML DOM document to serve as * an element and text node generator. */ _makeGenerator: function () { var doc; // IE9 does implement createDocument(); however, using it will cause the browser to leak memory on page unload. // Here, we test for presence of createDocument() plus IE's proprietary documentMode attribute, which would be // less than 10 in the case of IE9 and below. if (document.implementation.createDocument === undefined || document.implementation.createDocument && document.documentMode && document.documentMode < 10) { doc = this._getIEXmlDom(); doc.appendChild(doc.createElement('strophe')); } else { doc = document.implementation .createDocument('jabber:client', 'strophe', null); } return doc; }, /** Function: xmlGenerator * Get the DOM document to generate elements. * * Returns: * The currently used DOM document. */ xmlGenerator: function () { if (!Strophe._xmlGenerator) { Strophe._xmlGenerator = Strophe._makeGenerator(); } return Strophe._xmlGenerator; }, /** PrivateFunction: _getIEXmlDom * Gets IE xml doc object * * Returns: * A Microsoft XML DOM Object * See Also: * http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx */ _getIEXmlDom : function() { var doc = null; var docStrings = [ "Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM" ]; for (var d = 0; d < docStrings.length; d++) { if (doc === null) { try { doc = new ActiveXObject(docStrings[d]); } catch (e) { doc = null; } } else { break; } } return doc; }, /** Function: xmlElement * Create an XML DOM element. * * This function creates an XML DOM element correctly across all * implementations. Note that these are not HTML DOM elements, which * aren't appropriate for XMPP stanzas. * * Parameters: * (String) name - The name for the element. * (Array|Object) attrs - An optional array or object containing * key/value pairs to use as element attributes. The object should * be in the format {'key': 'value'} or {key: 'value'}. The array * should have the format [['key1', 'value1'], ['key2', 'value2']]. * (String) text - The text child data for the element. * * Returns: * A new XML DOM element. */ xmlElement: function (name) { if (!name) { return null; } var node = Strophe.xmlGenerator().createElement(name); // FIXME: this should throw errors if args are the wrong type or // there are more than two optional args var a, i, k; for (a = 1; a < arguments.length; a++) { if (!arguments[a]) { continue; } if (typeof(arguments[a]) == "string" || typeof(arguments[a]) == "number") { node.appendChild(Strophe.xmlTextNode(arguments[a])); } else if (typeof(arguments[a]) == "object" && typeof(arguments[a].sort) == "function") { for (i = 0; i < arguments[a].length; i++) { if (typeof(arguments[a][i]) == "object" && typeof(arguments[a][i].sort) == "function") { node.setAttribute(arguments[a][i][0], arguments[a][i][1]); } } } else if (typeof(arguments[a]) == "object") { for (k in arguments[a]) { if (arguments[a].hasOwnProperty(k)) { node.setAttribute(k, arguments[a][k]); } } } } return node; }, /* Function: xmlescape * Excapes invalid xml characters. * * Parameters: * (String) text - text to escape. * * Returns: * Escaped text. */ xmlescape: function(text) { text = text.replace(/\&/g, "&amp;"); text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); text = text.replace(/'/g, "&apos;"); text = text.replace(/"/g, "&quot;"); return text; }, /** Function: xmlTextNode * Creates an XML DOM text node. * * Provides a cross implementation version of document.createTextNode. * * Parameters: * (String) text - The content of the text node. * * Returns: * A new XML DOM text node. */ xmlTextNode: function (text) { return Strophe.xmlGenerator().createTextNode(text); }, /** Function: xmlHtmlNode * Creates an XML DOM html node. * * Parameters: * (String) html - The content of the html node. * * Returns: * A new XML DOM text node. */ xmlHtmlNode: function (html) { var node; //ensure text is escaped if (window.DOMParser) { var parser = new DOMParser(); node = parser.parseFromString(html, "text/xml"); } else { node = new ActiveXObject("Microsoft.XMLDOM"); node.async="false"; node.loadXML(html); } return node; }, /** Function: getText * Get the concatenation of all text children of an element. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * A String with the concatenated text of all text element children. */ getText: function (elem) { if (!elem) { return null; } var str = ""; if (elem.childNodes.length === 0 && elem.nodeType == Strophe.ElementType.TEXT) { str += elem.nodeValue; } for (var i = 0; i < elem.childNodes.length; i++) { if (elem.childNodes[i].nodeType == Strophe.ElementType.TEXT) { str += elem.childNodes[i].nodeValue; } } return Strophe.xmlescape(str); }, /** Function: copyElement * Copy an XML DOM element. * * This function copies a DOM element and all its descendants and returns * the new copy. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * A new, copied DOM element tree. */ copyElement: function (elem) { var i, el; if (elem.nodeType == Strophe.ElementType.NORMAL) { el = Strophe.xmlElement(elem.tagName); for (i = 0; i < elem.attributes.length; i++) { el.setAttribute(elem.attributes[i].nodeName.toLowerCase(), elem.attributes[i].value); } for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.copyElement(elem.childNodes[i])); } } else if (elem.nodeType == Strophe.ElementType.TEXT) { el = Strophe.xmlGenerator().createTextNode(elem.nodeValue); } return el; }, /** Function: createHtml * Copy an HTML DOM element into an XML DOM. * * This function copies a DOM element and all its descendants and returns * the new copy. * * Parameters: * (HTMLElement) elem - A DOM element. * * Returns: * A new, copied DOM element tree. */ createHtml: function (elem) { var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue; if (elem.nodeType == Strophe.ElementType.NORMAL) { tag = elem.nodeName.toLowerCase(); if(Strophe.XHTML.validTag(tag)) { try { el = Strophe.xmlElement(tag); for(i = 0; i < Strophe.XHTML.attributes[tag].length; i++) { attribute = Strophe.XHTML.attributes[tag][i]; value = elem.getAttribute(attribute); if(typeof value == 'undefined' || value === null || value === '' || value === false || value === 0) { continue; } if(attribute == 'style' && typeof value == 'object') { if(typeof value.cssText != 'undefined') { value = value.cssText; // we're dealing with IE, need to get CSS out } } // filter out invalid css styles if(attribute == 'style') { css = []; cssAttrs = value.split(';'); for(j = 0; j < cssAttrs.length; j++) { attr = cssAttrs[j].split(':'); cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase(); if(Strophe.XHTML.validCSS(cssName)) { cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, ""); css.push(cssName + ': ' + cssValue); } } if(css.length > 0) { value = css.join('; '); el.setAttribute(attribute, value); } } else { el.setAttribute(attribute, value); } } for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } catch(e) { // invalid elements el = Strophe.xmlTextNode(''); } } else { el = Strophe.xmlGenerator().createDocumentFragment(); for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } } else if (elem.nodeType == Strophe.ElementType.FRAGMENT) { el = Strophe.xmlGenerator().createDocumentFragment(); for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } else if (elem.nodeType == Strophe.ElementType.TEXT) { el = Strophe.xmlTextNode(elem.nodeValue); } return el; }, /** Function: escapeNode * Escape the node part (also called local part) of a JID. * * Parameters: * (String) node - A node (or local part). * * Returns: * An escaped node (or local part). */ escapeNode: function (node) { return node.replace(/^\s+|\s+$/g, '') .replace(/\\/g, "\\5c") .replace(/ /g, "\\20") .replace(/\"/g, "\\22") .replace(/\&/g, "\\26") .replace(/\'/g, "\\27") .replace(/\//g, "\\2f") .replace(/:/g, "\\3a") .replace(/</g, "\\3c") .replace(/>/g, "\\3e") .replace(/@/g, "\\40"); }, /** Function: unescapeNode * Unescape a node part (also called local part) of a JID. * * Parameters: * (String) node - A node (or local part). * * Returns: * An unescaped node (or local part). */ unescapeNode: function (node) { return node.replace(/\\20/g, " ") .replace(/\\22/g, '"') .replace(/\\26/g, "&") .replace(/\\27/g, "'") .replace(/\\2f/g, "/") .replace(/\\3a/g, ":") .replace(/\\3c/g, "<") .replace(/\\3e/g, ">") .replace(/\\40/g, "@") .replace(/\\5c/g, "\\"); }, /** Function: getNodeFromJid * Get the node portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the node. */ getNodeFromJid: function (jid) { if (jid.indexOf("@") < 0) { return null; } return jid.split("@")[0]; }, /** Function: getDomainFromJid * Get the domain portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the domain. */ getDomainFromJid: function (jid) { var bare = Strophe.getBareJidFromJid(jid); if (bare.indexOf("@") < 0) { return bare; } else { var parts = bare.split("@"); parts.splice(0, 1); return parts.join('@'); } }, /** Function: getResourceFromJid * Get the resource portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the resource. */ getResourceFromJid: function (jid) { var s = jid.split("/"); if (s.length < 2) { return null; } s.splice(0, 1); return s.join('/'); }, /** Function: getBareJidFromJid * Get the bare JID from a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the bare JID. */ getBareJidFromJid: function (jid) { return jid ? jid.split("/")[0] : null; }, /** Function: log * User overrideable logging function. * * This function is called whenever the Strophe library calls any * of the logging functions. The default implementation of this * function does nothing. If client code wishes to handle the logging * messages, it should override this with * > Strophe.log = function (level, msg) { * > (user code here) * > }; * * Please note that data sent and received over the wire is logged * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput(). * * The different levels and their meanings are * * DEBUG - Messages useful for debugging purposes. * INFO - Informational messages. This is mostly information like * 'disconnect was called' or 'SASL auth succeeded'. * WARN - Warnings about potential problems. This is mostly used * to report transient connection errors like request timeouts. * ERROR - Some error occurred. * FATAL - A non-recoverable fatal error occurred. * * Parameters: * (Integer) level - The log level of the log message. This will * be one of the values in Strophe.LogLevel. * (String) msg - The log message. */ /* jshint ignore:start */ log: function (level, msg) { return; }, /* jshint ignore:end */ /** Function: debug * Log a message at the Strophe.LogLevel.DEBUG level. * * Parameters: * (String) msg - The log message. */ debug: function(msg) { this.log(this.LogLevel.DEBUG, msg); }, /** Function: info * Log a message at the Strophe.LogLevel.INFO level. * * Parameters: * (String) msg - The log message. */ info: function (msg) { this.log(this.LogLevel.INFO, msg); }, /** Function: warn * Log a message at the Strophe.LogLevel.WARN level. * * Parameters: * (String) msg - The log message. */ warn: function (msg) { this.log(this.LogLevel.WARN, msg); }, /** Function: error * Log a message at the Strophe.LogLevel.ERROR level. * * Parameters: * (String) msg - The log message. */ error: function (msg) { this.log(this.LogLevel.ERROR, msg); }, /** Function: fatal * Log a message at the Strophe.LogLevel.FATAL level. * * Parameters: * (String) msg - The log message. */ fatal: function (msg) { this.log(this.LogLevel.FATAL, msg); }, /** Function: serialize * Render a DOM element and all descendants to a String. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * The serialized element tree as a String. */ serialize: function (elem) { var result; if (!elem) { return null; } if (typeof(elem.tree) === "function") { elem = elem.tree(); } var nodeName = elem.nodeName; var i, child; if (elem.getAttribute("_realname")) { nodeName = elem.getAttribute("_realname"); } result = "<" + nodeName; for (i = 0; i < elem.attributes.length; i++) { if(elem.attributes[i].nodeName != "_realname") { result += " " + elem.attributes[i].nodeName.toLowerCase() + "='" + elem.attributes[i].value .replace(/&/g, "&amp;") .replace(/\'/g, "&apos;") .replace(/>/g, "&gt;") .replace(/</g, "&lt;") + "'"; } } if (elem.childNodes.length > 0) { result += ">"; for (i = 0; i < elem.childNodes.length; i++) { child = elem.childNodes[i]; switch( child.nodeType ){ case Strophe.ElementType.NORMAL: // normal element, so recurse result += Strophe.serialize(child); break; case Strophe.ElementType.TEXT: // text element to escape values result += Strophe.xmlescape(child.nodeValue); break; case Strophe.ElementType.CDATA: // cdata section so don't escape values result += "<![CDATA["+child.nodeValue+"]]>"; } } result += "</" + nodeName + ">"; } else { result += "/>"; } return result; }, /** PrivateVariable: _requestId * _Private_ variable that keeps track of the request ids for * connections. */ _requestId: 0, /** PrivateVariable: Strophe.connectionPlugins * _Private_ variable Used to store plugin names that need * initialization on Strophe.Connection construction. */ _connectionPlugins: {}, /** Function: addConnectionPlugin * Extends the Strophe.Connection object with the given plugin. * * Parameters: * (String) name - The name of the extension. * (Object) ptype - The plugin's prototype. */ addConnectionPlugin: function (name, ptype) { Strophe._connectionPlugins[name] = ptype; } }; /** Class: Strophe.Builder * XML DOM builder. * * This object provides an interface similar to JQuery but for building * DOM element easily and rapidly. All the functions except for toString() * and tree() return the object, so calls can be chained. Here's an * example using the $iq() builder helper. * > $iq({to: 'you', from: 'me', type: 'get', id: '1'}) * > .c('query', {xmlns: 'strophe:example'}) * > .c('example') * > .toString() * The above generates this XML fragment * > <iq to='you' from='me' type='get' id='1'> * > <query xmlns='strophe:example'> * > <example/> * > </query> * > </iq> * The corresponding DOM manipulations to get a similar fragment would be * a lot more tedious and probably involve several helper variables. * * Since adding children makes new operations operate on the child, up() * is provided to traverse up the tree. To add two children, do * > builder.c('child1', ...).up().c('child2', ...) * The next operation on the Builder will be relative to the second child. */ /** Constructor: Strophe.Builder * Create a Strophe.Builder object. * * The attributes should be passed in object notation. For example * > var b = new Builder('message', {to: 'you', from: 'me'}); * or * > var b = new Builder('messsage', {'xml:lang': 'en'}); * * Parameters: * (String) name - The name of the root element. * (Object) attrs - The attributes for the root element in object notation. * * Returns: * A new Strophe.Builder. */ Strophe.Builder = function (name, attrs) { // Set correct namespace for jabber:client elements if (name == "presence" || name == "message" || name == "iq") { if (attrs && !attrs.xmlns) { attrs.xmlns = Strophe.NS.CLIENT; } else if (!attrs) { attrs = {xmlns: Strophe.NS.CLIENT}; } } // Holds the tree being built. this.nodeTree = Strophe.xmlElement(name, attrs); // Points to the current operation node. this.node = this.nodeTree; }; Strophe.Builder.prototype = { /** Function: tree * Return the DOM tree. * * This function returns the current DOM tree as an element object. This * is suitable for passing to functions like Strophe.Connection.send(). * * Returns: * The DOM tree as a element object. */ tree: function () { return this.nodeTree; }, /** Function: toString * Serialize the DOM tree to a String. * * This function returns a string serialization of the current DOM * tree. It is often used internally to pass data to a * Strophe.Request object. * * Returns: * The serialized DOM tree in a String. */ toString: function () { return Strophe.serialize(this.nodeTree); }, /** Function: up * Make the current parent element the new current element. * * This function is often used after c() to traverse back up the tree. * For example, to add two children to the same element * > builder.c('child1', {}).up().c('child2', {}); * * Returns: * The Stophe.Builder object. */ up: function () { this.node = this.node.parentNode; return this; }, /** Function: attrs * Add or modify attributes of the current element. * * The attributes should be passed in object notation. This function * does not move the current element pointer. * * Parameters: * (Object) moreattrs - The attributes to add/modify in object notation. * * Returns: * The Strophe.Builder object. */ attrs: function (moreattrs) { for (var k in moreattrs) { if (moreattrs.hasOwnProperty(k)) { this.node.setAttribute(k, moreattrs[k]); } } return this; }, /** Function: c * Add a child to the current element and make it the new current * element. * * This function moves the current element pointer to the child, * unless text is provided. If you need to add another child, it * is necessary to use up() to go back to the parent in the tree. * * Parameters: * (String) name - The name of the child. * (Object) attrs - The attributes of the child in object notation. * (String) text - The text to add to the child. * * Returns: * The Strophe.Builder object. */ c: function (name, attrs, text) { var child = Strophe.xmlElement(name, attrs, text); this.node.appendChild(child); if (!text) { this.node = child; } return this; }, /** Function: cnode * Add a child to the current element and make it the new current * element. * * This function is the same as c() except that instead of using a * name and an attributes object to create the child it uses an * existing DOM element object. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * The Strophe.Builder object. */ cnode: function (elem) { var impNode; var xmlGen = Strophe.xmlGenerator(); try { impNode = (xmlGen.importNode !== undefined); } catch (e) { impNode = false; } var newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem); this.node.appendChild(newElem); this.node = newElem; return this; }, /** Function: t * Add a child text element. * * This *does not* make the child the new current element since there * are no children of text elements. * * Parameters: * (String) text - The text data to append to the current element. * * Returns: * The Strophe.Builder object. */ t: function (text) { var child = Strophe.xmlTextNode(text); this.node.appendChild(child); return this; }, /** Function: h * Replace current element contents with the HTML passed in. * * This *does not* make the child the new current element * * Parameters: * (String) html - The html to insert as contents of current element. * * Returns: * The Strophe.Builder object. */ h: function (html) { var fragment = document.createElement('body'); // force the browser to try and fix any invalid HTML tags fragment.innerHTML = html; // copy cleaned html into an xml dom var xhtml = Strophe.createHtml(fragment); while(xhtml.childNodes.length > 0) { this.node.appendChild(xhtml.childNodes[0]); } return this; } }; /** PrivateClass: Strophe.Handler * _Private_ helper class for managing stanza handlers. * * A Strophe.Handler encapsulates a user provided callback function to be * executed when matching stanzas are received by the connection. * Handlers can be either one-off or persistant depending on their * return value. Returning true will cause a Handler to remain active, and * returning false will remove the Handler. * * Users will not use Strophe.Handler objects directly, but instead they * will use Strophe.Connection.addHandler() and * Strophe.Connection.deleteHandler(). */ /** PrivateConstructor: Strophe.Handler * Create and initialize a new Strophe.Handler. * * Parameters: * (Function) handler - A function to be executed when the handler is run. * (String) ns - The namespace to match. * (String) name - The element name to match. * (String) type - The element type to match. * (String) id - The element id attribute to match. * (String) from - The element from attribute to match. * (Object) options - Handler options * * Returns: * A new Strophe.Handler object. */ Strophe.Handler = function (handler, ns, name, type, id, from, options) { this.handler = handler; this.ns = ns; this.name = name; this.type = type; this.id = id; this.options = options || {matchBare: false}; // default matchBare to false if undefined if (!this.options.matchBare) { this.options.matchBare = false; } if (this.options.matchBare) { this.from = from ? Strophe.getBareJidFromJid(from) : null; } else { this.from = from; } // whether the handler is a user handler or a system handler this.user = true; }; Strophe.Handler.prototype = { /** PrivateFunction: isMatch * Tests if a stanza matches the Strophe.Handler. * * Parameters: * (XMLElement) elem - The XML element to test. * * Returns: * true if the stanza matches and false otherwise. */ isMatch: function (elem) { var nsMatch; var from = null; if (this.options.matchBare) { from = Strophe.getBareJidFromJid(elem.getAttribute('from')); } else { from = elem.getAttribute('from'); } nsMatch = false; if (!this.ns) { nsMatch = true; } else { var that = this; Strophe.forEachChild(elem, null, function (elem) { if (elem.getAttribute("xmlns") == that.ns) { nsMatch = true; } }); nsMatch = nsMatch || elem.getAttribute("xmlns") == this.ns; } if (nsMatch && (!this.name || Strophe.isTagEqual(elem, this.name)) && (!this.type || elem.getAttribute("type") == this.type) && (!this.id || elem.getAttribute("id") == this.id) && (!this.from || from == this.from)) { return true; } return false; }, /** PrivateFunction: run * Run the callback on a matching stanza. * * Parameters: * (XMLElement) elem - The DOM element that triggered the * Strophe.Handler. * * Returns: * A boolean indicating if the handler should remain active. */ run: function (elem) { var result = null; try { result = this.handler(elem); } catch (e) { if (e.sourceURL) { Strophe.fatal("error: " + this.handler + " " + e.sourceURL + ":" + e.line + " - " + e.name + ": " + e.message); } else if (e.fileName) { if (typeof(console) != "undefined") { console.trace(); console.error(this.handler, " - error - ", e, e.message); } Strophe.fatal("error: " + this.handler + " " + e.fileName + ":" + e.lineNumber + " - " + e.name + ": " + e.message); } else { Strophe.fatal("error: " + e.message + "\n" + e.stack); } throw e; } return result; }, /** PrivateFunction: toString * Get a String representation of the Strophe.Handler object. * * Returns: * A String. */ toString: function () { return "{Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ")}"; } }; /** PrivateClass: Strophe.TimedHandler * _Private_ helper class for managing timed handlers. * * A Strophe.TimedHandler encapsulates a user provided callback that * should be called after a certain period of time or at regular * intervals. The return value of the callback determines whether the * Strophe.TimedHandler will continue to fire. * * Users will not use Strophe.TimedHandler objects directly, but instead * they will use Strophe.Connection.addTimedHandler() and * Strophe.Connection.deleteTimedHandler(). */ /** PrivateConstructor: Strophe.TimedHandler * Create and initialize a new Strophe.TimedHandler object. * * Parameters: * (Integer) period - The number of milliseconds to wait before the * handler is called. * (Function) handler - The callback to run when the handler fires. This * function should take no arguments. * * Returns: * A new Strophe.TimedHandler object. */ Strophe.TimedHandler = function (period, handler) { this.period = period; this.handler = handler; this.lastCalled = new Date().getTime(); this.user = true; }; Strophe.TimedHandler.prototype = { /** PrivateFunction: run * Run the callback for the Strophe.TimedHandler. * * Returns: * true if the Strophe.TimedHandler should be called again, and false * otherwise. */ run: function () { this.lastCalled = new Date().getTime(); return this.handler(); }, /** PrivateFunction: reset * Reset the last called time for the Strophe.TimedHandler. */ reset: function () { this.lastCalled = new Date().getTime(); }, /** PrivateFunction: toString * Get a string representation of the Strophe.TimedHandler object. * * Returns: * The string representation. */ toString: function () { return "{TimedHandler: " + this.handler + "(" + this.period +")}"; } }; /** Class: Strophe.Connection * XMPP Connection manager. * * This class is the main part of Strophe. It manages a BOSH connection * to an XMPP server and dispatches events to the user callbacks as * data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1 * and legacy authentication. * * After creating a Strophe.Connection object, the user will typically * call connect() with a user supplied callback to handle connection level * events like authentication failure, disconnection, or connection * complete. * * The user will also have several event handlers defined by using * addHandler() and addTimedHandler(). These will allow the user code to * respond to interesting stanzas or do something periodically with the * connection. These handlers will be active once authentication is * finished. * * To send data to the connection, use send(). */ /** Constructor: Strophe.Connection * Create and initialize a Strophe.Connection object. * * The transport-protocol for this connection will be chosen automatically * based on the given service parameter. URLs starting with "ws://" or * "wss://" will use WebSockets, URLs starting with "http://", "https://" * or without a protocol will use BOSH. * * To make Strophe connect to the current host you can leave out the protocol * and host part and just pass the path, e.g. * * > var conn = new Strophe.Connection("/http-bind/"); * * WebSocket options: * * If you want to connect to the current host with a WebSocket connection you * can tell Strophe to use WebSockets through a "protocol" attribute in the * optional options parameter. Valid values are "ws" for WebSocket and "wss" * for Secure WebSocket. * So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call * * > var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"}); * * Note that relative URLs _NOT_ starting with a "/" will also include the path * of the current site. * * Also because downgrading security is not permitted by browsers, when using * relative URLs both BOSH and WebSocket connections will use their secure * variants if the current connection to the site is also secure (https). * * BOSH options: * * by adding "sync" to the options, you can control if requests will * be made synchronously or not. The default behaviour is asynchronous. * If you want to make requests synchronous, make "sync" evaluate to true: * > var conn = new Strophe.Connection("/http-bind/", {sync: true}); * You can also toggle this on an already established connection: * > conn.options.sync = true; * * * Parameters: * (String) service - The BOSH or WebSocket service URL. * (Object) options - A hash of configuration options * * Returns: * A new Strophe.Connection object. */ Strophe.Connection = function (service, options) { // The service URL this.service = service; // Configuration options this.options = options || {}; var proto = this.options.protocol || ""; // Select protocal based on service or options if (service.indexOf("ws:") === 0 || service.indexOf("wss:") === 0 || proto.indexOf("ws") === 0) { this._proto = new Strophe.Websocket(this); } else { this._proto = new Strophe.Bosh(this); } /* The connected JID. */ this.jid = ""; /* the JIDs domain */ this.domain = null; /* stream:features */ this.features = null; // SASL this._sasl_data = {}; this.do_session = false; this.do_bind = false; // handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this._authentication = {}; this._idleTimeout = null; this._disconnectTimeout = null; this.do_authentication = true; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this.paused = false; this._data = []; this._uniqueId = 0; this._sasl_success_handler = null; this._sasl_failure_handler = null; this._sasl_challenge_handler = null; // Max retries before disconnecting this.maxRetries = 5; // setup onIdle callback every 1/10th of a second this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); // initialize plugins for (var k in Strophe._connectionPlugins) { if (Strophe._connectionPlugins.hasOwnProperty(k)) { var ptype = Strophe._connectionPlugins[k]; // jslint complaints about the below line, but this is fine var F = function () {}; // jshint ignore:line F.prototype = ptype; this[k] = new F(); this[k].init(this); } } }; Strophe.Connection.prototype = { /** Function: reset * Reset the connection. * * This function should be called after a connection is disconnected * before that connection is reused. */ reset: function () { this._proto._reset(); // SASL this.do_session = false; this.do_bind = false; // handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this._authentication = {}; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this._requests = []; this._uniqueId = 0; }, /** Function: pause * Pause the request manager. * * This will prevent Strophe from sending any more requests to the * server. This is very useful for temporarily pausing * BOSH-Connections while a lot of send() calls are happening quickly. * This causes Strophe to send the data in a single request, saving * many request trips. */ pause: function () { this.paused = true; }, /** Function: resume * Resume the request manager. * * This resumes after pause() has been called. */ resume: function () { this.paused = false; }, /** Function: getUniqueId * Generate a unique ID for use in <iq/> elements. * * All <iq/> stanzas are required to have unique id attributes. This * function makes creating these easy. Each connection instance has * a counter which starts from zero, and the value of this counter * plus a colon followed by the suffix becomes the unique id. If no * suffix is supplied, the counter is used as the unique id. * * Suffixes are used to make debugging easier when reading the stream * data, and their use is recommended. The counter resets to 0 for * every new connection for the same reason. For connections to the * same server that authenticate the same way, all the ids should be * the same, which makes it easy to see changes. This is useful for * automated testing as well. * * Parameters: * (String) suffix - A optional suffix to append to the id. * * Returns: * A unique string to be used for the id attribute. */ getUniqueId: function (suffix) { if (typeof(suffix) == "string" || typeof(suffix) == "number") { return ++this._uniqueId + ":" + suffix; } else { return ++this._uniqueId + ""; } }, /** Function: connect * Starts the connection process. * * As the connection process proceeds, the user supplied callback will * be triggered multiple times with status updates. The callback * should take two arguments - the status code and the error condition. * * The status code will be one of the values in the Strophe.Status * constants. The error condition will be one of the conditions * defined in RFC 3920 or the condition 'strophe-parsererror'. * * The Parameters _wait_, _hold_ and _route_ are optional and only relevant * for BOSH connections. Please see XEP 124 for a more detailed explanation * of the optional parameters. * * Parameters: * (String) jid - The user's JID. This may be a bare JID, * or a full JID. If a node is not supplied, SASL ANONYMOUS * authentication will be attempted. * (String) pass - The user's password. * (Function) callback - The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). * (String) route - The optional route value. */ connect: function (jid, pass, callback, wait, hold, route) { this.jid = jid; /** Variable: authzid * Authorization identity. */ this.authzid = Strophe.getBareJidFromJid(this.jid); /** Variable: authcid * Authentication identity (User name). */ this.authcid = Strophe.getNodeFromJid(this.jid); /** Variable: pass * Authentication identity (User password). */ this.pass = pass; /** Variable: servtype * Digest MD5 compatibility. */ this.servtype = "xmpp"; this.connect_callback = callback; this.disconnecting = false; this.connected = false; this.authenticated = false; this.errors = 0; // parse jid for domain this.domain = Strophe.getDomainFromJid(this.jid); this._changeConnectStatus(Strophe.Status.CONNECTING, null); this._proto._connect(wait, hold, route); }, /** Function: attach * Attach to an already created and authenticated BOSH session. * * This function is provided to allow Strophe to attach to BOSH * sessions which have been created externally, perhaps by a Web * application. This is often used to support auto-login type features * without putting user credentials into the page. * * Parameters: * (String) jid - The full JID that is bound by the session. * (String) sid - The SID of the BOSH session. * (String) rid - The current RID of the BOSH session. This RID * will be used by the next request. * (Function) callback The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * Other settings will require tweaks to the Strophe.TIMEOUT value. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). * (Integer) wind - The optional HTTBIND window value. This is the * allowed range of request ids that are valid. The default is 5. */ attach: function (jid, sid, rid, callback, wait, hold, wind) { this._proto._attach(jid, sid, rid, callback, wait, hold, wind); }, /** Function: xmlInput * User overrideable function that receives XML data coming into the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.xmlInput = function (elem) { * > (user code) * > }; * * Due to limitations of current Browsers' XML-Parsers the opening and closing * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here. * * BOSH-Connections will have all stanzas wrapped in a <body> tag. See * <Strophe.Bosh.strip> if you want to strip this tag. * * Parameters: * (XMLElement) elem - The XML data received by the connection. */ /* jshint unused:false */ xmlInput: function (elem) { return; }, /* jshint unused:true */ /** Function: xmlOutput * User overrideable function that receives XML data sent to the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.xmlOutput = function (elem) { * > (user code) * > }; * * Due to limitations of current Browsers' XML-Parsers the opening and closing * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here. * * BOSH-Connections will have all stanzas wrapped in a <body> tag. See * <Strophe.Bosh.strip> if you want to strip this tag. * * Parameters: * (XMLElement) elem - The XMLdata sent by the connection. */ /* jshint unused:false */ xmlOutput: function (elem) { return; }, /* jshint unused:true */ /** Function: rawInput * User overrideable function that receives raw data coming into the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.rawInput = function (data) { * > (user code) * > }; * * Parameters: * (String) data - The data received by the connection. */ /* jshint unused:false */ rawInput: function (data) { return; }, /* jshint unused:true */ /** Function: rawOutput * User overrideable function that receives raw data sent to the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.rawOutput = function (data) { * > (user code) * > }; * * Parameters: * (String) data - The data sent by the connection. */ /* jshint unused:false */ rawOutput: function (data) { return; }, /* jshint unused:true */ /** Function: send * Send a stanza. * * This function is called to push data onto the send queue to * go out over the wire. Whenever a request is sent to the BOSH * server, all pending data is sent and the queue is flushed. * * Parameters: * (XMLElement | * [XMLElement] | * Strophe.Builder) elem - The stanza to send. */ send: function (elem) { if (elem === null) { return ; } if (typeof(elem.sort) === "function") { for (var i = 0; i < elem.length; i++) { this._queueData(elem[i]); } } else if (typeof(elem.tree) === "function") { this._queueData(elem.tree()); } else { this._queueData(elem); } this._proto._send(); }, /** Function: flush * Immediately send any pending outgoing data. * * Normally send() queues outgoing data until the next idle period * (100ms), which optimizes network use in the common cases when * several send()s are called in succession. flush() can be used to * immediately send all pending data. */ flush: function () { // cancel the pending idle period and run the idle function // immediately clearTimeout(this._idleTimeout); this._onIdle(); }, /** Function: sendIQ * Helper function to send IQ stanzas. * * Parameters: * (XMLElement) elem - The stanza to send. * (Function) callback - The callback function for a successful request. * (Function) errback - The callback function for a failed or timed * out request. On timeout, the stanza will be null. * (Integer) timeout - The time specified in milliseconds for a * timeout to occur. * * Returns: * The id used to send the IQ. */ sendIQ: function(elem, callback, errback, timeout) { var timeoutHandler = null; var that = this; if (typeof(elem.tree) === "function") { elem = elem.tree(); } var id = elem.getAttribute('id'); // inject id if not found if (!id) { id = this.getUniqueId("sendIQ"); elem.setAttribute("id", id); } var handler = this.addHandler(function (stanza) { // remove timeout handler if there is one if (timeoutHandler) { that.deleteTimedHandler(timeoutHandler); } var iqtype = stanza.getAttribute('type'); if (iqtype == 'result') { if (callback) { callback(stanza); } } else if (iqtype == 'error') { if (errback) { errback(stanza); } } else { throw { name: "StropheError", message: "Got bad IQ type of " + iqtype }; } }, null, 'iq', null, id); // if timeout specified, setup timeout handler. if (timeout) { timeoutHandler = this.addTimedHandler(timeout, function () { // get rid of normal handler that.deleteHandler(handler); // call errback on timeout with null stanza if (errback) { errback(null); } return false; }); } this.send(elem); return id; }, /** PrivateFunction: _queueData * Queue outgoing data for later sending. Also ensures that the data * is a DOMElement. */ _queueData: function (element) { if (element === null || !element.tagName || !element.childNodes) { throw { name: "StropheError", message: "Cannot queue non-DOMElement." }; } this._data.push(element); }, /** PrivateFunction: _sendRestart * Send an xmpp:restart stanza. */ _sendRestart: function () { this._data.push("restart"); this._proto._sendRestart(); this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); }, /** Function: addTimedHandler * Add a timed handler to the connection. * * This function adds a timed handler. The provided handler will * be called every period milliseconds until it returns false, * the connection is terminated, or the handler is removed. Handlers * that wish to continue being invoked should return true. * * Because of method binding it is necessary to save the result of * this function if you wish to remove a handler with * deleteTimedHandler(). * * Note that user handlers are not active until authentication is * successful. * * Parameters: * (Integer) period - The period of the handler. * (Function) handler - The callback function. * * Returns: * A reference to the handler that can be used to remove it. */ addTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); this.addTimeds.push(thand); return thand; }, /** Function: deleteTimedHandler * Delete a timed handler for a connection. * * This function removes a timed handler from the connection. The * handRef parameter is *not* the function passed to addTimedHandler(), * but is the reference returned from addTimedHandler(). * * Parameters: * (Strophe.TimedHandler) handRef - The handler reference. */ deleteTimedHandler: function (handRef) { // this must be done in the Idle loop so that we don't change // the handlers during iteration this.removeTimeds.push(handRef); }, /** Function: addHandler * Add a stanza handler for the connection. * * This function adds a stanza handler to the connection. The * handler callback will be called for any stanza that matches * the parameters. Note that if multiple parameters are supplied, * they must all match for the handler to be invoked. * * The handler will receive the stanza that triggered it as its argument. * The handler should return true if it is to be invoked again; * returning false will remove the handler after it returns. * * As a convenience, the ns parameters applies to the top level element * and also any of its immediate children. This is primarily to make * matching /iq/query elements easy. * * The options argument contains handler matching flags that affect how * matches are determined. Currently the only flag is matchBare (a * boolean). When matchBare is true, the from parameter and the from * attribute on the stanza will be matched as bare JIDs instead of * full JIDs. To use this, pass {matchBare: true} as the value of * options. The default value for matchBare is false. * * The return value should be saved if you wish to remove the handler * with deleteHandler(). * * Parameters: * (Function) handler - The user callback. * (String) ns - The namespace to match. * (String) name - The stanza name to match. * (String) type - The stanza type attribute to match. * (String) id - The stanza id attribute to match. * (String) from - The stanza from attribute to match. * (String) options - The handler options * * Returns: * A reference to the handler that can be used to remove it. */ addHandler: function (handler, ns, name, type, id, from, options) { var hand = new Strophe.Handler(handler, ns, name, type, id, from, options); this.addHandlers.push(hand); return hand; }, /** Function: deleteHandler * Delete a stanza handler for a connection. * * This function removes a stanza handler from the connection. The * handRef parameter is *not* the function passed to addHandler(), * but is the reference returned from addHandler(). * * Parameters: * (Strophe.Handler) handRef - The handler reference. */ deleteHandler: function (handRef) { // this must be done in the Idle loop so that we don't change // the handlers during iteration this.removeHandlers.push(handRef); }, /** Function: disconnect * Start the graceful disconnection process. * * This function starts the disconnection process. This process starts * by sending unavailable presence and sending BOSH body of type * terminate. A timeout handler makes sure that disconnection happens * even if the BOSH server does not respond. * * The user supplied connection callback will be notified of the * progress as this process happens. * * Parameters: * (String) reason - The reason the disconnect is occuring. */ disconnect: function (reason) { this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason); Strophe.info("Disconnect was called because: " + reason); if (this.connected) { var pres = false; this.disconnecting = true; if (this.authenticated) { pres = $pres({ xmlns: Strophe.NS.CLIENT, type: 'unavailable' }); } // setup timeout handler this._disconnectTimeout = this._addSysTimedHandler( 3000, this._onDisconnectTimeout.bind(this)); this._proto._disconnect(pres); } }, /** PrivateFunction: _changeConnectStatus * _Private_ helper function that makes sure plugins and the user's * callback are notified of connection status changes. * * Parameters: * (Integer) status - the new connection status, one of the values * in Strophe.Status * (String) condition - the error condition or null */ _changeConnectStatus: function (status, condition) { // notify all plugins listening for status changes for (var k in Strophe._connectionPlugins) { if (Strophe._connectionPlugins.hasOwnProperty(k)) { var plugin = this[k]; if (plugin.statusChanged) { try { plugin.statusChanged(status, condition); } catch (err) { Strophe.error("" + k + " plugin caused an exception " + "changing status: " + err); } } } } // notify the user's callback if (this.connect_callback) { try { this.connect_callback(status, condition); } catch (e) { Strophe.error("User connection callback caused an " + "exception: " + e); } } }, /** PrivateFunction: _doDisconnect * _Private_ function to disconnect. * * This is the last piece of the disconnection logic. This resets the * connection and alerts the user's connection callback. */ _doDisconnect: function () { // Cancel Disconnect Timeout if (this._disconnectTimeout !== null) { this.deleteTimedHandler(this._disconnectTimeout); this._disconnectTimeout = null; } Strophe.info("_doDisconnect was called"); this._proto._doDisconnect(); this.authenticated = false; this.disconnecting = false; // delete handlers this.handlers = []; this.timedHandlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; // tell the parent we disconnected this._changeConnectStatus(Strophe.Status.DISCONNECTED, null); this.connected = false; }, /** PrivateFunction: _dataRecv * _Private_ handler to processes incoming data from the the connection. * * Except for _connect_cb handling the initial connection request, * this function handles the incoming data for all requests. This * function also fires stanza handlers that match each incoming * stanza. * * Parameters: * (Strophe.Request) req - The request that has data ready. * (string) req - The stanza a raw string (optiona). */ _dataRecv: function (req, raw) { Strophe.info("_dataRecv called"); var elem = this._proto._reqToData(req); if (elem === null) { return; } if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) { if (elem.nodeName === this._proto.strip && elem.childNodes.length) { this.xmlInput(elem.childNodes[0]); } else { this.xmlInput(elem); } } if (this.rawInput !== Strophe.Connection.prototype.rawInput) { if (raw) { this.rawInput(raw); } else { this.rawInput(Strophe.serialize(elem)); } } // remove handlers scheduled for deletion var i, hand; while (this.removeHandlers.length > 0) { hand = this.removeHandlers.pop(); i = this.handlers.indexOf(hand); if (i >= 0) { this.handlers.splice(i, 1); } } // add handlers scheduled for addition while (this.addHandlers.length > 0) { this.handlers.push(this.addHandlers.pop()); } // handle graceful disconnect if (this.disconnecting && this._proto._emptyQueue()) { this._doDisconnect(); return; } var typ = elem.getAttribute("type"); var cond, conflict; if (typ !== null && typ == "terminate") { // Don't process stanzas that come in after disconnect if (this.disconnecting) { return; } // an error occurred cond = elem.getAttribute("condition"); conflict = elem.getElementsByTagName("conflict"); if (cond !== null) { if (cond == "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._changeConnectStatus(Strophe.Status.CONNFAIL, cond); } else { this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown"); } this.disconnect('unknown stream-error'); return; } // send each incoming stanza through the handler chain var that = this; Strophe.forEachChild(elem, null, function (child) { var i, newList; // process handlers newList = that.handlers; that.handlers = []; for (i = 0; i < newList.length; i++) { var hand = newList[i]; // encapsulate 'handler.run' not to lose the whole handler list if // one of the handlers throws an exception try { if (hand.isMatch(child) && (that.authenticated || !hand.user)) { if (hand.run(child)) { that.handlers.push(hand); } } else { that.handlers.push(hand); } } catch(e) { // if the handler throws an exception, we consider it as false Strophe.warn('Removing Strophe handlers due to uncaught exception: ' + e.message); } } }); }, /** Attribute: mechanisms * SASL Mechanisms available for Conncection. */ mechanisms: {}, /** PrivateFunction: _connect_cb * _Private_ handler for initial connection request. * * This handler is used to process the initial connection request * response from the BOSH server. It is used to set up authentication * handlers and start the authentication process. * * SASL authentication will be attempted if available, otherwise * the code will fall back to legacy authentication. * * Parameters: * (Strophe.Request) req - The current request. * (Function) _callback - low level (xmpp) connect callback function. * Useful for plugins with their own xmpp connect callback (when their) * want to do something special). */ _connect_cb: function (req, _callback, raw) { Strophe.info("_connect_cb was called"); this.connected = true; var bodyWrap = this._proto._reqToData(req); if (!bodyWrap) { return; } if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) { if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) { this.xmlInput(bodyWrap.childNodes[0]); } else { this.xmlInput(bodyWrap); } } if (this.rawInput !== Strophe.Connection.prototype.rawInput) { if (raw) { this.rawInput(raw); } else { this.rawInput(Strophe.serialize(bodyWrap)); } } var conncheck = this._proto._connect_cb(bodyWrap); if (conncheck === Strophe.Status.CONNFAIL) { return; } this._authentication.sasl_scram_sha1 = false; this._authentication.sasl_plain = false; this._authentication.sasl_digest_md5 = false; this._authentication.sasl_anonymous = false; this._authentication.legacy_auth = false; // Check for the stream:features tag var hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0; if (!hasFeatures) { hasFeatures = bodyWrap.getElementsByTagName("features").length > 0; } var mechanisms = bodyWrap.getElementsByTagName("mechanism"); var matched = []; var i, mech, found_authentication = false; if (!hasFeatures) { this._proto._no_auth_received(_callback); return; } if (mechanisms.length > 0) { for (i = 0; i < mechanisms.length; i++) { mech = Strophe.getText(mechanisms[i]); if (this.mechanisms[mech]) matched.push(this.mechanisms[mech]); } } this._authentication.legacy_auth = bodyWrap.getElementsByTagName("auth").length > 0; found_authentication = this._authentication.legacy_auth || matched.length > 0; if (!found_authentication) { this._proto._no_auth_received(_callback); return; } if (this.do_authentication !== false) this.authenticate(matched); }, /** Function: authenticate * Set up authentication * * Contiunues the initial connection request by setting up authentication * handlers and start the authentication process. * * SASL authentication will be attempted if available, otherwise * the code will fall back to legacy authentication. * */ authenticate: function (matched) { var i; // Sorting matched mechanisms according to priority. for (i = 0; i < matched.length - 1; ++i) { var higher = i; for (var j = i + 1; j < matched.length; ++j) { if (matched[j].prototype.priority > matched[higher].prototype.priority) { higher = j; } } if (higher != i) { var swap = matched[i]; matched[i] = matched[higher]; matched[higher] = swap; } } // run each mechanism var mechanism_found = false; for (i = 0; i < matched.length; ++i) { if (!matched[i].test(this)) continue; this._sasl_success_handler = this._addSysHandler( this._sasl_success_cb.bind(this), null, "success", null, null); this._sasl_failure_handler = this._addSysHandler( this._sasl_failure_cb.bind(this), null, "failure", null, null); this._sasl_challenge_handler = this._addSysHandler( this._sasl_challenge_cb.bind(this), null, "challenge", null, null); this._sasl_mechanism = new matched[i](); this._sasl_mechanism.onStart(this); var request_auth_exchange = $build("auth", { xmlns: Strophe.NS.SASL, mechanism: this._sasl_mechanism.name }); if (this._sasl_mechanism.isClientFirst) { var response = this._sasl_mechanism.onChallenge(this, null); request_auth_exchange.t(Base64.encode(response)); } this.send(request_auth_exchange.tree()); mechanism_found = true; break; } if (!mechanism_found) { // if none of the mechanism worked if (Strophe.getNodeFromJid(this.jid) === null) { // we don't have a node, which is required for non-anonymous // client connections this._changeConnectStatus(Strophe.Status.CONNFAIL, 'x-strophe-bad-non-anon-jid'); this.disconnect('x-strophe-bad-non-anon-jid'); } else { // fall back to legacy authentication this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null); this._addSysHandler(this._auth1_cb.bind(this), null, null, null, "_auth_1"); this.send($iq({ type: "get", to: this.domain, id: "_auth_1" }).c("query", { xmlns: Strophe.NS.AUTH }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree()); } } }, _sasl_challenge_cb: function(elem) { var challenge = Base64.decode(Strophe.getText(elem)); var response = this._sasl_mechanism.onChallenge(this, challenge); var stanza = $build('response', { xmlns: Strophe.NS.SASL }); if (response !== "") { stanza.t(Base64.encode(response)); } this.send(stanza.tree()); return true; }, /** PrivateFunction: _auth1_cb * _Private_ handler for legacy authentication. * * This handler is called in response to the initial <iq type='get'/> * for legacy authentication. It builds an authentication <iq/> and * sends it, creating a handler (calling back to _auth2_cb()) to * handle the result * * Parameters: * (XMLElement) elem - The stanza that triggered the callback. * * Returns: * false to remove the handler. */ /* jshint unused:false */ _auth1_cb: function (elem) { // build plaintext auth iq var iq = $iq({type: "set", id: "_auth_2"}) .c('query', {xmlns: Strophe.NS.AUTH}) .c('username', {}).t(Strophe.getNodeFromJid(this.jid)) .up() .c('password').t(this.pass); if (!Strophe.getResourceFromJid(this.jid)) { // since the user has not supplied a resource, we pick // a default one here. unlike other auth methods, the server // cannot do this for us. this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe'; } iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid)); this._addSysHandler(this._auth2_cb.bind(this), null, null, null, "_auth_2"); this.send(iq.tree()); return false; }, /* jshint unused:true */ /** PrivateFunction: _sasl_success_cb * _Private_ handler for succesful SASL authentication. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_success_cb: function (elem) { if (this._sasl_data["server-signature"]) { var serverSignature; var success = Base64.decode(Strophe.getText(elem)); var attribMatch = /([a-z]+)=([^,]+)(,|$)/; var matches = success.match(attribMatch); if (matches[1] == "v") { serverSignature = matches[2]; } if (serverSignature != this._sasl_data["server-signature"]) { // remove old handlers this.deleteHandler(this._sasl_failure_handler); this._sasl_failure_handler = null; if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } this._sasl_data = {}; return this._sasl_failure_cb(null); } } Strophe.info("SASL authentication succeeded."); if(this._sasl_mechanism) this._sasl_mechanism.onSuccess(); // remove old handlers this.deleteHandler(this._sasl_failure_handler); this._sasl_failure_handler = null; if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } this._addSysHandler(this._sasl_auth1_cb.bind(this), null, "stream:features", null, null); // we must send an xmpp:restart now this._sendRestart(); return false; }, /** PrivateFunction: _sasl_auth1_cb * _Private_ handler to start stream binding. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_auth1_cb: function (elem) { // save stream:features for future usage this.features = elem; var i, child; for (i = 0; i < elem.childNodes.length; i++) { child = elem.childNodes[i]; if (child.nodeName == 'bind') { this.do_bind = true; } if (child.nodeName == 'session') { this.do_session = true; } } if (!this.do_bind) { this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } else { this._addSysHandler(this._sasl_bind_cb.bind(this), null, null, null, "_bind_auth_2"); var resource = Strophe.getResourceFromJid(this.jid); if (resource) { this.send($iq({type: "set", id: "_bind_auth_2"}) .c('bind', {xmlns: Strophe.NS.BIND}) .c('resource', {}).t(resource).tree()); } else { this.send($iq({type: "set", id: "_bind_auth_2"}) .c('bind', {xmlns: Strophe.NS.BIND}) .tree()); } } return false; }, /** PrivateFunction: _sasl_bind_cb * _Private_ handler for binding result and session start. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_bind_cb: function (elem) { if (elem.getAttribute("type") == "error") { Strophe.info("SASL binding failed."); var conflict = elem.getElementsByTagName("conflict"), condition; if (conflict.length > 0) { condition = 'conflict'; } this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition); return false; } // TODO - need to grab errors var bind = elem.getElementsByTagName("bind"); var jidNode; if (bind.length > 0) { // Grab jid jidNode = bind[0].getElementsByTagName("jid"); if (jidNode.length > 0) { this.jid = Strophe.getText(jidNode[0]); if (this.do_session) { this._addSysHandler(this._sasl_session_cb.bind(this), null, null, null, "_session_auth_2"); this.send($iq({type: "set", id: "_session_auth_2"}) .c('session', {xmlns: Strophe.NS.SESSION}) .tree()); } else { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } } } else { Strophe.info("SASL binding failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } }, /** PrivateFunction: _sasl_session_cb * _Private_ handler to finish successful SASL connection. * * This sets Connection.authenticated to true on success, which * starts the processing of user handlers. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_session_cb: function (elem) { if (elem.getAttribute("type") == "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } else if (elem.getAttribute("type") == "error") { Strophe.info("Session creation failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } return false; }, /** PrivateFunction: _sasl_failure_cb * _Private_ handler for SASL authentication failure. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ /* jshint unused:false */ _sasl_failure_cb: function (elem) { // delete unneeded handlers if (this._sasl_success_handler) { this.deleteHandler(this._sasl_success_handler); this._sasl_success_handler = null; } if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } if(this._sasl_mechanism) this._sasl_mechanism.onFailure(); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; }, /* jshint unused:true */ /** PrivateFunction: _auth2_cb * _Private_ handler to finish legacy authentication. * * This handler is called when the result from the jabber:iq:auth * <iq/> stanza is returned. * * Parameters: * (XMLElement) elem - The stanza that triggered the callback. * * Returns: * false to remove the handler. */ _auth2_cb: function (elem) { if (elem.getAttribute("type") == "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } else if (elem.getAttribute("type") == "error") { this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); this.disconnect('authentication failed'); } return false; }, /** PrivateFunction: _addSysTimedHandler * _Private_ function to add a system level timed handler. * * This function is used to add a Strophe.TimedHandler for the * library code. System timed handlers are allowed to run before * authentication is complete. * * Parameters: * (Integer) period - The period of the handler. * (Function) handler - The callback function. */ _addSysTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); thand.user = false; this.addTimeds.push(thand); return thand; }, /** PrivateFunction: _addSysHandler * _Private_ function to add a system level stanza handler. * * This function is used to add a Strophe.Handler for the * library code. System stanza handlers are allowed to run before * authentication is complete. * * Parameters: * (Function) handler - The callback function. * (String) ns - The namespace to match. * (String) name - The stanza name to match. * (String) type - The stanza type attribute to match. * (String) id - The stanza id attribute to match. */ _addSysHandler: function (handler, ns, name, type, id) { var hand = new Strophe.Handler(handler, ns, name, type, id); hand.user = false; this.addHandlers.push(hand); return hand; }, /** PrivateFunction: _onDisconnectTimeout * _Private_ timeout handler for handling non-graceful disconnection. * * If the graceful disconnect process does not complete within the * time allotted, this handler finishes the disconnect anyway. * * Returns: * false to remove the handler. */ _onDisconnectTimeout: function () { Strophe.info("_onDisconnectTimeout was called"); this._proto._onDisconnectTimeout(); // actually disconnect this._doDisconnect(); return false; }, /** PrivateFunction: _onIdle * _Private_ handler to process events during idle cycle. * * This handler is called every 100ms to fire timed handlers that * are ready and keep poll requests going. */ _onIdle: function () { var i, thand, since, newList; // add timed handlers scheduled for addition // NOTE: we add before remove in the case a timed handler is // added and then deleted before the next _onIdle() call. while (this.addTimeds.length > 0) { this.timedHandlers.push(this.addTimeds.pop()); } // remove timed handlers that have been scheduled for deletion while (this.removeTimeds.length > 0) { thand = this.removeTimeds.pop(); i = this.timedHandlers.indexOf(thand); if (i >= 0) { this.timedHandlers.splice(i, 1); } } // call ready timed handlers var now = new Date().getTime(); newList = []; for (i = 0; i < this.timedHandlers.length; i++) { thand = this.timedHandlers[i]; if (this.authenticated || !thand.user) { since = thand.lastCalled + thand.period; if (since - now <= 0) { if (thand.run()) { newList.push(thand); } } else { newList.push(thand); } } } this.timedHandlers = newList; clearTimeout(this._idleTimeout); this._proto._onIdle(); // reactivate the timer only if connected if (this.connected) { this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); } } }; if (callback) { callback(Strophe, $build, $msg, $iq, $pres); } /** Class: Strophe.SASLMechanism * * encapsulates SASL authentication mechanisms. * * User code may override the priority for each mechanism or disable it completely. * See <priority> for information about changing priority and <test> for informatian on * how to disable a mechanism. * * By default, all mechanisms are enabled and the priorities are * * SCRAM-SHA1 - 40 * DIGEST-MD5 - 30 * Plain - 20 */ /** * PrivateConstructor: Strophe.SASLMechanism * SASL auth mechanism abstraction. * * Parameters: * (String) name - SASL Mechanism name. * (Boolean) isClientFirst - If client should send response first without challenge. * (Number) priority - Priority. * * Returns: * A new Strophe.SASLMechanism object. */ Strophe.SASLMechanism = function(name, isClientFirst, priority) { /** PrivateVariable: name * Mechanism name. */ this.name = name; /** PrivateVariable: isClientFirst * If client sends response without initial server challenge. */ this.isClientFirst = isClientFirst; /** Variable: priority * Determines which <SASLMechanism> is chosen for authentication (Higher is better). * Users may override this to prioritize mechanisms differently. * * In the default configuration the priorities are * * SCRAM-SHA1 - 40 * DIGEST-MD5 - 30 * Plain - 20 * * Example: (This will cause Strophe to choose the mechanism that the server sent first) * * > Strophe.SASLMD5.priority = Strophe.SASLSHA1.priority; * * See <SASL mechanisms> for a list of available mechanisms. * */ this.priority = priority; }; Strophe.SASLMechanism.prototype = { /** * Function: test * Checks if mechanism able to run. * To disable a mechanism, make this return false; * * To disable plain authentication run * > Strophe.SASLPlain.test = function() { * > return false; * > } * * See <SASL mechanisms> for a list of available mechanisms. * * Parameters: * (Strophe.Connection) connection - Target Connection. * * Returns: * (Boolean) If mechanism was able to run. */ /* jshint unused:false */ test: function(connection) { return true; }, /* jshint unused:true */ /** PrivateFunction: onStart * Called before starting mechanism on some connection. * * Parameters: * (Strophe.Connection) connection - Target Connection. */ onStart: function(connection) { this._connection = connection; }, /** PrivateFunction: onChallenge * Called by protocol implementation on incoming challenge. If client is * first (isClientFirst == true) challenge will be null on the first call. * * Parameters: * (Strophe.Connection) connection - Target Connection. * (String) challenge - current challenge to handle. * * Returns: * (String) Mechanism response. */ /* jshint unused:false */ onChallenge: function(connection, challenge) { throw new Error("You should implement challenge handling!"); }, /* jshint unused:true */ /** PrivateFunction: onFailure * Protocol informs mechanism implementation about SASL failure. */ onFailure: function() { this._connection = null; }, /** PrivateFunction: onSuccess * Protocol informs mechanism implementation about SASL success. */ onSuccess: function() { this._connection = null; } }; /** Constants: SASL mechanisms * Available authentication mechanisms * * Strophe.SASLAnonymous - SASL Anonymous authentication. * Strophe.SASLPlain - SASL Plain authentication. * Strophe.SASLMD5 - SASL Digest-MD5 authentication * Strophe.SASLSHA1 - SASL SCRAM-SHA1 authentication */ // Building SASL callbacks /** PrivateConstructor: SASLAnonymous * SASL Anonymous authentication. */ Strophe.SASLAnonymous = function() {}; Strophe.SASLAnonymous.prototype = new Strophe.SASLMechanism("ANONYMOUS", false, 10); Strophe.SASLAnonymous.test = function(connection) { return connection.authcid === null; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLAnonymous.prototype.name] = Strophe.SASLAnonymous; /** PrivateConstructor: SASLPlain * SASL Plain authentication. */ Strophe.SASLPlain = function() {}; Strophe.SASLPlain.prototype = new Strophe.SASLMechanism("PLAIN", true, 20); Strophe.SASLPlain.test = function(connection) { return connection.authcid !== null; }; Strophe.SASLPlain.prototype.onChallenge = function(connection) { var auth_str = connection.authzid; auth_str = auth_str + "\u0000"; auth_str = auth_str + connection.authcid; auth_str = auth_str + "\u0000"; auth_str = auth_str + connection.pass; return auth_str; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLPlain.prototype.name] = Strophe.SASLPlain; /** PrivateConstructor: SASLSHA1 * SASL SCRAM SHA 1 authentication. */ Strophe.SASLSHA1 = function() {}; /* TEST: * This is a simple example of a SCRAM-SHA-1 authentication exchange * when the client doesn't support channel bindings (username 'user' and * password 'pencil' are used): * * C: n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL * S: r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92, * i=4096 * C: c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j, * p=v0X8v3Bz2T0CJGbJQyF0X+HI4Ts= * S: v=rmF9pqV8S7suAoZWja4dJRkFsKQ= * */ Strophe.SASLSHA1.prototype = new Strophe.SASLMechanism("SCRAM-SHA-1", true, 40); Strophe.SASLSHA1.test = function(connection) { return connection.authcid !== null; }; Strophe.SASLSHA1.prototype.onChallenge = function(connection, challenge, test_cnonce) { var cnonce = test_cnonce || MD5.hexdigest(Math.random() * 1234567890); var auth_str = "n=" + connection.authcid; auth_str += ",r="; auth_str += cnonce; connection._sasl_data.cnonce = cnonce; connection._sasl_data["client-first-message-bare"] = auth_str; auth_str = "n,," + auth_str; this.onChallenge = function (connection, challenge) { var nonce, salt, iter, Hi, U, U_old, i, k; var clientKey, serverKey, clientSignature; var responseText = "c=biws,"; var authMessage = connection._sasl_data["client-first-message-bare"] + "," + challenge + ","; var cnonce = connection._sasl_data.cnonce; var attribMatch = /([a-z]+)=([^,]+)(,|$)/; while (challenge.match(attribMatch)) { var matches = challenge.match(attribMatch); challenge = challenge.replace(matches[0], ""); switch (matches[1]) { case "r": nonce = matches[2]; break; case "s": salt = matches[2]; break; case "i": iter = matches[2]; break; } } if (nonce.substr(0, cnonce.length) !== cnonce) { connection._sasl_data = {}; return connection._sasl_failure_cb(); } responseText += "r=" + nonce; authMessage += responseText; salt = Base64.decode(salt); salt += "\x00\x00\x00\x01"; Hi = U_old = core_hmac_sha1(connection.pass, salt); for (i = 1; i < iter; i++) { U = core_hmac_sha1(connection.pass, binb2str(U_old)); for (k = 0; k < 5; k++) { Hi[k] ^= U[k]; } U_old = U; } Hi = binb2str(Hi); clientKey = core_hmac_sha1(Hi, "Client Key"); serverKey = str_hmac_sha1(Hi, "Server Key"); clientSignature = core_hmac_sha1(str_sha1(binb2str(clientKey)), authMessage); connection._sasl_data["server-signature"] = b64_hmac_sha1(serverKey, authMessage); for (k = 0; k < 5; k++) { clientKey[k] ^= clientSignature[k]; } responseText += ",p=" + Base64.encode(binb2str(clientKey)); return responseText; }.bind(this); return auth_str; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLSHA1.prototype.name] = Strophe.SASLSHA1; /** PrivateConstructor: SASLMD5 * SASL DIGEST MD5 authentication. */ Strophe.SASLMD5 = function() {}; Strophe.SASLMD5.prototype = new Strophe.SASLMechanism("DIGEST-MD5", false, 30); Strophe.SASLMD5.test = function(connection) { return connection.authcid !== null; }; /** PrivateFunction: _quote * _Private_ utility function to backslash escape and quote strings. * * Parameters: * (String) str - The string to be quoted. * * Returns: * quoted string */ Strophe.SASLMD5.prototype._quote = function (str) { return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"'; //" end string workaround for emacs }; Strophe.SASLMD5.prototype.onChallenge = function(connection, challenge, test_cnonce) { var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/; var cnonce = test_cnonce || MD5.hexdigest("" + (Math.random() * 1234567890)); var realm = ""; var host = null; var nonce = ""; var qop = ""; var matches; while (challenge.match(attribMatch)) { matches = challenge.match(attribMatch); challenge = challenge.replace(matches[0], ""); matches[2] = matches[2].replace(/^"(.+)"$/, "$1"); switch (matches[1]) { case "realm": realm = matches[2]; break; case "nonce": nonce = matches[2]; break; case "qop": qop = matches[2]; break; case "host": host = matches[2]; break; } } var digest_uri = connection.servtype + "/" + connection.domain; if (host !== null) { digest_uri = digest_uri + "/" + host; } var A1 = MD5.hash(connection.authcid + ":" + realm + ":" + this._connection.pass) + ":" + nonce + ":" + cnonce; var A2 = 'AUTHENTICATE:' + digest_uri; var responseText = ""; responseText += 'charset=utf-8,'; responseText += 'username=' + this._quote(connection.authcid) + ','; responseText += 'realm=' + this._quote(realm) + ','; responseText += 'nonce=' + this._quote(nonce) + ','; responseText += 'nc=00000001,'; responseText += 'cnonce=' + this._quote(cnonce) + ','; responseText += 'digest-uri=' + this._quote(digest_uri) + ','; responseText += 'response=' + MD5.hexdigest(MD5.hexdigest(A1) + ":" + nonce + ":00000001:" + cnonce + ":auth:" + MD5.hexdigest(A2)) + ","; responseText += 'qop=auth'; this.onChallenge = function () { return ""; }.bind(this); return responseText; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLMD5.prototype.name] = Strophe.SASLMD5; })(function () { window.Strophe = arguments[0]; window.$build = arguments[1]; window.$msg = arguments[2]; window.$iq = arguments[3]; window.$pres = arguments[4]; }); /* This program is distributed under the terms of the MIT license. Please see the LICENSE file for details. Copyright 2006-2008, OGG, LLC */ /* jshint undef: true, unused: true:, noarg: true, latedef: true */ /*global window, setTimeout, clearTimeout, XMLHttpRequest, ActiveXObject, Strophe, $build */ /** PrivateClass: Strophe.Request * _Private_ helper class that provides a cross implementation abstraction * for a BOSH related XMLHttpRequest. * * The Strophe.Request class is used internally to encapsulate BOSH request * information. It is not meant to be used from user's code. */ /** PrivateConstructor: Strophe.Request * Create and initialize a new Strophe.Request object. * * Parameters: * (XMLElement) elem - The XML data to be sent in the request. * (Function) func - The function that will be called when the * XMLHttpRequest readyState changes. * (Integer) rid - The BOSH rid attribute associated with this request. * (Integer) sends - The number of times this same request has been * sent. */ Strophe.Request = function (elem, func, rid, sends) { this.id = ++Strophe._requestId; this.xmlData = elem; this.data = Strophe.serialize(elem); // save original function in case we need to make a new request // from this one. this.origFunc = func; this.func = func; this.rid = rid; this.date = NaN; this.sends = sends || 0; this.abort = false; this.dead = null; this.age = function () { if (!this.date) { return 0; } var now = new Date(); return (now - this.date) / 1000; }; this.timeDead = function () { if (!this.dead) { return 0; } var now = new Date(); return (now - this.dead) / 1000; }; this.xhr = this._newXHR(); }; Strophe.Request.prototype = { /** PrivateFunction: getResponse * Get a response from the underlying XMLHttpRequest. * * This function attempts to get a response from the request and checks * for errors. * * Throws: * "parsererror" - A parser error occured. * * Returns: * The DOM element tree of the response. */ getResponse: function () { var node = null; if (this.xhr.responseXML && this.xhr.responseXML.documentElement) { node = this.xhr.responseXML.documentElement; if (node.tagName == "parsererror") { Strophe.error("invalid response received"); Strophe.error("responseText: " + this.xhr.responseText); Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML)); throw "parsererror"; } } else if (this.xhr.responseText) { Strophe.error("invalid response received"); Strophe.error("responseText: " + this.xhr.responseText); Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML)); } return node; }, /** PrivateFunction: _newXHR * _Private_ helper function to create XMLHttpRequests. * * This function creates XMLHttpRequests across all implementations. * * Returns: * A new XMLHttpRequest. */ _newXHR: function () { var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); if (xhr.overrideMimeType) { xhr.overrideMimeType("text/xml"); } } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // use Function.bind() to prepend ourselves as an argument xhr.onreadystatechange = this.func.bind(null, this); return xhr; } }; /** Class: Strophe.Bosh * _Private_ helper class that handles BOSH Connections * * The Strophe.Bosh class is used internally by Strophe.Connection * to encapsulate BOSH sessions. It is not meant to be used from user's code. */ /** File: bosh.js * A JavaScript library to enable BOSH in Strophejs. * * this library uses Bidirectional-streams Over Synchronous HTTP (BOSH) * to emulate a persistent, stateful, two-way connection to an XMPP server. * More information on BOSH can be found in XEP 124. */ /** PrivateConstructor: Strophe.Bosh * Create and initialize a Strophe.Bosh object. * * Parameters: * (Strophe.Connection) connection - The Strophe.Connection that will use BOSH. * * Returns: * A new Strophe.Bosh object. */ Strophe.Bosh = function(connection) { this._conn = connection; /* request id for body tags */ this.rid = Math.floor(Math.random() * 4294967295); /* The current session ID. */ this.sid = null; // default BOSH values this.hold = 1; this.wait = 60; this.window = 5; this._requests = []; }; Strophe.Bosh.prototype = { /** Variable: strip * * BOSH-Connections will have all stanzas wrapped in a <body> tag when * passed to <Strophe.Connection.xmlInput> or <Strophe.Connection.xmlOutput>. * To strip this tag, User code can set <Strophe.Bosh.strip> to "body": * * > Strophe.Bosh.prototype.strip = "body"; * * This will enable stripping of the body tag in both * <Strophe.Connection.xmlInput> and <Strophe.Connection.xmlOutput>. */ strip: null, /** PrivateFunction: _buildBody * _Private_ helper function to generate the <body/> wrapper for BOSH. * * Returns: * A Strophe.Builder with a <body/> element. */ _buildBody: function () { var bodyWrap = $build('body', { rid: this.rid++, xmlns: Strophe.NS.HTTPBIND }); if (this.sid !== null) { bodyWrap.attrs({sid: this.sid}); } return bodyWrap; }, /** PrivateFunction: _reset * Reset the connection. * * This function is called by the reset function of the Strophe Connection */ _reset: function () { this.rid = Math.floor(Math.random() * 4294967295); this.sid = null; }, /** PrivateFunction: _connect * _Private_ function that initializes the BOSH connection. * * Creates and sends the Request that initializes the BOSH connection. */ _connect: function (wait, hold, route) { this.wait = wait || this.wait; this.hold = hold || this.hold; // build the body tag var body = this._buildBody().attrs({ to: this._conn.domain, "xml:lang": "en", wait: this.wait, hold: this.hold, content: "text/xml; charset=utf-8", ver: "1.6", "xmpp:version": "1.0", "xmlns:xmpp": Strophe.NS.BOSH }); if(route){ body.attrs({ route: route }); } var _connect_cb = this._conn._connect_cb; this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, _connect_cb.bind(this._conn)), body.tree().getAttribute("rid"))); this._throttledRequestHandler(); }, /** PrivateFunction: _attach * Attach to an already created and authenticated BOSH session. * * This function is provided to allow Strophe to attach to BOSH * sessions which have been created externally, perhaps by a Web * application. This is often used to support auto-login type features * without putting user credentials into the page. * * Parameters: * (String) jid - The full JID that is bound by the session. * (String) sid - The SID of the BOSH session. * (String) rid - The current RID of the BOSH session. This RID * will be used by the next request. * (Function) callback The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * Other settings will require tweaks to the Strophe.TIMEOUT value. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). * (Integer) wind - The optional HTTBIND window value. This is the * allowed range of request ids that are valid. The default is 5. */ _attach: function (jid, sid, rid, callback, wait, hold, wind) { this._conn.jid = jid; this.sid = sid; this.rid = rid; this._conn.connect_callback = callback; this._conn.domain = Strophe.getDomainFromJid(this._conn.jid); this._conn.authenticated = true; this._conn.connected = true; this.wait = wait || this.wait; this.hold = hold || this.hold; this.window = wind || this.window; this._conn._changeConnectStatus(Strophe.Status.ATTACHED, null); }, /** PrivateFunction: _connect_cb * _Private_ handler for initial connection request. * * This handler is used to process the Bosh-part of the initial request. * Parameters: * (Strophe.Request) bodyWrap - The received stanza. */ _connect_cb: function (bodyWrap) { var typ = bodyWrap.getAttribute("type"); var cond, conflict; if (typ !== null && typ == "terminate") { // an error occurred Strophe.error("BOSH-Connection failed: " + cond); cond = bodyWrap.getAttribute("condition"); conflict = bodyWrap.getElementsByTagName("conflict"); if (cond !== null) { if (cond == "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, cond); } else { this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown"); } this._conn._doDisconnect(); return Strophe.Status.CONNFAIL; } // check to make sure we don't overwrite these if _connect_cb is // called multiple times in the case of missing stream:features if (!this.sid) { this.sid = bodyWrap.getAttribute("sid"); } var wind = bodyWrap.getAttribute('requests'); if (wind) { this.window = parseInt(wind, 10); } var hold = bodyWrap.getAttribute('hold'); if (hold) { this.hold = parseInt(hold, 10); } var wait = bodyWrap.getAttribute('wait'); if (wait) { this.wait = parseInt(wait, 10); } }, /** PrivateFunction: _disconnect * _Private_ part of Connection.disconnect for Bosh * * Parameters: * (Request) pres - This stanza will be sent before disconnecting. */ _disconnect: function (pres) { this._sendTerminate(pres); }, /** PrivateFunction: _doDisconnect * _Private_ function to disconnect. * * Resets the SID and RID. */ _doDisconnect: function () { this.sid = null; this.rid = Math.floor(Math.random() * 4294967295); }, /** PrivateFunction: _emptyQueue * _Private_ function to check if the Request queue is empty. * * Returns: * True, if there are no Requests queued, False otherwise. */ _emptyQueue: function () { return this._requests.length === 0; }, /** PrivateFunction: _hitError * _Private_ function to handle the error count. * * Requests are resent automatically until their error count reaches * 5. Each time an error is encountered, this function is called to * increment the count and disconnect if the count is too high. * * Parameters: * (Integer) reqStatus - The request status. */ _hitError: function (reqStatus) { this.errors++; Strophe.warn("request errored, status: " + reqStatus + ", number of errors: " + this.errors); if (this.errors > 4) { this._onDisconnectTimeout(); } }, /** PrivateFunction: _no_auth_received * * Called on stream start/restart when no stream:features * has been received and sends a blank poll request. */ _no_auth_received: function (_callback) { if (_callback) { _callback = _callback.bind(this._conn); } else { _callback = this._conn._connect_cb.bind(this._conn); } var body = this._buildBody(); this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, _callback.bind(this._conn)), body.tree().getAttribute("rid"))); this._throttledRequestHandler(); }, /** PrivateFunction: _onDisconnectTimeout * _Private_ timeout handler for handling non-graceful disconnection. * * Cancels all remaining Requests and clears the queue. */ _onDisconnectTimeout: function () { var req; while (this._requests.length > 0) { req = this._requests.pop(); req.abort = true; req.xhr.abort(); // jslint complains, but this is fine. setting to empty func // is necessary for IE6 req.xhr.onreadystatechange = function () {}; // jshint ignore:line } }, /** PrivateFunction: _onIdle * _Private_ handler called by Strophe.Connection._onIdle * * Sends all queued Requests or polls with empty Request if there are none. */ _onIdle: function () { var data = this._conn._data; // if no requests are in progress, poll if (this._conn.authenticated && this._requests.length === 0 && data.length === 0 && !this._conn.disconnecting) { Strophe.info("no requests during idle cycle, sending " + "blank request"); data.push(null); } if (this._requests.length < 2 && data.length > 0 && !this._conn.paused) { var body = this._buildBody(); for (var i = 0; i < data.length; i++) { if (data[i] !== null) { if (data[i] === "restart") { body.attrs({ to: this._conn.domain, "xml:lang": "en", "xmpp:restart": "true", "xmlns:xmpp": Strophe.NS.BOSH }); } else { body.cnode(data[i]).up(); } } } delete this._conn._data; this._conn._data = []; this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid"))); this._processRequest(this._requests.length - 1); } if (this._requests.length > 0) { var time_elapsed = this._requests[0].age(); if (this._requests[0].dead !== null) { if (this._requests[0].timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) { this._throttledRequestHandler(); } } if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) { Strophe.warn("Request " + this._requests[0].id + " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) + " seconds since last activity"); this._throttledRequestHandler(); } } }, /** PrivateFunction: _onRequestStateChange * _Private_ handler for Strophe.Request state changes. * * This function is called when the XMLHttpRequest readyState changes. * It contains a lot of error handling logic for the many ways that * requests can fail, and calls the request callback when requests * succeed. * * Parameters: * (Function) func - The handler for the request. * (Strophe.Request) req - The request that is changing readyState. */ _onRequestStateChange: function (func, req) { Strophe.debug("request id " + req.id + "." + req.sends + " state changed to " + req.xhr.readyState); if (req.abort) { req.abort = false; return; } // request complete var reqStatus; if (req.xhr.readyState == 4) { reqStatus = 0; try { reqStatus = req.xhr.status; } catch (e) { // ignore errors from undefined status attribute. works // around a browser bug } if (typeof(reqStatus) == "undefined") { reqStatus = 0; } if (this.disconnecting) { if (reqStatus >= 400) { this._hitError(reqStatus); return; } } var reqIs0 = (this._requests[0] == req); var reqIs1 = (this._requests[1] == req); if ((reqStatus > 0 && reqStatus < 500) || req.sends > 5) { // remove from internal queue this._removeRequest(req); Strophe.debug("request id " + req.id + " should now be removed"); } // request succeeded if (reqStatus == 200) { // if request 1 finished, or request 0 finished and request // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to // restart the other - both will be in the first spot, as the // completed request has been removed from the queue already if (reqIs1 || (reqIs0 && this._requests.length > 0 && this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) { this._restartRequest(0); } // call handler Strophe.debug("request id " + req.id + "." + req.sends + " got 200"); func(req); this.errors = 0; } else { Strophe.error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened"); if (reqStatus === 0 || (reqStatus >= 400 && reqStatus < 600) || reqStatus >= 12000) { this._hitError(reqStatus); if (reqStatus >= 400 && reqStatus < 500) { this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING, null); this._conn._doDisconnect(); } } } if (!((reqStatus > 0 && reqStatus < 500) || req.sends > 5)) { this._throttledRequestHandler(); } } }, /** PrivateFunction: _processRequest * _Private_ function to process a request in the queue. * * This function takes requests off the queue and sends them and * restarts dead requests. * * Parameters: * (Integer) i - The index of the request in the queue. */ _processRequest: function (i) { var self = this; var req = this._requests[i]; var reqStatus = -1; try { if (req.xhr.readyState == 4) { reqStatus = req.xhr.status; } } catch (e) { Strophe.error("caught an error in _requests[" + i + "], reqStatus: " + reqStatus); } if (typeof(reqStatus) == "undefined") { reqStatus = -1; } // make sure we limit the number of retries if (req.sends > this.maxRetries) { this._onDisconnectTimeout(); return; } var time_elapsed = req.age(); var primaryTimeout = (!isNaN(time_elapsed) && time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)); var secondaryTimeout = (req.dead !== null && req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)); var requestCompletedWithServerError = (req.xhr.readyState == 4 && (reqStatus < 1 || reqStatus >= 500)); if (primaryTimeout || secondaryTimeout || requestCompletedWithServerError) { if (secondaryTimeout) { Strophe.error("Request " + this._requests[i].id + " timed out (secondary), restarting"); } req.abort = true; req.xhr.abort(); // setting to null fails on IE6, so set to empty function req.xhr.onreadystatechange = function () {}; this._requests[i] = new Strophe.Request(req.xmlData, req.origFunc, req.rid, req.sends); req = this._requests[i]; } if (req.xhr.readyState === 0) { Strophe.debug("request id " + req.id + "." + req.sends + " posting"); try { req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true); } catch (e2) { Strophe.error("XHR open failed."); if (!this._conn.connected) { this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "bad-service"); } this._conn.disconnect(); return; } // Fires the XHR request -- may be invoked immediately // or on a gradually expanding retry window for reconnects var sendFunc = function () { req.date = new Date(); if (self._conn.options.customHeaders){ var headers = self._conn.options.customHeaders; for (var header in headers) { if (headers.hasOwnProperty(header)) { req.xhr.setRequestHeader(header, headers[header]); } } } req.xhr.send(req.data); }; // Implement progressive backoff for reconnects -- // First retry (send == 1) should also be instantaneous if (req.sends > 1) { // Using a cube of the retry number creates a nicely // expanding retry window var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait), Math.pow(req.sends, 3)) * 1000; setTimeout(sendFunc, backoff); } else { sendFunc(); } req.sends++; if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) { if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) { this._conn.xmlOutput(req.xmlData.childNodes[0]); } else { this._conn.xmlOutput(req.xmlData); } } if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) { this._conn.rawOutput(req.data); } } else { Strophe.debug("_processRequest: " + (i === 0 ? "first" : "second") + " request has readyState of " + req.xhr.readyState); } }, /** PrivateFunction: _removeRequest * _Private_ function to remove a request from the queue. * * Parameters: * (Strophe.Request) req - The request to remove. */ _removeRequest: function (req) { Strophe.debug("removing request"); var i; for (i = this._requests.length - 1; i >= 0; i--) { if (req == this._requests[i]) { this._requests.splice(i, 1); } } // IE6 fails on setting to null, so set to empty function req.xhr.onreadystatechange = function () {}; this._throttledRequestHandler(); }, /** PrivateFunction: _restartRequest * _Private_ function to restart a request that is presumed dead. * * Parameters: * (Integer) i - The index of the request in the queue. */ _restartRequest: function (i) { var req = this._requests[i]; if (req.dead === null) { req.dead = new Date(); } this._processRequest(i); }, /** PrivateFunction: _reqToData * _Private_ function to get a stanza out of a request. * * Tries to extract a stanza out of a Request Object. * When this fails the current connection will be disconnected. * * Parameters: * (Object) req - The Request. * * Returns: * The stanza that was passed. */ _reqToData: function (req) { try { return req.getResponse(); } catch (e) { if (e != "parsererror") { throw e; } this._conn.disconnect("strophe-parsererror"); } }, /** PrivateFunction: _sendTerminate * _Private_ function to send initial disconnect sequence. * * This is the first step in a graceful disconnect. It sends * the BOSH server a terminate body and includes an unavailable * presence if authentication has completed. */ _sendTerminate: function (pres) { Strophe.info("_sendTerminate was called"); var body = this._buildBody().attrs({type: "terminate"}); if (pres) { body.cnode(pres.tree()); } var req = new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid")); this._requests.push(req); this._throttledRequestHandler(); }, /** PrivateFunction: _send * _Private_ part of the Connection.send function for BOSH * * Just triggers the RequestHandler to send the messages that are in the queue */ _send: function () { clearTimeout(this._conn._idleTimeout); this._throttledRequestHandler(); this._conn._idleTimeout = setTimeout(this._conn._onIdle.bind(this._conn), 100); }, /** PrivateFunction: _sendRestart * * Send an xmpp:restart stanza. */ _sendRestart: function () { this._throttledRequestHandler(); clearTimeout(this._conn._idleTimeout); }, /** PrivateFunction: _throttledRequestHandler * _Private_ function to throttle requests to the connection window. * * This function makes sure we don't send requests so fast that the * request ids overflow the connection window in the case that one * request died. */ _throttledRequestHandler: function () { if (!this._requests) { Strophe.debug("_throttledRequestHandler called with " + "undefined requests"); } else { Strophe.debug("_throttledRequestHandler called with " + this._requests.length + " requests"); } if (!this._requests || this._requests.length === 0) { return; } if (this._requests.length > 0) { this._processRequest(0); } if (this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window) { this._processRequest(1); } } }; /* This program is distributed under the terms of the MIT license. Please see the LICENSE file for details. Copyright 2006-2008, OGG, LLC */ /* jshint undef: true, unused: true:, noarg: true, latedef: true */ /*global document, window, clearTimeout, WebSocket, DOMParser, Strophe, $build */ /** Class: Strophe.WebSocket * _Private_ helper class that handles WebSocket Connections * * The Strophe.WebSocket class is used internally by Strophe.Connection * to encapsulate WebSocket sessions. It is not meant to be used from user's code. */ /** File: websocket.js * A JavaScript library to enable XMPP over Websocket in Strophejs. * * This file implements XMPP over WebSockets for Strophejs. * If a Connection is established with a Websocket url (ws://...) * Strophe will use WebSockets. * For more information on XMPP-over WebSocket see this RFC draft: * http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00 * * WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de) */ /** PrivateConstructor: Strophe.Websocket * Create and initialize a Strophe.WebSocket object. * Currently only sets the connection Object. * * Parameters: * (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets. * * Returns: * A new Strophe.WebSocket object. */ Strophe.Websocket = function(connection) { this._conn = connection; this.strip = "stream:stream"; var service = connection.service; if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) { // If the service is not an absolute URL, assume it is a path and put the absolute // URL together from options, current URL and the path. var new_service = ""; if (connection.options.protocol === "ws" && window.location.protocol !== "https:") { new_service += "ws"; } else { new_service += "wss"; } new_service += "://" + window.location.host; if (service.indexOf("/") !== 0) { new_service += window.location.pathname + service; } else { new_service += service; } connection.service = new_service; } }; Strophe.Websocket.prototype = { /** PrivateFunction: _buildStream * _Private_ helper function to generate the <stream> start tag for WebSockets * * Returns: * A Strophe.Builder with a <stream> element. */ _buildStream: function () { return $build("stream:stream", { "to": this._conn.domain, "xmlns": Strophe.NS.CLIENT, "xmlns:stream": Strophe.NS.STREAM, "version": '1.0' }); }, /** PrivateFunction: _check_streamerror * _Private_ checks a message for stream:error * * Parameters: * (Strophe.Request) bodyWrap - The received stanza. * connectstatus - The ConnectStatus that will be set on error. * Returns: * true if there was a streamerror, false otherwise. */ _check_streamerror: function (bodyWrap, connectstatus) { var errors = bodyWrap.getElementsByTagName("stream:error"); if (errors.length === 0) { return false; } var error = errors[0]; var condition = ""; var text = ""; var ns = "urn:ietf:params:xml:ns:xmpp-streams"; for (var i = 0; i < error.childNodes.length; i++) { var e = error.childNodes[i]; if (e.getAttribute("xmlns") !== ns) { break; } if (e.nodeName === "text") { text = e.textContent; } else { condition = e.nodeName; } } var errorString = "WebSocket stream error: "; if (condition) { errorString += condition; } else { errorString += "unknown"; } if (text) { errorString += " - " + condition; } Strophe.error(errorString); // close the connection on stream_error this._conn._changeConnectStatus(connectstatus, condition); this._conn._doDisconnect(); return true; }, /** PrivateFunction: _reset * Reset the connection. * * This function is called by the reset function of the Strophe Connection. * Is not needed by WebSockets. */ _reset: function () { return; }, /** PrivateFunction: _connect * _Private_ function called by Strophe.Connection.connect * * Creates a WebSocket for a connection and assigns Callbacks to it. * Does nothing if there already is a WebSocket. */ _connect: function () { // Ensure that there is no open WebSocket from a previous Connection. this._closeSocket(); // Create the new WobSocket this.socket = new WebSocket(this._conn.service, "xmpp"); this.socket.onopen = this._onOpen.bind(this); this.socket.onerror = this._onError.bind(this); this.socket.onclose = this._onClose.bind(this); this.socket.onmessage = this._connect_cb_wrapper.bind(this); }, /** PrivateFunction: _connect_cb * _Private_ function called by Strophe.Connection._connect_cb * * checks for stream:error * * Parameters: * (Strophe.Request) bodyWrap - The received stanza. */ _connect_cb: function(bodyWrap) { var error = this._check_streamerror(bodyWrap, Strophe.Status.CONNFAIL); if (error) { return Strophe.Status.CONNFAIL; } }, /** PrivateFunction: _handleStreamStart * _Private_ function that checks the opening stream:stream tag for errors. * * Disconnects if there is an error and returns false, true otherwise. * * Parameters: * (Node) message - Stanza containing the stream:stream. */ _handleStreamStart: function(message) { var error = false; // Check for errors in the stream:stream tag var ns = message.getAttribute("xmlns"); if (typeof ns !== "string") { error = "Missing xmlns in stream:stream"; } else if (ns !== Strophe.NS.CLIENT) { error = "Wrong xmlns in stream:stream: " + ns; } var ns_stream = message.namespaceURI; if (typeof ns_stream !== "string") { error = "Missing xmlns:stream in stream:stream"; } else if (ns_stream !== Strophe.NS.STREAM) { error = "Wrong xmlns:stream in stream:stream: " + ns_stream; } var ver = message.getAttribute("version"); if (typeof ver !== "string") { error = "Missing version in stream:stream"; } else if (ver !== "1.0") { error = "Wrong version in stream:stream: " + ver; } if (error) { this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, error); this._conn._doDisconnect(); return false; } return true; }, /** PrivateFunction: _connect_cb_wrapper * _Private_ function that handles the first connection messages. * * On receiving an opening stream tag this callback replaces itself with the real * message handler. On receiving a stream error the connection is terminated. */ _connect_cb_wrapper: function(message) { if (message.data.indexOf("<stream:stream ") === 0 || message.data.indexOf("<?xml") === 0) { // Strip the XML Declaration, if there is one var data = message.data.replace(/^(<\?.*?\?>\s*)*/, ""); if (data === '') return; //Make the initial stream:stream selfclosing to parse it without a SAX parser. data = message.data.replace(/<stream:stream (.*[^\/])>/, "<stream:stream $1/>"); var streamStart = new DOMParser().parseFromString(data, "text/xml").documentElement; this._conn.xmlInput(streamStart); this._conn.rawInput(message.data); //_handleStreamSteart will check for XML errors and disconnect on error if (this._handleStreamStart(streamStart)) { //_connect_cb will check for stream:error and disconnect on error this._connect_cb(streamStart); // ensure received stream:stream is NOT selfclosing and save it for following messages this.streamStart = message.data.replace(/^<stream:(.*)\/>$/, "<stream:$1>"); } } else if (message.data === "</stream:stream>") { this._conn.rawInput(message.data); this._conn.xmlInput(document.createElement("stream:stream")); this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Received closing stream"); this._conn._doDisconnect(); return; } else { var string = this._streamWrap(message.data); var elem = new DOMParser().parseFromString(string, "text/xml").documentElement; this.socket.onmessage = this._onMessage.bind(this); this._conn._connect_cb(elem, null, message.data); } }, /** PrivateFunction: _disconnect * _Private_ function called by Strophe.Connection.disconnect * * Disconnects and sends a last stanza if one is given * * Parameters: * (Request) pres - This stanza will be sent before disconnecting. */ _disconnect: function (pres) { if (this.socket.readyState !== WebSocket.CLOSED) { if (pres) { this._conn.send(pres); } var close = '</stream:stream>'; this._conn.xmlOutput(document.createElement("stream:stream")); this._conn.rawOutput(close); try { this.socket.send(close); } catch (e) { Strophe.info("Couldn't send closing stream tag."); } } this._conn._doDisconnect(); }, /** PrivateFunction: _doDisconnect * _Private_ function to disconnect. * * Just closes the Socket for WebSockets */ _doDisconnect: function () { Strophe.info("WebSockets _doDisconnect was called"); this._closeSocket(); }, /** PrivateFunction _streamWrap * _Private_ helper function to wrap a stanza in a <stream> tag. * This is used so Strophe can process stanzas from WebSockets like BOSH */ _streamWrap: function (stanza) { return this.streamStart + stanza + '</stream:stream>'; }, /** PrivateFunction: _closeSocket * _Private_ function to close the WebSocket. * * Closes the socket if it is still open and deletes it */ _closeSocket: function () { if (this.socket) { try { this.socket.close(); } catch (e) {} } this.socket = null; }, /** PrivateFunction: _emptyQueue * _Private_ function to check if the message queue is empty. * * Returns: * True, because WebSocket messages are send immediately after queueing. */ _emptyQueue: function () { return true; }, /** PrivateFunction: _onClose * _Private_ function to handle websockets closing. * * Nothing to do here for WebSockets */ _onClose: function() { if(this._conn.connected && !this._conn.disconnecting) { Strophe.error("Websocket closed unexcectedly"); this._conn._doDisconnect(); } else { Strophe.info("Websocket closed"); } }, /** PrivateFunction: _no_auth_received * * Called on stream start/restart when no stream:features * has been received. */ _no_auth_received: function (_callback) { Strophe.error("Server did not send any auth methods"); this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Server did not send any auth methods"); if (_callback) { _callback = _callback.bind(this._conn); _callback(); } this._conn._doDisconnect(); }, /** PrivateFunction: _onDisconnectTimeout * _Private_ timeout handler for handling non-graceful disconnection. * * This does nothing for WebSockets */ _onDisconnectTimeout: function () {}, /** PrivateFunction: _onError * _Private_ function to handle websockets errors. * * Parameters: * (Object) error - The websocket error. */ _onError: function(error) { Strophe.error("Websocket error " + error); this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established was disconnected."); this._disconnect(); }, /** PrivateFunction: _onIdle * _Private_ function called by Strophe.Connection._onIdle * * sends all queued stanzas */ _onIdle: function () { var data = this._conn._data; if (data.length > 0 && !this._conn.paused) { for (var i = 0; i < data.length; i++) { if (data[i] !== null) { var stanza, rawStanza; if (data[i] === "restart") { stanza = this._buildStream(); rawStanza = this._removeClosingTag(stanza); stanza = stanza.tree(); } else { stanza = data[i]; rawStanza = Strophe.serialize(stanza); } this._conn.xmlOutput(stanza); this._conn.rawOutput(rawStanza); this.socket.send(rawStanza); } } this._conn._data = []; } }, /** PrivateFunction: _onMessage * _Private_ function to handle websockets messages. * * This function parses each of the messages as if they are full documents. [TODO : We may actually want to use a SAX Push parser]. * * Since all XMPP traffic starts with "<stream:stream version='1.0' xml:lang='en' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='3697395463' from='SERVER'>" * The first stanza will always fail to be parsed... * Addtionnaly, the seconds stanza will always be a <stream:features> with the stream NS defined in the previous stanza... so we need to 'force' the inclusion of the NS in this stanza! * * Parameters: * (string) message - The websocket message. */ _onMessage: function(message) { var elem, data; // check for closing stream if (message.data === "</stream:stream>") { var close = "</stream:stream>"; this._conn.rawInput(close); this._conn.xmlInput(document.createElement("stream:stream")); if (!this._conn.disconnecting) { this._conn._doDisconnect(); } return; } else if (message.data.search("<stream:stream ") === 0) { //Make the initial stream:stream selfclosing to parse it without a SAX parser. data = message.data.replace(/<stream:stream (.*[^\/])>/, "<stream:stream $1/>"); elem = new DOMParser().parseFromString(data, "text/xml").documentElement; if (!this._handleStreamStart(elem)) { return; } } else { data = this._streamWrap(message.data); elem = new DOMParser().parseFromString(data, "text/xml").documentElement; } if (this._check_streamerror(elem, Strophe.Status.ERROR)) { return; } //handle unavailable presence stanza before disconnecting if (this._conn.disconnecting && elem.firstChild.nodeName === "presence" && elem.firstChild.getAttribute("type") === "unavailable") { this._conn.xmlInput(elem); this._conn.rawInput(Strophe.serialize(elem)); // if we are already disconnecting we will ignore the unavailable stanza and // wait for the </stream:stream> tag before we close the connection return; } this._conn._dataRecv(elem, message.data); }, /** PrivateFunction: _onOpen * _Private_ function to handle websockets connection setup. * * The opening stream tag is sent here. */ _onOpen: function() { Strophe.info("Websocket open"); var start = this._buildStream(); this._conn.xmlOutput(start.tree()); var startString = this._removeClosingTag(start); this._conn.rawOutput(startString); this.socket.send(startString); }, /** PrivateFunction: _removeClosingTag * _Private_ function to Make the first <stream:stream> non-selfclosing * * Parameters: * (Object) elem - The <stream:stream> tag. * * Returns: * The stream:stream tag as String */ _removeClosingTag: function(elem) { var string = Strophe.serialize(elem); string = string.replace(/<(stream:stream .*[^\/])\/>$/, "<$1>"); return string; }, /** PrivateFunction: _reqToData * _Private_ function to get a stanza out of a request. * * WebSockets don't use requests, so the passed argument is just returned. * * Parameters: * (Object) stanza - The stanza. * * Returns: * The stanza that was passed. */ _reqToData: function (stanza) { return stanza; }, /** PrivateFunction: _send * _Private_ part of the Connection.send function for WebSocket * * Just flushes the messages that are in the queue */ _send: function () { this._conn.flush(); }, /** PrivateFunction: _sendRestart * * Send an xmpp:restart stanza. */ _sendRestart: function () { clearTimeout(this._conn._idleTimeout); this._conn._onIdle.bind(this._conn)(); } };
/** * @file * Provide dragging capabilities to admin uis. */ /** * Triggers when weights columns are toggled. * * @event columnschange */ (function ($, Drupal, drupalSettings) { 'use strict'; /** * Store the state of weight columns display for all tables. * * Default value is to hide weight columns. */ var showWeight = JSON.parse(localStorage.getItem('Drupal.tableDrag.showWeight')); /** * Drag and drop table rows with field manipulation. * * Using the drupal_attach_tabledrag() function, any table with weights or * parent relationships may be made into draggable tables. Columns containing * a field may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to * tableDrag. * * @type {Drupal~behavior} */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { function initTableDrag(table, base) { if (table.length) { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(table[0], settings.tableDrag[base]); } } for (var base in settings.tableDrag) { if (settings.tableDrag.hasOwnProperty(base)) { initTableDrag($(context).find('#' + base).once('tabledrag'), base); } } } }; /** * Provides table and field manipulation. * * @constructor * * @param {HTMLElement} table * DOM object for the table to be made draggable. * @param {object} tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; var $table = $(table); /** * @type {jQuery} */ this.$table = $(table); /** * * @type {HTMLElement} */ this.table = table; /** * @type {object} */ this.tableSettings = tableSettings; /** * Used to hold information about a current drag operation. * * @type {?HTMLElement} */ this.dragObject = null; /** * Provides operations for row manipulation. * * @type {?HTMLElement} */ this.rowObject = null; /** * Remember the previous element. * * @type {?HTMLElement} */ this.oldRowElement = null; /** * Used to determine up or down direction from last mouse move. * * @type {number} */ this.oldY = 0; /** * Whether anything in the entire table has changed. * * @type {bool} */ this.changed = false; /** * Maximum amount of allowed parenting. * * @type {number} */ this.maxDepth = 0; /** * Direction of the table. * * @type {number} */ this.rtl = $(this.table).css('direction') === 'rtl' ? -1 : 1; /** * * @type {bool} */ this.striping = $(this.table).data('striping') === 1; /** * Configure the scroll settings. * * @type {object} * * @prop {number} amount * @prop {number} interval * @prop {number} trigger */ this.scrollSettings = {amount: 4, interval: 50, trigger: 70}; /** * * @type {?number} */ this.scrollInterval = null; /** * * @type {number} */ this.scrollY = 0; /** * * @type {number} */ this.windowHeight = 0; /** * Check this table's settings for parent relationships. * * For efficiency, large sections of code can be skipped if we don't need to * track horizontal movement and indentations. * * @type {bool} */ this.indentEnabled = false; for (var group in tableSettings) { if (tableSettings.hasOwnProperty(group)) { for (var n in tableSettings[group]) { if (tableSettings[group].hasOwnProperty(n)) { if (tableSettings[group][n].relationship === 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } } } if (this.indentEnabled) { /** * Total width of indents, set in makeDraggable. * * @type {number} */ this.indentCount = 1; // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); var $indentation = testCell.find('.js-indentation'); /** * * @type {number} */ this.indentAmount = $indentation.get(1).offsetLeft - $indentation.get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $table.find('> tr.draggable, > tbody > tr.draggable').each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $table.before($('<button type="button" class="link tabledrag-toggle-weight"></button>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .on('click', $.proxy(function (e) { e.preventDefault(); this.toggleColumns(); }, this)) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add event bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).on('touchmove', function (event) { return self.dragRow(event.originalEvent.touches[0], self); }); $(document).on('touchend', function (event) { return self.dropRow(event.originalEvent.touches[0], self); }); $(document).on('mousemove pointermove', function (event) { return self.dragRow(event, self); }); $(document).on('mouseup pointerup', function (event) { return self.dropRow(event, self); }); // React to localStorage event showing or hiding weight columns. $(window).on('storage', $.proxy(function (e) { // Only react to 'Drupal.tableDrag.showWeight' value change. if (e.originalEvent.key === 'Drupal.tableDrag.showWeight') { // This was changed in another window, get the new value for this // window. showWeight = JSON.parse(e.originalEvent.newValue); this.displayColumns(showWeight); } }, this)); }; /** * Initialize columns containing form elements to be hidden by default. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' localStorage value. */ Drupal.tableDrag.prototype.initColumns = function () { var $table = this.$table; var hidden; var cell; var columnIndex; for (var group in this.tableSettings) { if (this.tableSettings.hasOwnProperty(group)) { // Find the first field in this group. for (var d in this.tableSettings[group]) { if (this.tableSettings[group].hasOwnProperty(d)) { var field = $table.find('.' + this.tableSettings[group][d].target).eq(0); if (field.length && this.tableSettings[group][d].hidden) { hidden = this.tableSettings[group][d].hidden; cell = field.closest('td'); break; } } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 // based. Match immediate children of the parent element to allow // nesting. columnIndex = cell.parent().find('> td').index(cell.get(0)) + 1; $table.find('> thead > tr, > tbody > tr, > tr').each(this.addColspanClass(columnIndex)); } } } this.displayColumns(showWeight); }; /** * Mark cells that have colspan. * * In order to adjust the colspan instead of hiding them altogether. * * @param {number} columnIndex * The column index to add colspan class to. * * @return {function} * Function to add colspan class. */ Drupal.tableDrag.prototype.addColspanClass = function (columnIndex) { return function () { // Get the columnIndex and adjust for any colspans in this row. var $row = $(this); var index = columnIndex; var cells = $row.children(); var cell; cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }; }; /** * Hide or display weight columns. Triggers an event on change. * * @fires event:columnschange * * @param {bool} displayWeight * 'true' will show weight columns. */ Drupal.tableDrag.prototype.displayColumns = function (displayWeight) { if (displayWeight) { this.showColumns(); } // Default action is to hide columns. else { this.hideColumns(); } // Trigger an event to allow other scripts to react to this display change. // Force the extra parameter as a bool. $('table').findOnce('tabledrag').trigger('columnschange', !!displayWeight); }; /** * Toggle the weight column depending on 'showWeight' value. * * Store only default override. */ Drupal.tableDrag.prototype.toggleColumns = function () { showWeight = !showWeight; this.displayColumns(showWeight); if (showWeight) { // Save default override. localStorage.setItem('Drupal.tableDrag.showWeight', showWeight); } else { // Reset the value to its default. localStorage.removeItem('Drupal.tableDrag.showWeight'); } }; /** * Hide the columns containing weight/parent form elements. * * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { var $tables = $('table').findOnce('tabledrag'); // Hide weight/parent cells and headers. $tables.find('.tabledrag-hide').css('display', 'none'); // Show TableDrag handles. $tables.find('.tabledrag-handle').css('display', ''); // Reduce the colspan of any effected multi-span columns. $tables.find('.tabledrag-has-colspan').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); }; /** * Show the columns containing weight/parent form elements. * * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { var $tables = $('table').findOnce('tabledrag'); // Show weight/parent cells and headers. $tables.find('.tabledrag-hide').css('display', ''); // Hide TableDrag handles. $tables.find('.tabledrag-handle').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $tables.find('.tabledrag-has-colspan').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); }; /** * Find the target used within a particular row and group. * * @param {string} group * Group selector. * @param {HTMLElement} row * The row HTML element. * * @return {object} * The table row settings. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $(row).find('.' + group); var tableSettingsGroup = this.tableSettings[group]; for (var delta in tableSettingsGroup) { if (tableSettingsGroup.hasOwnProperty(delta)) { var targetClass = tableSettingsGroup[delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in tableSettingsGroup[delta]) { if (tableSettingsGroup[delta].hasOwnProperty(n)) { rowSettings[n] = tableSettingsGroup[delta][n]; } } return rowSettings; } } } }; /** * Take an item and add event handlers to make it become draggable. * * @param {HTMLElement} item * The item to add event handlers to. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; var $item = $(item); // Add a class to the title link. $item.find('td:first-of-type').find('a').addClass('menu-item__link'); // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). var $indentationLast = $item.find('td:first-of-type').find('.js-indentation').eq(-1); if ($indentationLast.length) { $indentationLast.after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($item.find('.js-indentation').length, self.indentCount); } else { $item.find('td').eq(0).prepend(handle); } handle.on('mousedown touchstart pointerdown', function (event) { event.preventDefault(); if (event.originalEvent.type === 'touchstart') { event = event.originalEvent.touches[0]; } self.dragStart(event, self, item); }); // Prevent the anchor tag from jumping us to the top of the page. handle.on('click', function (e) { e.preventDefault(); }); // Set blur cleanup when a handle is focused. handle.on('focus', function () { self.safeBlur = true; }); // On blur, fire the same function as a touchend/mouseup. This is used to // update values after a row has been moved through the keyboard support. handle.on('blur', function (event) { if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.on('keydown', function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode !== 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; var groupHeight; switch (event.keyCode) { // Left arrow. case 37: // Safari left arrow. case 63234: keyChange = true; self.rowObject.indent(-1 * self.rtl); break; // Up arrow. case 38: // Safari up arrow. case 63232: var $previousRow = $(self.rowObject.element).prev('tr:first-of-type'); var previousRow = $previousRow.get(0); while (previousRow && $previousRow.is(':hidden')) { $previousRow = $(previousRow).prev('tr:first-of-type'); previousRow = $previousRow.get(0); } if (previousRow) { // Do not allow the onBlur cleanup. self.safeBlur = false; self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. groupHeight = 0; while (previousRow && $previousRow.find('.js-indentation').length) { $previousRow = $(previousRow).prev('tr:first-of-type'); previousRow = $previousRow.get(0); groupHeight += $previousRow.is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] !== previousRow || $previousRow.is('.draggable')) { // Swap with the previous row (unless previous row is the first // one and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } // Regain focus after the DOM manipulation. handle.trigger('focus'); } break; // Right arrow. case 39: // Safari right arrow. case 63235: keyChange = true; self.rowObject.indent(self.rtl); break; // Down arrow. case 40: // Safari down arrow. case 63233: var $nextRow = $(self.rowObject.group).eq(-1).next('tr:first-of-type'); var nextRow = $nextRow.get(0); while (nextRow && $nextRow.is(':hidden')) { $nextRow = $(nextRow).next('tr:first-of-type'); nextRow = $nextRow.get(0); } if (nextRow) { // Do not allow the onBlur cleanup. self.safeBlur = false; self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).eq(-1).get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } // Regain focus after the DOM manipulation. handle.trigger('focus'); } break; } if (self.rowObject && self.rowObject.changed === true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; if (self.striping === true) { self.restripeTable(); } self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted // scrolling. IE and Safari will suppress scrolling on keydown, but all // other browsers need to return false on keypress. // http://www.quirksmode.org/js/keys.html handle.on('keypress', function (event) { switch (event.keyCode) { // Left arrow. case 37: // Up arrow. case 38: // Right arrow. case 39: // Down arrow. case 40: return false; } }); }; /** * Pointer event initiator, creates drag object and information. * * @param {jQuery.Event} event * The event object that trigger the drag. * @param {Drupal.tableDrag} self * The drag handle. * @param {HTMLElement} item * The item that that is being dragged. */ Drupal.tableDrag.prototype.dragStart = function (event, self, item) { // Create a new dragObject recording the pointer information. self.dragObject = {}; self.dragObject.initOffset = self.getPointerOffset(item, event); self.dragObject.initPointerCoords = self.pointerCoords(event); if (self.indentEnabled) { self.dragObject.indentPointerPos = self.dragObject.initPointerCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $(self.rowObject.element).find('a.tabledrag-handle').trigger('blur'); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'pointer', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } }; /** * Pointer movement handler, bound to document. * * @param {jQuery.Event} event * The pointer event. * @param {Drupal.tableDrag} self * The tableDrag instance. * * @return {bool|undefined} * Undefined if no dragObject is defined, false otherwise. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentPointerCoords = self.pointerCoords(event); var y = self.currentPointerCoords.y - self.dragObject.initOffset.y; var x = self.currentPointerCoords.x - self.dragObject.initOffset.x; // Check for row swapping and vertical scrolling. if (y !== self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; // Update the old value. self.oldY = y; // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentPointerCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction === 'down' || scrollAmount < 0 && self.rowObject.direction === 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction === 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } if (self.striping === true) { self.restripeTable(); } } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentPointerCoords.x - self.dragObject.indentPointerPos.x; // Set the number of indentations the pointer has been moved left or // right. var indentDiff = Math.round(xDiff / self.indentAmount); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and pointer indentations. self.dragObject.indentPointerPos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Pointerup behavior. * * @param {jQuery.Event} event * The pointer event. * @param {Drupal.tableDrag} self * The tableDrag instance. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { var droppedRow; var $droppedRow; // Drop row functionality. if (self.rowObject !== null) { droppedRow = self.rowObject.element; $droppedRow = $(droppedRow); // The row is already in the right place so we just release it. if (self.rowObject.changed === true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { if (self.tableSettings.hasOwnProperty(group)) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship === 'group') { for (var n in self.rowObject.children) { if (self.rowObject.children.hasOwnProperty(n)) { self.updateField(self.rowObject.children[n], group); } } } } } self.rowObject.markChanged(); if (self.changed === false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $droppedRow.removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to pointerup events. if (self.dragObject !== null) { self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); } }; /** * Get the coordinates from the event (allowing for browser differences). * * @param {jQuery.Event} event * The pointer event. * * @return {object} * An object with `x` and `y` keys indicating the position. */ Drupal.tableDrag.prototype.pointerCoords = function (event) { if (event.pageX || event.pageY) { return {x: event.pageX, y: event.pageY}; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Get the event offset from the target element. * * Given a target element and a pointer event, get the event offset from that * element. To do this we need the element's position and the target position. * * @param {HTMLElement} target * The target HTML element. * @param {jQuery.Event} event * The pointer event. * * @return {object} * An object with `x` and `y` keys indicating the position. */ Drupal.tableDrag.prototype.getPointerOffset = function (target, event) { var docPos = $(target).offset(); var pointerPos = this.pointerCoords(event); return {x: pointerPos.x - docPos.left, y: pointerPos.y - docPos.top}; }; /** * Find the row the mouse is currently over. * * This row is then taken and swapped with the one being dragged. * * @param {number} x * The x coordinate of the mouse on the page (not the screen). * @param {number} y * The y coordinate of the mouse on the page (not the screen). * * @return {*} * The drop target row, if found. */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var $row = $(row); var rowY = $row.offset().top; var rowHeight; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight === 0) { rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (n in this.rowObject.group) { if (this.rowObject.group[n] === row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row === this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a // draggable row. while ($row.is(':hidden') && $row.prev('tr').is(':hidden')) { $row = $row.prev('tr:first-of-type'); row = $row.get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields. * * @param {HTMLElement} changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { if (this.tableSettings.hasOwnProperty(group)) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } } }; /** * After the row is dropped, update a single table field. * * @param {HTMLElement} changedRow * DOM object for the row that was just dropped. * @param {string} group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); var $changedRow = $(changedRow); var sourceRow; var $previousRow; var previousRow; var useSibling; // Set the row as its own target. if (rowSettings.relationship === 'self' || rowSettings.relationship === 'group') { sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship === 'sibling') { $previousRow = $changedRow.prev('tr:first-of-type'); previousRow = $previousRow.get(0); var $nextRow = $changedRow.next('tr:first-of-type'); var nextRow = $nextRow.get(0); sourceRow = changedRow; if ($previousRow.is('.draggable') && $previousRow.find('.' + group).length) { if (this.indentEnabled) { if ($previousRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($nextRow.is('.draggable') && $nextRow.find('.' + group).length) { if (this.indentEnabled) { if ($nextRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship === 'parent') { $previousRow = $changedRow.prev('tr'); previousRow = $previousRow; while ($previousRow.length && $previousRow.find('.js-indentation').length >= this.rowObject.indents) { $previousRow = $previousRow.prev('tr'); previousRow = $previousRow; } // If we found a row. if ($previousRow.length) { sourceRow = $previousRow.get(0); } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first-of-type').get(0); if (sourceRow === this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $changedRow.find(targetClass).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $(sourceElement).closest('tr').find('.js-indentation').length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $(targetElement).find('option').each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(siblings).find(targetClass).each(function () { // If there are more items than possible values, assign the // maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(siblings[0]).find(targetClass).val(), 10) || 0; $(siblings).find(targetClass).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all tableDrag related classes from one row to another. * * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. * * @param {HTMLElement} sourceRow * The element for the source row. * @param {HTMLElement} targetRow * The element for the target row. * @param {string} group * The group selector. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $(sourceRow).find('.' + group); var targetElement = $(targetRow).find('.' + group); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; /** * Check the suggested scroll of the table. * * @param {number} cursorY * The Y position of the cursor. * * @return {number} * The suggested scroll. */ Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth !== 0 ? de.clientHeight : b.offsetHeight); var scrollY; if (document.all) { scrollY = this.scrollY = !de.scrollTop ? b.scrollTop : de.scrollTop; } else { scrollY = this.scrollY = window.pageYOffset ? window.pageYOffset : window.scrollY; } var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; /** * Set the scroll for the table. * * @param {number} scrollAmount * The amount of scroll to apply to the window. */ Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentPointerCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; /** * Command to restripe table properly. */ Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $(this.table).find('> tbody > tr.draggable:visible, > tr.draggable:visible') .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. * * @return {null} * Returns null when the stub function is used. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. * * @return {null} * Returns null when the stub function is used. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param {HTMLElement} tableRow * The DOM element for the table row we will be manipulating. * @param {string} method * The method in which this row is being moved. Either 'keyboard' or * 'mouse'. * @param {bool} indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param {number} maxDepth * The maximum amount of indentations this row may contain. * @param {bool} addClasses * Whether we want to add classes to this row to indicate child * relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { var $tableRow = $(tableRow); this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $tableRow.find('.js-indentation').length; this.changed = false; this.table = $tableRow.closest('table')[0]; this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; // Direction the row is being moved. this.direction = ''; if (this.indentEnabled) { this.indents = $tableRow.find('.js-indentation').length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($(this.group[n]).find('.js-indentation').length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param {bool} addClasses * Whether we want to add classes to this row to indicate child * relationships. * * @return {Array} * An array of children of the row. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; function rowIndentation(indentNum, el) { var self = $(el); if (child === 1 && (indentNum === parentIndentation)) { self.addClass('tree-child-first'); } if (indentNum === parentIndentation) { self.addClass('tree-child'); } else if (indentNum > parentIndentation) { self.addClass('tree-child-horizontal'); } } while (currentRow.length) { // A greater indentation indicates this is a child. if (currentRow.find('.js-indentation').length > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { currentRow.find('.js-indentation').each(rowIndentation); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $(rows[rows.length - 1]).find('.js-indentation:nth-child(' + (parentIndentation + 1) + ')').addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param {HTMLElement} row * DOM object for the row being considered for swapping. * * @return {bool} * Whether the swap is a valid swap or not. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { var $row = $(row); if (this.indentEnabled) { var prevRow; var nextRow; if (this.direction === 'down') { prevRow = row; nextRow = $row.next('tr').get(0); } else { prevRow = $row.prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] === row && $row.is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param {string} position * Whether the swap will occur 'before' or 'after' the given row. * @param {HTMLElement} row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { // Makes sure only DOM object are passed to Drupal.detachBehaviors(). this.group.forEach(function (row) { Drupal.detachBehaviors(row, drupalSettings, 'move'); }); $(row)[position](this.group); // Makes sure only DOM object are passed to Drupal.attachBehaviors()s. this.group.forEach(function (row) { Drupal.attachBehaviors(row, drupalSettings); }); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position. * * @param {?HTMLElement} prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param {?HTMLElement} nextRow * DOM object for the row after the tested position * (or null for last position in the table). * * @return {object} * An object with the keys `min` and `max` to indicate the valid indent * interval. */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var $prevRow = $(prevRow); var minIndent; var maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $(nextRow).find('.js-indentation').length : 0; // Maximum indentation: if (!prevRow || $prevRow.is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $prevRow.find('.js-indentation').length + ($prevRow.is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return {min: minIndent, max: maxIndent}; }; /** * Indent a row within the legal bounds of the table. * * @param {number} indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. * * @return {number} * The number of indentations applied. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { var $group = $(this.group); // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $group.eq(-1).next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $group.find('.js-indentation:first-of-type').remove(); this.indents--; } else { $group.find('td:first-of-type').prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row. * * According to its subgroup or indentation. Note that the passed-in row is * included in the list of siblings. * * @param {object} rowSettings * The field settings we're using to identify what constitutes a sibling. * * @return {Array} * An array of siblings. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; var checkRowIndentation; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if (checkRow.find('.' + rowSettings.target)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { checkRowIndentation = checkRow.find('.js-indentation').length; } if (!(this.indentEnabled) || (checkRowIndentation === rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = checkRow[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] === 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { if (this.children.hasOwnProperty(n)) { $(this.children[n]).find('.js-indentation') .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $(this.element).find('td:first-of-type'); if (cell.find('abbr.tabledrag-changed').length === 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. * * @return {null} * Returns null when the stub function is used. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. * * @param {HTMLElement} swappedRow * The element for the swapped row. * * @return {null} * Returns null when the stub function is used. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; $.extend(Drupal.theme, /** @lends Drupal.theme */{ /** * @return {string} * Markup for the marker. */ tableDragChangedMarker: function () { return '<abbr class="warning tabledrag-changed" title="' + Drupal.t('Changed') + '">*</abbr>'; }, /** * @return {string} * Markup for the indentation. */ tableDragIndentation: function () { return '<div class="js-indentation indentation">&nbsp;</div>'; }, /** * @return {string} * Markup for the warning. */ tableDragChangedWarning: function () { return '<div class="tabledrag-changed-warning messages messages--warning" role="alert">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('You have unsaved changes.') + '</div>'; } }); })(jQuery, Drupal, drupalSettings);
(function(){"use strict";function a(a){var b,c,d,e,f=Array.prototype.slice.call(arguments,1);for(b=0,c=f.length;c>b;b+=1)if(d=f[b])for(e in d)o.call(d,e)&&(a[e]=d[e]);return a}function b(a,b,c){this.locales=a,this.formats=b,this.pluralFn=c}function c(a){this.id=a}function d(a,b,c,d){this.id=a,this.offset=b,this.options=c,this.pluralFn=d}function e(a,b,c,d){this.id=a,this.offset=b,this.numberFormat=c,this.string=d}function f(a,b){this.id=a,this.options=b}function g(a,b,c){var d="string"==typeof a?g.__parse(a):a;if(!d||"messageFormatPattern"!==d.type)throw new TypeError("A message must be provided as a String or AST.");c=this._mergeFormats(g.formats,c),q(this,"_locale",{value:this._resolveLocale(b)});var e=g.__localeData__[this._locale].pluralRuleFunction,f=this._compilePattern(d,b,c,e),h=this;this.format=function(a){return h._format(f,a)}}function h(a){return 400*a/146097}function i(a,b){b=b||{},D(a)&&(a=a.concat()),A(this,"_locale",{value:this._resolveLocale(a)}),A(this,"_locales",{value:a}),A(this,"_options",{value:{style:this._resolveStyle(b.style),units:this._isValidUnits(b.units)&&b.units}}),A(this,"_messages",{value:B(null)});var c=this;this.format=function(a){return c._format(a)}}function j(a){var b=R(null);return function(){var c=Array.prototype.slice.call(arguments),d=k(c),e=d&&b[d];return e||(e=R(a.prototype),a.apply(e,c),d&&(b[d]=e)),e}}function k(a){if("undefined"!=typeof JSON){var b,c,d,e=[];for(b=0,c=a.length;c>b;b+=1)d=a[b],e.push(d&&"object"==typeof d?l(d):d);return JSON.stringify(e)}}function l(a){var b,c,d,e,f=[],g=[];for(b in a)a.hasOwnProperty(b)&&g.push(b);var h=g.sort();for(c=0,d=h.length;d>c;c+=1)b=h[c],e={},e[b]=a[b],f[c]=e;return f}function m(a,b){if(!isFinite(a))throw new TypeError(b)}function n(a){w.__addLocaleData(a),L.__addLocaleData(a)}var o=Object.prototype.hasOwnProperty,p=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),q=(!p&&!Object.prototype.__defineGetter__,p?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!o.call(a,b)||"value"in c)&&(a[b]=c.value)}),r=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)o.call(b,e)&&q(d,e,b[e]);return d},s=b;b.prototype.compile=function(a){return this.pluralStack=[],this.currentPlural=null,this.pluralNumberFormat=null,this.compileMessage(a)},b.prototype.compileMessage=function(a){if(!a||"messageFormatPattern"!==a.type)throw new Error('Message AST is not of type: "messageFormatPattern"');var b,c,d,e=a.elements,f=[];for(b=0,c=e.length;c>b;b+=1)switch(d=e[b],d.type){case"messageTextElement":f.push(this.compileMessageText(d));break;case"argumentElement":f.push(this.compileArgument(d));break;default:throw new Error("Message element does not have a valid type")}return f},b.prototype.compileMessageText=function(a){return this.currentPlural&&/(^|[^\\])#/g.test(a.value)?(this.pluralNumberFormat||(this.pluralNumberFormat=new Intl.NumberFormat(this.locales)),new e(this.currentPlural.id,this.currentPlural.format.offset,this.pluralNumberFormat,a.value)):a.value.replace(/\\#/g,"#")},b.prototype.compileArgument=function(a){var b=a.format;if(!b)return new c(a.id);var e,g=this.formats,h=this.locales,i=this.pluralFn;switch(b.type){case"numberFormat":return e=g.number[b.style],{id:a.id,format:new Intl.NumberFormat(h,e).format};case"dateFormat":return e=g.date[b.style],{id:a.id,format:new Intl.DateTimeFormat(h,e).format};case"timeFormat":return e=g.time[b.style],{id:a.id,format:new Intl.DateTimeFormat(h,e).format};case"pluralFormat":return e=this.compileOptions(a),new d(a.id,b.offset,e,i);case"selectFormat":return e=this.compileOptions(a),new f(a.id,e);default:throw new Error("Message element does not have a valid format type")}},b.prototype.compileOptions=function(a){var b=a.format,c=b.options,d={};this.pluralStack.push(this.currentPlural),this.currentPlural="pluralFormat"===b.type?a:null;var e,f,g;for(e=0,f=c.length;f>e;e+=1)g=c[e],d[g.selector]=this.compileMessage(g.value);return this.currentPlural=this.pluralStack.pop(),d},c.prototype.format=function(a){return a?"string"==typeof a?a:String(a):""},d.prototype.getOption=function(a){var b=this.options,c=b["="+a]||b[this.pluralFn(a-this.offset)];return c||b.other},e.prototype.format=function(a){var b=this.numberFormat.format(a-this.offset);return this.string.replace(/(^|[^\\])#/g,"$1"+b).replace(/\\#/g,"#")},f.prototype.getOption=function(a){var b=this.options;return b[a]||b.other};var t=function(){function a(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}function b(a,b,c,d,e,f){this.message=a,this.expected=b,this.found=c,this.offset=d,this.line=e,this.column=f,this.name="SyntaxError"}function c(a){function c(b){function c(b,c,d){var e,f;for(e=c;d>e;e++)f=a.charAt(e),"\n"===f?(b.seenCR||b.line++,b.column=1,b.seenCR=!1):"\r"===f||"\u2028"===f||"\u2029"===f?(b.line++,b.column=1,b.seenCR=!0):(b.column++,b.seenCR=!1)}return Ob!==b&&(Ob>b&&(Ob=0,Pb={line:1,column:1,seenCR:!1}),c(Pb,Ob,b),Ob=b),Pb}function d(a){Qb>Mb||(Mb>Qb&&(Qb=Mb,Rb=[]),Rb.push(a))}function e(d,e,f){function g(a){var b=1;for(a.sort(function(a,b){return a.description<b.description?-1:a.description>b.description?1:0});b<a.length;)a[b-1]===a[b]?a.splice(b,1):b++}function h(a,b){function c(a){function b(a){return a.charCodeAt(0).toString(16).toUpperCase()}return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,function(a){return"\\x0"+b(a)}).replace(/[\x10-\x1F\x80-\xFF]/g,function(a){return"\\x"+b(a)}).replace(/[\u0180-\u0FFF]/g,function(a){return"\\u0"+b(a)}).replace(/[\u1080-\uFFFF]/g,function(a){return"\\u"+b(a)})}var d,e,f,g=new Array(a.length);for(f=0;f<a.length;f++)g[f]=a[f].description;return d=a.length>1?g.slice(0,-1).join(", ")+" or "+g[a.length-1]:g[0],e=b?'"'+c(b)+'"':"end of input","Expected "+d+" but "+e+" found."}var i=c(f),j=f<a.length?a.charAt(f):null;return null!==e&&g(e),new b(null!==d?d:h(e,j),e,j,f,i.line,i.column)}function f(){var a;return a=g()}function g(){var a,b,c;for(a=Mb,b=[],c=h();c!==C;)b.push(c),c=h();return b!==C&&(Nb=a,b=F(b)),a=b}function h(){var a;return a=j(),a===C&&(a=l()),a}function i(){var b,c,d,e,f,g;if(b=Mb,c=[],d=Mb,e=u(),e!==C?(f=z(),f!==C?(g=u(),g!==C?(e=[e,f,g],d=e):(Mb=d,d=G)):(Mb=d,d=G)):(Mb=d,d=G),d!==C)for(;d!==C;)c.push(d),d=Mb,e=u(),e!==C?(f=z(),f!==C?(g=u(),g!==C?(e=[e,f,g],d=e):(Mb=d,d=G)):(Mb=d,d=G)):(Mb=d,d=G);else c=G;return c!==C&&(Nb=b,c=H(c)),b=c,b===C&&(b=Mb,c=t(),c!==C&&(c=a.substring(b,Mb)),b=c),b}function j(){var a,b;return a=Mb,b=i(),b!==C&&(Nb=a,b=I(b)),a=b}function k(){var b,c,e;if(b=x(),b===C){if(b=Mb,c=[],J.test(a.charAt(Mb))?(e=a.charAt(Mb),Mb++):(e=C,0===Sb&&d(K)),e!==C)for(;e!==C;)c.push(e),J.test(a.charAt(Mb))?(e=a.charAt(Mb),Mb++):(e=C,0===Sb&&d(K));else c=G;c!==C&&(c=a.substring(b,Mb)),b=c}return b}function l(){var b,c,e,f,g,h,i,j,l;return b=Mb,123===a.charCodeAt(Mb)?(c=L,Mb++):(c=C,0===Sb&&d(M)),c!==C?(e=u(),e!==C?(f=k(),f!==C?(g=u(),g!==C?(h=Mb,44===a.charCodeAt(Mb)?(i=O,Mb++):(i=C,0===Sb&&d(P)),i!==C?(j=u(),j!==C?(l=m(),l!==C?(i=[i,j,l],h=i):(Mb=h,h=G)):(Mb=h,h=G)):(Mb=h,h=G),h===C&&(h=N),h!==C?(i=u(),i!==C?(125===a.charCodeAt(Mb)?(j=Q,Mb++):(j=C,0===Sb&&d(R)),j!==C?(Nb=b,c=S(f,h),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function m(){var a;return a=n(),a===C&&(a=o(),a===C&&(a=p())),a}function n(){var b,c,e,f,g,h,i;return b=Mb,a.substr(Mb,6)===T?(c=T,Mb+=6):(c=C,0===Sb&&d(U)),c===C&&(a.substr(Mb,4)===V?(c=V,Mb+=4):(c=C,0===Sb&&d(W)),c===C&&(a.substr(Mb,4)===X?(c=X,Mb+=4):(c=C,0===Sb&&d(Y)))),c!==C?(e=u(),e!==C?(f=Mb,44===a.charCodeAt(Mb)?(g=O,Mb++):(g=C,0===Sb&&d(P)),g!==C?(h=u(),h!==C?(i=z(),i!==C?(g=[g,h,i],f=g):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G),f===C&&(f=N),f!==C?(Nb=b,c=Z(c,f),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function o(){var b,c,e,f,g,h,i,j,k;if(b=Mb,a.substr(Mb,6)===$?(c=$,Mb+=6):(c=C,0===Sb&&d(_)),c!==C)if(e=u(),e!==C)if(44===a.charCodeAt(Mb)?(f=O,Mb++):(f=C,0===Sb&&d(P)),f!==C)if(g=u(),g!==C)if(h=s(),h===C&&(h=N),h!==C)if(i=u(),i!==C){if(j=[],k=r(),k!==C)for(;k!==C;)j.push(k),k=r();else j=G;j!==C?(Nb=b,c=ab(h,j),b=c):(Mb=b,b=G)}else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;return b}function p(){var b,c,e,f,g,h,i;if(b=Mb,a.substr(Mb,6)===bb?(c=bb,Mb+=6):(c=C,0===Sb&&d(cb)),c!==C)if(e=u(),e!==C)if(44===a.charCodeAt(Mb)?(f=O,Mb++):(f=C,0===Sb&&d(P)),f!==C)if(g=u(),g!==C){if(h=[],i=r(),i!==C)for(;i!==C;)h.push(i),i=r();else h=G;h!==C?(Nb=b,c=db(h),b=c):(Mb=b,b=G)}else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;return b}function q(){var b,c,e,f;return b=Mb,c=Mb,61===a.charCodeAt(Mb)?(e=eb,Mb++):(e=C,0===Sb&&d(fb)),e!==C?(f=x(),f!==C?(e=[e,f],c=e):(Mb=c,c=G)):(Mb=c,c=G),c!==C&&(c=a.substring(b,Mb)),b=c,b===C&&(b=z()),b}function r(){var b,c,e,f,h,i,j,k,l;return b=Mb,c=u(),c!==C?(e=q(),e!==C?(f=u(),f!==C?(123===a.charCodeAt(Mb)?(h=L,Mb++):(h=C,0===Sb&&d(M)),h!==C?(i=u(),i!==C?(j=g(),j!==C?(k=u(),k!==C?(125===a.charCodeAt(Mb)?(l=Q,Mb++):(l=C,0===Sb&&d(R)),l!==C?(Nb=b,c=gb(e,j),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function s(){var b,c,e,f;return b=Mb,a.substr(Mb,7)===hb?(c=hb,Mb+=7):(c=C,0===Sb&&d(ib)),c!==C?(e=u(),e!==C?(f=x(),f!==C?(Nb=b,c=jb(f),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function t(){var b,c;if(Sb++,b=[],lb.test(a.charAt(Mb))?(c=a.charAt(Mb),Mb++):(c=C,0===Sb&&d(mb)),c!==C)for(;c!==C;)b.push(c),lb.test(a.charAt(Mb))?(c=a.charAt(Mb),Mb++):(c=C,0===Sb&&d(mb));else b=G;return Sb--,b===C&&(c=C,0===Sb&&d(kb)),b}function u(){var b,c,e;for(Sb++,b=Mb,c=[],e=t();e!==C;)c.push(e),e=t();return c!==C&&(c=a.substring(b,Mb)),b=c,Sb--,b===C&&(c=C,0===Sb&&d(nb)),b}function v(){var b;return ob.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(pb)),b}function w(){var b;return qb.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(rb)),b}function x(){var b,c,e,f,g,h;if(b=Mb,48===a.charCodeAt(Mb)?(c=sb,Mb++):(c=C,0===Sb&&d(tb)),c===C){if(c=Mb,e=Mb,ub.test(a.charAt(Mb))?(f=a.charAt(Mb),Mb++):(f=C,0===Sb&&d(vb)),f!==C){for(g=[],h=v();h!==C;)g.push(h),h=v();g!==C?(f=[f,g],e=f):(Mb=e,e=G)}else Mb=e,e=G;e!==C&&(e=a.substring(c,Mb)),c=e}return c!==C&&(Nb=b,c=wb(c)),b=c}function y(){var b,c,e,f,g,h,i,j;return xb.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(yb)),b===C&&(b=Mb,a.substr(Mb,2)===zb?(c=zb,Mb+=2):(c=C,0===Sb&&d(Ab)),c!==C&&(Nb=b,c=Bb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Cb?(c=Cb,Mb+=2):(c=C,0===Sb&&d(Db)),c!==C&&(Nb=b,c=Eb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Fb?(c=Fb,Mb+=2):(c=C,0===Sb&&d(Gb)),c!==C&&(Nb=b,c=Hb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Ib?(c=Ib,Mb+=2):(c=C,0===Sb&&d(Jb)),c!==C?(e=Mb,f=Mb,g=w(),g!==C?(h=w(),h!==C?(i=w(),i!==C?(j=w(),j!==C?(g=[g,h,i,j],f=g):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G),f!==C&&(f=a.substring(e,Mb)),e=f,e!==C?(Nb=b,c=Kb(e),b=c):(Mb=b,b=G)):(Mb=b,b=G))))),b}function z(){var a,b,c;if(a=Mb,b=[],c=y(),c!==C)for(;c!==C;)b.push(c),c=y();else b=G;return b!==C&&(Nb=a,b=Lb(b)),a=b}var A,B=arguments.length>1?arguments[1]:{},C={},D={start:f},E=f,F=function(a){return{type:"messageFormatPattern",elements:a}},G=C,H=function(a){var b,c,d,e,f,g="";for(b=0,d=a.length;d>b;b+=1)for(e=a[b],c=0,f=e.length;f>c;c+=1)g+=e[c];return g},I=function(a){return{type:"messageTextElement",value:a}},J=/^[^ \t\n\r,.+={}#]/,K={type:"class",value:"[^ \\t\\n\\r,.+={}#]",description:"[^ \\t\\n\\r,.+={}#]"},L="{",M={type:"literal",value:"{",description:'"{"'},N=null,O=",",P={type:"literal",value:",",description:'","'},Q="}",R={type:"literal",value:"}",description:'"}"'},S=function(a,b){return{type:"argumentElement",id:a,format:b&&b[2]}},T="number",U={type:"literal",value:"number",description:'"number"'},V="date",W={type:"literal",value:"date",description:'"date"'},X="time",Y={type:"literal",value:"time",description:'"time"'},Z=function(a,b){return{type:a+"Format",style:b&&b[2]}},$="plural",_={type:"literal",value:"plural",description:'"plural"'},ab=function(a,b){return{type:"pluralFormat",offset:a||0,options:b}},bb="select",cb={type:"literal",value:"select",description:'"select"'},db=function(a){return{type:"selectFormat",options:a}},eb="=",fb={type:"literal",value:"=",description:'"="'},gb=function(a,b){return{type:"optionalFormatPattern",selector:a,value:b}},hb="offset:",ib={type:"literal",value:"offset:",description:'"offset:"'},jb=function(a){return a},kb={type:"other",description:"whitespace"},lb=/^[ \t\n\r]/,mb={type:"class",value:"[ \\t\\n\\r]",description:"[ \\t\\n\\r]"},nb={type:"other",description:"optionalWhitespace"},ob=/^[0-9]/,pb={type:"class",value:"[0-9]",description:"[0-9]"},qb=/^[0-9a-f]/i,rb={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},sb="0",tb={type:"literal",value:"0",description:'"0"'},ub=/^[1-9]/,vb={type:"class",value:"[1-9]",description:"[1-9]"},wb=function(a){return parseInt(a,10)},xb=/^[^{}\\\0-\x1F \t\n\r]/,yb={type:"class",value:"[^{}\\\\\\0-\\x1F \\t\\n\\r]",description:"[^{}\\\\\\0-\\x1F \\t\\n\\r]"},zb="\\#",Ab={type:"literal",value:"\\#",description:'"\\\\#"'},Bb=function(){return"\\#"},Cb="\\{",Db={type:"literal",value:"\\{",description:'"\\\\{"'},Eb=function(){return"{"},Fb="\\}",Gb={type:"literal",value:"\\}",description:'"\\\\}"'},Hb=function(){return"}"},Ib="\\u",Jb={type:"literal",value:"\\u",description:'"\\\\u"'},Kb=function(a){return String.fromCharCode(parseInt(a,16))},Lb=function(a){return a.join("")},Mb=0,Nb=0,Ob=0,Pb={line:1,column:1,seenCR:!1},Qb=0,Rb=[],Sb=0;if("startRule"in B){if(!(B.startRule in D))throw new Error("Can't start parsing from rule \""+B.startRule+'".');E=D[B.startRule]}if(A=E(),A!==C&&Mb===a.length)return A;throw A!==C&&Mb<a.length&&d({type:"end",description:"end of input"}),e(null,Rb,Qb)}return a(b,Error),{SyntaxError:b,parse:c}}(),u=g;q(g,"formats",{enumerable:!0,value:{number:{currency:{style:"currency"},percent:{style:"percent"}},date:{"short":{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},"long":{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{"short":{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},"long":{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}}}),q(g,"__localeData__",{value:r(null)}),q(g,"__addLocaleData",{value:function(a){if(!a||!a.locale)throw new Error("Locale data provided to IntlMessageFormat is missing a `locale` property");if(!a.pluralRuleFunction)throw new Error("Locale data provided to IntlMessageFormat is missing a `pluralRuleFunction` property");var b=a.locale.toLowerCase().split("-")[0];g.__localeData__[b]=a}}),q(g,"__parse",{value:t.parse}),q(g,"defaultLocale",{enumerable:!0,writable:!0,value:void 0}),g.prototype.resolvedOptions=function(){return{locale:this._locale}},g.prototype._compilePattern=function(a,b,c,d){var e=new s(b,c,d);return e.compile(a)},g.prototype._format=function(a,b){var c,d,e,f,g,h="";for(c=0,d=a.length;d>c;c+=1)if(e=a[c],"string"!=typeof e){if(f=e.id,!b||!o.call(b,f))throw new Error("A value must be provided for: "+f);g=b[f],h+=e.options?this._format(e.getOption(g),b):e.format(g)}else h+=e;return h},g.prototype._mergeFormats=function(b,c){var d,e,f={};for(d in b)o.call(b,d)&&(f[d]=e=r(b[d]),c&&o.call(c,d)&&a(e,c[d]));return f},g.prototype._resolveLocale=function(a){a||(a=g.defaultLocale),"string"==typeof a&&(a=[a]);var b,c,d,e=g.__localeData__;for(b=0,c=a.length;c>b;b+=1){if(d=a[b].split("-")[0].toLowerCase(),!/[a-z]{2,3}/.test(d))throw new Error("Language tag provided to IntlMessageFormat is not structrually valid: "+d);if(o.call(e,d))return d}throw new Error("No locale data has been added to IntlMessageFormat for: "+a.join(", "))};var v={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"}};u.__addLocaleData(v),u.defaultLocale="en";var w=u,x=Object.prototype.hasOwnProperty,y=Object.prototype.toString,z=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),A=(!z&&!Object.prototype.__defineGetter__,z?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!x.call(a,b)||"value"in c)&&(a[b]=c.value)}),B=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)x.call(b,e)&&A(d,e,b[e]);return d},C=Array.prototype.indexOf||function(a,b){var c=this;if(!c.length)return-1;for(var d=b||0,e=c.length;e>d;d++)if(c[d]===a)return d;return-1},D=Array.isArray||function(a){return"[object Array]"===y.call(a)},E=Date.now||function(){return(new Date).getTime()},F=Math.round,G=function(a,b){a=+a,b=+b;var c=F(b-a),d=F(c/1e3),e=F(d/60),f=F(e/60),g=F(f/24),i=F(g/7),j=h(g),k=F(12*j),l=F(j);return{millisecond:c,second:d,minute:e,hour:f,day:g,week:i,month:k,year:l}},H=i,I=["second","minute","hour","day","month","year"],J=["best fit","numeric"];A(i,"__localeData__",{value:B(null)}),A(i,"__addLocaleData",{value:function(a){if(!a||!a.locale)throw new Error("Locale data provided to IntlRelativeFormat is missing a `locale` property value");if(!a.fields)throw new Error("Locale data provided to IntlRelativeFormat is missing a `fields` property value");w.__addLocaleData(a);var b=a.locale.toLowerCase().split("-")[0];i.__localeData__[b]=a}}),A(i,"defaultLocale",{enumerable:!0,writable:!0,value:void 0}),A(i,"thresholds",{enumerable:!0,value:{second:45,minute:45,hour:22,day:26,month:11}}),i.prototype.resolvedOptions=function(){return{locale:this._locale,style:this._options.style,units:this._options.units}},i.prototype._compileMessage=function(a){var b,c=this._locales,d=this._locale,e=i.__localeData__,f=e[d].fields[a],g=f.relativeTime,h="",j="";for(b in g.future)g.future.hasOwnProperty(b)&&(h+=" "+b+" {"+g.future[b].replace("{0}","#")+"}");for(b in g.past)g.past.hasOwnProperty(b)&&(j+=" "+b+" {"+g.past[b].replace("{0}","#")+"}");var k="{when, select, future {{0, plural, "+h+"}}past {{0, plural, "+j+"}}}";return new w(k,c)},i.prototype._format=function(a){var b=E();if(void 0===a&&(a=b),!isFinite(a))throw new RangeError("The date value provided to IntlRelativeFormat#format() is not in valid range.");var c=G(b,a),d=this._options.units||this._selectUnits(c),e=c[d];if("numeric"!==this._options.style){var f=this._resolveRelativeUnits(e,d);if(f)return f}return this._resolveMessage(d).format({0:Math.abs(e),when:0>e?"past":"future"})},i.prototype._isValidUnits=function(a){if(!a||C.call(I,a)>=0)return!0;if("string"==typeof a){var b=/s$/.test(a)&&a.substr(0,a.length-1);if(b&&C.call(I,b)>=0)throw new Error('"'+a+'" is not a valid IntlRelativeFormat `units` value, did you mean: '+b)}throw new Error('"'+a+'" is not a valid IntlRelativeFormat `units` value, it must be one of: "'+I.join('", "')+'"')},i.prototype._resolveLocale=function(a){a||(a=i.defaultLocale),"string"==typeof a&&(a=[a]);var b,c,d,e=Object.prototype.hasOwnProperty,f=i.__localeData__;for(b=0,c=a.length;c>b;b+=1){if(d=a[b].split("-")[0].toLowerCase(),!/[a-z]{2,3}/.test(d))throw new Error("Language tag provided to IntlRelativeFormat is not structrually valid: "+d);if(e.call(f,d))return d}throw new Error("No locale data has been added to IntlRelativeFormat for: "+a.join(", "))},i.prototype._resolveMessage=function(a){var b=this._messages;return b[a]||(b[a]=this._compileMessage(a)),b[a]},i.prototype._resolveRelativeUnits=function(a,b){var c=i.__localeData__[this._locale].fields[b];return c.relative?c.relative[a]:void 0},i.prototype._resolveStyle=function(a){if(!a)return J[0];if(C.call(J,a)>=0)return a;throw new Error('"'+a+'" is not a valid IntlRelativeFormat `style` value, it must be one of: "'+J.join('", "')+'"')},i.prototype._selectUnits=function(a){var b,c,d;for(b=0,c=I.length;c>b&&(d=I[b],!(Math.abs(a[d])<i.thresholds[d]));b+=1);return d};var K={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"in {0} second",other:"in {0} seconds"},past:{one:"{0} second ago",other:"{0} seconds ago"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"in {0} minute",other:"in {0} minutes"},past:{one:"{0} minute ago",other:"{0} minutes ago"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"in {0} hour",other:"in {0} hours"},past:{one:"{0} hour ago",other:"{0} hours ago"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"in {0} day",other:"in {0} days"},past:{one:"{0} day ago",other:"{0} days ago"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"in {0} month",other:"in {0} months"},past:{one:"{0} month ago",other:"{0} months ago"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"in {0} year",other:"in {0} years"},past:{one:"{0} year ago",other:"{0} years ago"}}}}};H.__addLocaleData(K),H.defaultLocale="en";var L=H,M={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"in {0} second",other:"in {0} seconds"},past:{one:"{0} second ago",other:"{0} seconds ago"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"in {0} minute",other:"in {0} minutes"},past:{one:"{0} minute ago",other:"{0} minutes ago"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"in {0} hour",other:"in {0} hours"},past:{one:"{0} hour ago",other:"{0} hours ago"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"in {0} day",other:"in {0} days"},past:{one:"{0} day ago",other:"{0} days ago"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"in {0} month",other:"in {0} months"},past:{one:"{0} month ago",other:"{0} months ago"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"in {0} year",other:"in {0} years"},past:{one:"{0} year ago",other:"{0} years ago"}}}}},N=React,O=Object.prototype.hasOwnProperty,P=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),Q=(!P&&!Object.prototype.__defineGetter__,P?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!O.call(a,b)||"value"in c)&&(a[b]=c.value)}),R=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)O.call(b,e)&&Q(d,e,b[e]);return d},S=j,T={locales:N.PropTypes.oneOfType([N.PropTypes.string,N.PropTypes.array]),formats:N.PropTypes.object,messages:N.PropTypes.object},U={statics:{filterFormatOptions:function(a,b){return b||(b={}),(this.formatOptions||[]).reduce(function(c,d){return a.hasOwnProperty(d)?c[d]=a[d]:b.hasOwnProperty(d)&&(c[d]=b[d]),c},{})}},propsTypes:T,contextTypes:T,childContextTypes:T,getNumberFormat:S(Intl.NumberFormat),getDateTimeFormat:S(Intl.DateTimeFormat),getMessageFormat:S(w),getRelativeFormat:S(L),getChildContext:function(){var a=this.context,b=this.props;return{locales:b.locales||a.locales,formats:b.formats||a.formats,messages:b.messages||a.messages}},formatDate:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatDate()"),this._format("date",a,b)},formatTime:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatTime()"),this._format("time",a,b)},formatRelative:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatRelative()"),this._format("relative",a,b)},formatNumber:function(a,b){return this._format("number",a,b)},formatMessage:function(a,b){var c=this.props.locales||this.context.locales,d=this.props.formats||this.context.formats;return"function"==typeof a?a(b):("string"==typeof a&&(a=this.getMessageFormat(a,c,d)),a.format(b))},getIntlMessage:function(a){var b,c=this.props.messages||this.context.messages,d=a.split(".");try{b=d.reduce(function(a,b){return a[b]},c)}finally{if(void 0===b)throw new ReferenceError("Could not find Intl message: "+a)}return b},getNamedFormat:function(a,b){var c=this.props.formats||this.context.formats,d=null;try{d=c[a][b]}finally{if(!d)throw new ReferenceError("No "+a+" format named: "+b)}return d},_format:function(a,b,c){var d=this.props.locales||this.context.locales;switch(c&&"string"==typeof c&&(c=this.getNamedFormat(a,c)),a){case"date":case"time":return this.getDateTimeFormat(d,c).format(b);case"number":return this.getNumberFormat(d,c).format(b);case"relative":return this.getRelativeFormat(d,c).format(b);default:throw new Error("Unrecognized format type: "+a)}}},V=N.createClass({displayName:"FormattedDate",mixins:[U],statics:{formatOptions:["localeMatcher","timeZone","hour12","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("date",c),e=V.filterFormatOptions(a,d);return N.DOM.span(null,this.formatDate(b,e))}}),W=V,X=N.createClass({displayName:"FormattedTime",mixins:[U],statics:{formatOptions:["localeMatcher","timeZone","hour12","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("time",c),e=X.filterFormatOptions(a,d);return N.DOM.span(null,this.formatTime(b,e))}}),Y=X,Z=N.createClass({displayName:"FormattedRelative",mixins:[U],statics:{formatOptions:["style","units"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("relative",c),e=Z.filterFormatOptions(a,d);return N.DOM.span(null,this.formatRelative(b,e))}}),$=Z,_=N.createClass({displayName:"FormattedNumber",mixins:[U],statics:{formatOptions:["localeMatcher","style","currency","currencyDisplay","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("number",c),e=_.filterFormatOptions(a,d);return N.DOM.span(null,this.formatNumber(b,e))}}),ab=_,bb=N.createClass({displayName:"FormattedMessage",mixins:[U],propTypes:{tagName:N.PropTypes.string,message:N.PropTypes.string.isRequired},getDefaultProps:function(){return{tagName:"span"}},render:function(){var a=this.props,b=a.tagName,c=a.message,d=Math.floor(1099511627776*Math.random()).toString(16),e=new RegExp("(@__ELEMENT-"+d+"-\\d+__@)","g"),f={},g=function(){var a=0;return function(){return"@__ELEMENT-"+d+"-"+(a+=1)+"__@"}}(),h=Object.keys(a).reduce(function(b,c){var d,e=a[c];return N.isValidElement(e)?(d=g(),b[c]=d,f[d]=e):b[c]=e,b},{}),i=this.formatMessage(c,h),j=i.split(e).filter(function(a){return!!a}).map(function(a){return f[a]||a}),k=[b,null].concat(j);return N.createElement.apply(null,k)}}),cb=bb,db={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},eb=/[&><"']/g,fb=function(a){return(""+a).replace(eb,function(a){return db[a]})},gb=N.createClass({displayName:"FormattedHTMLMessage",mixins:[U],propTypes:{tagName:N.PropTypes.string,message:N.PropTypes.string.isRequired},getDefaultProps:function(){return{tagName:"span"}},render:function(){var a=this.props,b=a.tagName,c=a.message,d=Object.keys(a).reduce(function(b,c){var d=a[c];return"string"==typeof d?d=fb(d):N.isValidElement(d)&&(d=N.renderToStaticMarkup(d)),b[c]=d,b},{});return N.DOM[b]({dangerouslySetInnerHTML:{__html:this.formatMessage(c,d)}})}}),hb=gb;n(M);var ib={IntlMixin:U,FormattedDate:W,FormattedTime:Y,FormattedRelative:$,FormattedNumber:ab,FormattedMessage:cb,FormattedHTMLMessage:hb,__addLocaleData:n};"undefined"!=typeof window&&(window.ReactIntlMixin=U,U.__addLocaleData=n),this.ReactIntl=ib}).call(this); //# sourceMappingURL=react-intl.min.js.map
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatAlignCenter = (props) => ( <SvgIcon {...props}> <path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"/> </SvgIcon> ); EditorFormatAlignCenter = pure(EditorFormatAlignCenter); EditorFormatAlignCenter.displayName = 'EditorFormatAlignCenter'; EditorFormatAlignCenter.muiName = 'SvgIcon'; export default EditorFormatAlignCenter;
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":4,"../lib/Shim.IE8":27}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),!0}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,e){e=e||[],this._left&&this._left.findRange(a,b,c,d,e);var f=this.sortAsc(this._data[b],c),g=this.sortAsc(this._data[b],d);if(!(0!==f&&1!==f||0!==g&&-1!==g))switch(a){case"hash":e.push(this._hash);break;case"data":e.push(this._data);break;default:e.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,e),e},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._index),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":23,"./Shared":26}],3:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},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},this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),d.mixin(n.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" 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: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[p]),q=!0;break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this._onChange(),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H=this._metrics.create("find"),I=this.primaryKey(),J=this,K=!0,L={},M=[],N=[],O=[],P={},Q={},R=function(c){return J._match(c,a,b,"and",P)};if(H.start(),a){if(H.time("analyseQuery"),c=this._analyseQuery(J.decouple(a),b,H),H.time("analyseQuery"),H.data("analysis",c),c.hasJoin&&c.queriesJoin){for(H.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],L[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];H.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(H.data("index.potential",c.indexMatch),H.data("index.used",c.indexMatch[0].index),H.time("indexLookup"),e=c.indexMatch[0].lookup||[],H.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(K=!1)):H.flag("usedIndex",!1),K&&(e&&e.length?(d=e.length,H.time("tableScan: "+d),e=e.filter(R)):(d=this._data.length,H.time("tableScan: "+d),e=this._data.filter(R)),H.time("tableScan: "+d)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(Q.page=b.$page,Q.pages=Math.ceil(e.length/b.$limit),Q.records=e.length,b.$page&&b.$limit>0&&(H.data("cursor",Q),e.splice(0,b.$page*b.$limit))),b.$skip&&(Q.skip=b.$skip,e.splice(0,b.$skip),H.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(Q.limit=b.$limit,e.length=b.$limit,H.data("limit",b.$limit)),b.$decouple&&(H.time("decouple"),e=this.decouple(e),H.time("decouple"),H.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=L[k]?L[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=m[n].query),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=J._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else M.push(e[x])}H.data("flag.join",!0)}if(M.length){for(H.time("removalQueue"),z=0;z<M.length;z++)y=e.indexOf(M[z]),y>-1&&e.splice(y,1);H.time("removalQueue")}if(b.$transform){for(H.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));H.time("transform"),H.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(H.time("transformOut"),e=this.transformOut(e),H.time("transformOut")),H.data("results",e.length)}else e=[];H.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?N.push(z):0===b[z]&&O.push(z));if(H.time("scanFields"),N.length||O.length){for(H.data("flag.limitFields",!0),H.data("limitFields.on",N),H.data("limitFields.off",O),H.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(N.length&&A!==I&&-1===N.indexOf(A)&&delete G[A],O.length&&O.indexOf(A)>-1&&delete G[A])}H.time("limitFields")}if(b.$elemMatch){H.data("flag.elemMatch",!0),H.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(J._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}H.time("projection-elemMatch")}if(b.$elemsMatch){H.data("flag.elemsMatch",!0),H.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)J._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}H.time("projection-elemsMatch")}return H.stop(),e.__fdbOp=H,e.$cursor=Q,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g=this;if("string"==typeof a)return"$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b)[0]:new h(a).value(b)[0];c={};for(f in a)if(a.hasOwnProperty(f))switch(d=typeof a[f],e=a[f],d){case"string":"$$."===e.substr(0,3)?c[f]=new h(e.substr(3,e.length-3)).value(b)[0]:c[f]=e;break;case"object":c[f]=g._resolveDynamicQuery(e,b);break;default:c[f]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=String(c),e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update); break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":26}],4:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.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"},b.exports=i},{"./Db.js":6,"./Metrics.js":10,"./Overload":22,"./Shared":26}],5:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":22,"./Shared":26}],7:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(h.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},i.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},i.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},i.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},i.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},i.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=i},{"./BinaryTree":2,"./Path":23,"./Shared":26}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":23,"./Shared":26}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":26}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":21,"./Shared":26}],11:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],12:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],13:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":22,"./Serialiser":25}],14:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],15:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":22}],16:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){for(k in b)if(b.hasOwnProperty(k)){if(f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++){if(i[h]instanceof RegExp&&i[h].test(b))return!0;if(i[h]===b)return!0}return!1}throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(l[k]===b)return!1;return!0}throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0}return-1}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],19:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1; }};b.exports=e},{"./Overload":22}],20:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":23,"./Shared":26}],22:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":26}],24:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":26}],25:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.382",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Tags":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],27:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]);
;(function(exports) { if (exports.F2 && !exports.F2_TESTING_MODE) { return; } /*! JSON.org requires the following notice to accompany json2: Copyright (c) 2002 JSON.org http://json.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* 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 '&nbsp;'), 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. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; 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 (key) { 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 (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, 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') { 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') { 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'); }; } }()); /*! * jQuery JavaScript Library v1.10.2 * 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-07-03T13:48Z */ (function( window, undefined ) { // 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+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // 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, // 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-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/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(); }, // The ready event handler completed = function( event ) { // 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(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { 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 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 rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_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 this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // 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 ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_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] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; 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; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // 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 ( length === i ) { 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 // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // 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"); } }, // 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 ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, 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 && !core_hasOwn.call(obj, "constructor") && !core_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 ( jQuery.support.ownLast ) { for ( key in obj ) { return core_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 || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // 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 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 ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing 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; }, noop: function() {}, // 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: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_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 { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_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 l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // 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 if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_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 = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_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; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function 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; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. 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; } }); 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 ); }; // 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 ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // 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(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } 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 + "*" ), rsibling = new RegExp( 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" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, 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 : // BMP codepoint high < 0 ? 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 #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 ) && 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]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ 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; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * 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 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.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", 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 = 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><option selected=''></option></select>"; // 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: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + 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 ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? 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 = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // 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 || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else 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 ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; 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 ); } } 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 for ( ; (node = elem[i]); 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 (see #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 only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { 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; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // 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, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); 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 for ( ; (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 ) && 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 ) ); 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 (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } 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; })( window ); // 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( core_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 action = tuple[ 0 ], 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[ action + "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 = core_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 ? core_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(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // 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; // 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"; // 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; // 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; // 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>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // 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: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // 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"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.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() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; 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 support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;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() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // 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"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_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.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // 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 = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; 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 ] = core_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 ( jQuery.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 throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which 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 ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // 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" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; 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 ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); 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; } 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 ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ 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 ); }; }); }, 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 nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.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 ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, 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( core_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 + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, 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( core_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 + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } 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( core_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 === core_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; }, val: function( value ) { var ret, hooks, 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 ( jQuery.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; } } }, 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 === core_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( core_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 ( !jQuery.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; } } } }, 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; } } } }); // 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 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; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : 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) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, 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; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.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 ); } }; }); } if ( !jQuery.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 + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.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 ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // 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 ( !jQuery.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 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 !== core_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( core_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( core_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 = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_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 && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === 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 = core_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 ] === core_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.returnValue === false || 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 ( !jQuery.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 ( !jQuery.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 ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } 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 ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ 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; }, 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; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, 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; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], 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)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // 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 ); }; }); jQuery.extend({ 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; })); }, 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; } }); // 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 ( isSimple.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; }); } 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, manipulation_rcheckableType = /^(?:checkbox|radio)$/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: jQuery.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; jQuery.fn.extend({ text: function( value ) { return jQuery.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 ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { 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 jQuery.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 ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.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 // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_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" || jQuery.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, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && 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 ) { // Hope ajax is available... 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; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? 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 ( !jQuery.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 ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_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.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() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_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 ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.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 ( (!jQuery.support.noCloneEvent || !jQuery.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 ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.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 ( !jQuery.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 = jQuery.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 !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _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(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // 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]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], 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 isHidden( 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 ); } 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", css_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; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, 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(); } }); } }); 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": jQuery.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 NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( 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 ( !jQuery.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 ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { 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; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; 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; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // 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; } } return ret === "" ? "auto" : ret; }; } 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.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 && ( jQuery.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"; } // Try to determine the default display value of an element function css_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'/>") .css( "cssText", "display:block !important" ) ).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; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } 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, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.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; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: 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" ] ); } } }; } // 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 if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: 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; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { 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.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // 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; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; 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 || !manipulation_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(); } }); //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, "+" ); }; 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 ); } } 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 // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, 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+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* 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( core_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 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; } 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; }; // 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.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( core_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 += ( ajax_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_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_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 }); }; }); /* 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 }; } // 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 + "_" + ( ajax_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 += ( ajax_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"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( 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 ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.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 ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#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 && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.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 { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_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() ); } 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 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 ); } 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; } } } 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 ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, 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 if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.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" ) ) { 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 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.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 ); }; }); 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; }); } }); // 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; } // 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.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.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; 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 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.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 !== core_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 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // 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({ 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 it's 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 jQuery.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 ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // 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 jQuery.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 ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // 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; } ); } } })( window ); /*! * This file creates $ and jQuery variables within the F2 closure scope */ var $, jQuery = $ = window.jQuery.noConflict(true); /*! * Hij1nx requires the following notice to accompany EventEmitter: * * Copyright (c) 2011 hij1nx * * http://www.twitter.com/hij1nx * * Version: 2013-09-17 * GitHub SHA: 3caacce662998d7903d368b0c0f847f259cae0f7 * https://github.com/hij1nx/EventEmitter2 * Diff this version to master: https://github.com/hij1nx/EventEmitter2/compare/3caacce662998d7903d368b0c0f847f259cae0f7...master * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ ;!function(exports, undefined) { var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; var defaultMaxListeners = 10; function init() { this._events = {}; if (this._conf) { configure.call(this, this._conf); } } function configure(conf) { if (conf) { this._conf = conf; conf.delimiter && (this.delimiter = conf.delimiter); conf.maxListeners && (this._events.maxListeners = conf.maxListeners); conf.wildcard && (this.wildcard = conf.wildcard); conf.newListener && (this.newListener = conf.newListener); if (this.wildcard) { this.listenerTree = {}; } } } function EventEmitter(conf) { this._events = {}; this.newListener = false; configure.call(this, conf); } // // Attention, function return type now is array, always ! // It has zero elements if no any matches found and one or more // elements (leafs) if there are matches // function searchListenerTree(handlers, type, tree, i) { if (!tree) { return []; } var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, typeLength = type.length, currentType = type[i], nextType = type[i+1]; if (i === typeLength && tree._listeners) { // // If at the end of the event(s) list and the tree has listeners // invoke those listeners. // if (typeof tree._listeners === 'function') { handlers && handlers.push(tree._listeners); return [tree]; } else { for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { handlers && handlers.push(tree._listeners[leaf]); } return [tree]; } } if ((currentType === '*' || currentType === '**') || tree[currentType]) { // // If the event emitted is '*' at this part // or there is a concrete match at this patch // if (currentType === '*') { for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); } } return listeners; } else if(currentType === '**') { endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); if(endReached && tree._listeners) { // The next element has a _listeners, add it to the handlers. listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); } for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { if(branch === '*' || branch === '**') { if(tree[branch]._listeners && !endReached) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); } listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } else if(branch === nextType) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); } else { // No match on this one, shift into the tree but not in the type array. listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } } } return listeners; } listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); } xTree = tree['*']; if (xTree) { // // If the listener tree will allow any match for this part, // then recursively explore all branches of the tree // searchListenerTree(handlers, type, xTree, i+1); } xxTree = tree['**']; if(xxTree) { if(i < typeLength) { if(xxTree._listeners) { // If we have a listener on a '**', it will catch all, so add its handler. searchListenerTree(handlers, type, xxTree, typeLength); } // Build arrays of matching next branches and others. for(branch in xxTree) { if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { if(branch === nextType) { // We know the next element will match, so jump twice. searchListenerTree(handlers, type, xxTree[branch], i+2); } else if(branch === currentType) { // Current node matches, move into the tree. searchListenerTree(handlers, type, xxTree[branch], i+1); } else { isolatedBranch = {}; isolatedBranch[branch] = xxTree[branch]; searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); } } } } else if(xxTree._listeners) { // We have reached the end and still on a '**' searchListenerTree(handlers, type, xxTree, typeLength); } else if(xxTree['*'] && xxTree['*']._listeners) { searchListenerTree(handlers, type, xxTree['*'], typeLength); } } return listeners; } function growListenerTree(type, listener) { type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); // // Looks for two consecutive '**', if so, don't add the event at all. // for(var i = 0, len = type.length; i+1 < len; i++) { if(type[i] === '**' && type[i+1] === '**') { return; } } var tree = this.listenerTree; var name = type.shift(); while (name) { if (!tree[name]) { tree[name] = {}; } tree = tree[name]; if (type.length === 0) { if (!tree._listeners) { tree._listeners = listener; } else if(typeof tree._listeners === 'function') { tree._listeners = [tree._listeners, listener]; } else if (isArray(tree._listeners)) { tree._listeners.push(listener); if (!tree._listeners.warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && tree._listeners.length > m) { tree._listeners.warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', tree._listeners.length); console.trace(); } } } return true; } name = type.shift(); } return true; } // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.delimiter = '.'; EventEmitter.prototype.setMaxListeners = function(n) { this._events || init.call(this); this._events.maxListeners = n; if (!this._conf) this._conf = {}; this._conf.maxListeners = n; }; EventEmitter.prototype.event = ''; EventEmitter.prototype.once = function(event, fn) { this.many(event, 1, fn); return this; }; EventEmitter.prototype.many = function(event, ttl, fn) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } fn.apply(this, arguments); } listener._origin = fn; this.on(event, listener); return self; }; EventEmitter.prototype.emit = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener' && !this.newListener) { if (!this._events.newListener) { return false; } } // Loop through the *_all* functions and invoke them. if (this._all) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; for (i = 0, l = this._all.length; i < l; i++) { this.event = type; this._all[i].apply(this, args); } } // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._all && !this._events.error && !(this.wildcard && this.listenerTree.error)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } var handler; if(this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; if (arguments.length === 1) { handler.call(this); } else if (arguments.length > 1) switch (arguments.length) { case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } return true; } else if (handler) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { this.event = type; listeners[i].apply(this, args); } return (listeners.length > 0) || this._all; } else { return this._all; } }; EventEmitter.prototype.on = function(type, listener) { if (typeof type === 'function') { this.onAny(type); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if(this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if(typeof this._events[type] === 'function') { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } else if (isArray(this._events[type])) { // If we've already got an array, just append. this._events[type].push(listener); // Check for listener leak if (!this._events[type].warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } } return this; }; EventEmitter.prototype.onAny = function(fn) { if(!this._all) { this._all = []; } if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } // Add the function to the event listener collection. this._all.push(fn); return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prototype.off = function(type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { continue; } if(this.wildcard) { leaf._listeners.splice(position, 1); } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } return this; } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } return this; }; EventEmitter.prototype.offAny = function(fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); return this; } } } else { this._all = []; } return this; }; EventEmitter.prototype.removeListener = EventEmitter.prototype.off; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { !this._events || init.call(this); return this; } if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else { if (!this._events[type]) return this; this._events[type] = null; } return this; }; EventEmitter.prototype.listeners = function(type) { if(this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; EventEmitter.prototype.listenersAny = function() { if(this._all) { return this._all; } else { return []; } }; // if (typeof define === 'function' && define.amd) { // define('EventEmitter2', [], function() { // return EventEmitter; // }); // } else { exports.EventEmitter2 = EventEmitter; // } }(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window); /*! * Øyvind Sean Kinsey and others require the following notice to accompany easyXDM: * * http://easyxdm.net/ * Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) { /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */ var global = this; var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded var emptyFn = Function.prototype; var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4) var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global) var easyXDM = {}; var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite var IFRAME_PREFIX = "easyXDM_"; var HAS_NAME_PROPERTY_BUG; var useHash = false; // whether to use the hash over the query var flashVersion; // will be set if using flash var HAS_FLASH_THROTTLED_BUG; // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(object, property){ var t = typeof object[property]; return t == 'function' || (!!(t == 'object' && object[property])) || t == 'unknown'; } function isHostObject(object, property){ return !!(typeof(object[property]) == 'object' && object[property]); } // end // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ function isArray(o){ return Object.prototype.toString.call(o) === '[object Array]'; } // end function hasFlash(){ try { var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1); HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0; activeX = null; return true; } catch (notSupportedException) { return false; } } /* * Cross Browser implementation for adding and removing event listeners. */ var on, un; if (isHostMethod(window, "addEventListener")) { on = function(target, type, listener){ target.addEventListener(type, listener, false); }; un = function(target, type, listener){ target.removeEventListener(type, listener, false); }; } else if (isHostMethod(window, "attachEvent")) { on = function(object, sEvent, fpNotify){ object.attachEvent("on" + sEvent, fpNotify); }; un = function(object, sEvent, fpNotify){ object.detachEvent("on" + sEvent, fpNotify); }; } else { throw new Error("Browser not supported"); } /* * Cross Browser implementation of DOMContentLoaded. */ var domIsReady = false, domReadyQueue = [], readyState; if ("readyState" in document) { // If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and // 'interactive' (HTML5 specs, recent WebKit builds) states. // https://bugs.webkit.org/show_bug.cgi?id=45119 readyState = document.readyState; domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive")); } else { // If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately // when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not. // We only need a body to add elements to, so the existence of document.body is enough for us. domIsReady = !!document.body; } function dom_onReady(){ if (domIsReady) { return; } domIsReady = true; for (var i = 0; i < domReadyQueue.length; i++) { domReadyQueue[i](); } domReadyQueue.length = 0; } if (!domIsReady) { if (isHostMethod(window, "addEventListener")) { on(document, "DOMContentLoaded", dom_onReady); } else { on(document, "readystatechange", function(){ if (document.readyState == "complete") { dom_onReady(); } }); if (document.documentElement.doScroll && window === top) { var doScrollCheck = function(){ if (domIsReady) { return; } // http://javascript.nwbox.com/IEContentLoaded/ try { document.documentElement.doScroll("left"); } catch (e) { setTimeout(doScrollCheck, 1); return; } dom_onReady(); }; doScrollCheck(); } } // A fallback to window.onload, that will always work on(window, "load", dom_onReady); } /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {Object} scope An optional scope for the function to be called with. */ function whenReady(fn, scope){ if (domIsReady) { fn.call(scope); return; } domReadyQueue.push(function(){ fn.call(scope); }); } /** * Returns an instance of easyXDM from the parent window with * respect to the namespace. * * @return An instance of easyXDM (in the parent window) */ function getParentObject(){ var obj = parent; if (namespace !== "") { for (var i = 0, ii = namespace.split("."); i < ii.length; i++) { obj = obj[ii[i]]; } } return obj.easyXDM; } /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ function noConflict(ns){ window.easyXDM = _easyXDM; namespace = ns; if (namespace) { IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_"; } return easyXDM; } /* * Methods for working with URLs */ /** * Get the domain name from a url. * @param {String} url The url to extract the domain from. * @return The domain part of the url. * @type {String} */ function getDomainName(url){ return url.match(reURI)[3]; } /** * Get the port for a given URL, or "" if none * @param {String} url The url to extract the port from. * @return The port part of the url. * @type {String} */ function getPort(url){ return url.match(reURI)[4] || ""; } /** * Returns a string containing the schema, domain and if present the port * @param {String} url The url to extract the location from * @return {String} The location part of the url */ function getLocation(url){ var m = url.toLowerCase().match(reURI); var proto = m[2], domain = m[3], port = m[4] || ""; if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) { port = ""; } return proto + "//" + domain + port; } /** * Resolves a relative url into an absolute one. * @param {String} url The path to resolve. * @return {String} The resolved url. */ function resolveUrl(url){ // replace all // except the one in proto with / url = url.replace(reDoubleSlash, "$1/"); // If the url is a valid url we do nothing if (!url.match(/^(http||https):\/\//)) { // If this is a relative path var path = (url.substring(0, 1) === "/") ? "" : location.pathname; if (path.substring(path.length - 1) !== "/") { path = path.substring(0, path.lastIndexOf("/") + 1); } url = location.protocol + "//" + location.host + path + url; } // reduce all 'xyz/../' to just '' while (reParent.test(url)) { url = url.replace(reParent, ""); } return url; } /** * Appends the parameters to the given url.<br/> * The base url can contain existing query parameters. * @param {String} url The base url. * @param {Object} parameters The parameters to add. * @return {String} A new valid url with the parameters appended. */ function appendQueryParameters(url, parameters){ var hash = "", indexOf = url.indexOf("#"); if (indexOf !== -1) { hash = url.substring(indexOf); url = url.substring(0, indexOf); } var q = []; for (var key in parameters) { if (parameters.hasOwnProperty(key)) { q.push(key + "=" + encodeURIComponent(parameters[key])); } } return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash; } // build the query object either from location.query, if it contains the xdm_e argument, or from location.hash var query = (function(input){ input = input.substring(1).split("&"); var data = {}, pair, i = input.length; while (i--) { pair = input[i].split("="); data[pair[0]] = decodeURIComponent(pair[1]); } return data; }(/xdm_e=/.test(location.search) ? location.search : location.hash)); /* * Helper methods */ /** * Helper for checking if a variable/property is undefined * @param {Object} v The variable to test * @return {Boolean} True if the passed variable is undefined */ function undef(v){ return typeof v === "undefined"; } /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ var getJSON = function(){ var cached = {}; var obj = { a: [1, 2, 3] }, json = "{\"a\":[1,2,3]}"; if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) { // this is a working JSON instance return JSON; } if (Object.toJSON) { if (Object.toJSON(obj).replace((/\s/g), "") === json) { // this is a working stringify method cached.stringify = Object.toJSON; } } if (typeof String.prototype.evalJSON === "function") { obj = json.evalJSON(); if (obj.a && obj.a.length === 3 && obj.a[2] === 3) { // this is a working parse method cached.parse = function(str){ return str.evalJSON(); }; } } if (cached.stringify && cached.parse) { // Only memoize the result if we have valid instance getJSON = function(){ return cached; }; return cached; } return null; }; /** * Applies properties from the source object to the target object.<br/> * @param {Object} target The target of the properties. * @param {Object} source The source of the properties. * @param {Boolean} noOverwrite Set to True to only set non-existing properties. */ function apply(destination, source, noOverwrite){ var member; for (var prop in source) { if (source.hasOwnProperty(prop)) { if (prop in destination) { member = source[prop]; if (typeof member === "object") { apply(destination[prop], member, noOverwrite); } else if (!noOverwrite) { destination[prop] = source[prop]; } } else { destination[prop] = source[prop]; } } } return destination; } // This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName]. function testForNamePropertyBug(){ var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input")); input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name]; document.body.removeChild(form); } /** * Creates a frame and appends it to the DOM. * @param config {object} This object can have the following properties * <ul> * <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li> * <li> {object} attr The attributes that should be set on the frame.</li> * <li> {DOMElement} container Its parent element (Optional).</li> * <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li> * </ul> * @return The frames DOMElement * @type DOMElement */ function createFrame(config){ if (undef(HAS_NAME_PROPERTY_BUG)) { testForNamePropertyBug(); } var frame; // This is to work around the problems in IE6/7 with setting the name property. // Internally this is set as 'submitName' instead when using 'iframe.name = ...' // This is not required by easyXDM itself, but is to facilitate other use cases if (HAS_NAME_PROPERTY_BUG) { frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>"); } else { frame = document.createElement("IFRAME"); frame.name = config.props.name; } frame.id = frame.name = config.props.name; delete config.props.name; if (config.onLoad) { on(frame, "load", config.onLoad); } if (typeof config.container == "string") { config.container = document.getElementById(config.container); } if (!config.container) { // This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers. apply(frame.style, { position: "absolute", top: "-2000px" }); config.container = document.body; } // HACK for some reason, IE needs the source set // after the frame has been appended into the DOM // so remove the src, and set it afterwards var src = config.props.src; delete config.props.src; // transfer properties to the frame apply(frame, config.props); frame.border = frame.frameBorder = 0; frame.allowTransparency = true; config.container.appendChild(frame); // HACK see above frame.src = src; config.props.src = src; return frame; } /** * Check whether a domain is allowed using an Access Control List. * The ACL can contain * and ? as wildcards, or can be regular expressions. * If regular expressions they need to begin with ^ and end with $. * @param {Array/String} acl The list of allowed domains * @param {String} domain The domain to test. * @return {Boolean} True if the domain is allowed, false if not. */ function checkAcl(acl, domain){ // normalize into an array if (typeof acl == "string") { acl = [acl]; } var re, i = acl.length; while (i--) { re = acl[i]; re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$")); if (re.test(domain)) { return true; } } return false; } /* * Functions related to stacks */ /** * Prepares an array of stack-elements suitable for the current configuration * @param {Object} config The Transports configuration. See easyXDM.Socket for more. * @return {Array} An array of stack-elements with the TransportElement at index 0. */ function prepareTransportStack(config){ var protocol = config.protocol, stackEls; config.isHost = config.isHost || undef(query.xdm_p); useHash = config.hash || false; if (!config.props) { config.props = {}; } if (!config.isHost) { config.channel = query.xdm_c; config.secret = query.xdm_s; config.remote = query.xdm_e; protocol = query.xdm_p; if (config.acl && !checkAcl(config.acl, config.remote)) { throw new Error("Access denied for " + config.remote); } } else { config.remote = resolveUrl(config.remote); config.channel = config.channel || "default" + channelId++; config.secret = Math.random().toString(16).substring(2); if (undef(protocol)) { if (getLocation(location.href) == getLocation(config.remote)) { /* * Both documents has the same origin, lets use direct access. */ protocol = "4"; } else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) { /* * This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+ */ protocol = "1"; } else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) { /* * The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS */ protocol = "6"; } else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) { /* * This is supported in Gecko (Firefox 1+) */ protocol = "5"; } else if (config.remoteHelper) { /* * This is supported in all browsers that retains the value of window.name when * navigating from one domain to another, and where parent.frames[foo] can be used * to get access to a frame from the same domain */ config.remoteHelper = resolveUrl(config.remoteHelper); protocol = "2"; } else { /* * This is supported in all browsers where [window].location is writable for all * The resize event will be used if resize is supported and the iframe is not put * into a container, else polling will be used. */ protocol = "0"; } } } config.protocol = protocol; // for conditional branching switch (protocol) { case "0":// 0 = HashTransport apply(config, { interval: 100, delay: 2000, useResize: true, useParent: false, usePolling: false }, true); if (config.isHost) { if (!config.local) { // If no local is set then we need to find an image hosted on the current domain var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image; var i = images.length; while (i--) { image = images[i]; if (image.src.substring(0, domain.length) === domain) { config.local = image.src; break; } } if (!config.local) { // If no local was set, and we are unable to find a suitable file, then we resort to using the current window config.local = window; } } var parameters = { xdm_c: config.channel, xdm_p: 0 }; if (config.local === window) { // We are using the current window to listen to config.usePolling = true; config.useParent = true; config.local = location.protocol + "//" + location.host + location.pathname + location.search; parameters.xdm_e = config.local; parameters.xdm_pa = 1; // use parent } else { parameters.xdm_e = resolveUrl(config.local); } if (config.container) { config.useResize = false; parameters.xdm_po = 1; // use polling } config.remote = appendQueryParameters(config.remote, parameters); } else { apply(config, { channel: query.xdm_c, remote: query.xdm_e, useParent: !undef(query.xdm_pa), usePolling: !undef(query.xdm_po), useResize: config.useParent ? false : config.useResize }); } stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({ encode: true, maxLength: 4000 - config.remote.length }), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "1": stackEls = [new easyXDM.stack.PostMessageTransport(config)]; break; case "2": stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "3": stackEls = [new easyXDM.stack.NixTransport(config)]; break; case "4": stackEls = [new easyXDM.stack.SameOriginTransport(config)]; break; case "5": stackEls = [new easyXDM.stack.FrameElementTransport(config)]; break; case "6": if (!flashVersion) { hasFlash(); } stackEls = [new easyXDM.stack.FlashTransport(config)]; break; } // this behavior is responsible for buffering outgoing messages, and for performing lazy initialization stackEls.push(new easyXDM.stack.QueueBehavior({ lazy: config.lazy, remove: true })); return stackEls; } /** * Chains all the separate stack elements into a single usable stack.<br/> * If an element is missing a necessary method then it will have a pass-through method applied. * @param {Array} stackElements An array of stack elements to be linked. * @return {easyXDM.stack.StackElement} The last element in the chain. */ function chainStack(stackElements){ var stackEl, defaults = { incoming: function(message, origin){ this.up.incoming(message, origin); }, outgoing: function(message, recipient){ this.down.outgoing(message, recipient); }, callback: function(success){ this.up.callback(success); }, init: function(){ this.down.init(); }, destroy: function(){ this.down.destroy(); } }; for (var i = 0, len = stackElements.length; i < len; i++) { stackEl = stackElements[i]; apply(stackEl, defaults, true); if (i !== 0) { stackEl.down = stackElements[i - 1]; } if (i !== len - 1) { stackEl.up = stackElements[i + 1]; } } return stackEl; } /** * This will remove a stackelement from its stack while leaving the stack functional. * @param {Object} element The elment to remove from the stack. */ function removeFromStack(element){ element.up.down = element.down; element.down.up = element.up; element.up = element.down = null; } /* * Export the main object and any other methods applicable */ /** * @class easyXDM * A javascript library providing cross-browser, cross-domain messaging/RPC. * @version 2.4.15.118 * @singleton */ apply(easyXDM, { /** * The version of the library * @type {string} */ version: "2.4.15.118", /** * This is a map containing all the query parameters passed to the document. * All the values has been decoded using decodeURIComponent. * @type {object} */ query: query, /** * @private */ stack: {}, /** * Applies properties from the source object to the target object.<br/> * @param {object} target The target of the properties. * @param {object} source The source of the properties. * @param {boolean} noOverwrite Set to True to only set non-existing properties. */ apply: apply, /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ getJSONObject: getJSON, /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {object} scope An optional scope for the function to be called with. */ whenReady: whenReady, /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ noConflict: noConflict }); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.DomHelper * Contains methods for dealing with the DOM * @singleton */ easyXDM.DomHelper = { /** * Provides a consistent interface for adding eventhandlers * @param {Object} target The target to add the event to * @param {String} type The name of the event * @param {Function} listener The listener */ on: on, /** * Provides a consistent interface for removing eventhandlers * @param {Object} target The target to remove the event from * @param {String} type The name of the event * @param {Function} listener The listener */ un: un, /** * Checks for the presence of the JSON object. * If it is not present it will use the supplied path to load the JSON2 library. * This should be called in the documents head right after the easyXDM script tag. * http://json.org/json2.js * @param {String} path A valid path to json2.js */ requiresJSON: function(path){ if (!isHostObject(window, "JSON")) { // we need to encode the < in order to avoid an illegal token error // when the script is inlined in a document. document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>'); } } }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // (function(){ // The map containing the stored functions var _map = {}; /** * @class easyXDM.Fn * This contains methods related to function handling, such as storing callbacks. * @singleton * @namespace easyXDM */ easyXDM.Fn = { /** * Stores a function using the given name for reference * @param {String} name The name that the function should be referred by * @param {Function} fn The function to store * @namespace easyXDM.fn */ set: function(name, fn){ _map[name] = fn; }, /** * Retrieves the function referred to by the given name * @param {String} name The name of the function to retrieve * @param {Boolean} del If the function should be deleted after retrieval * @return {Function} The stored function * @namespace easyXDM.fn */ get: function(name, del){ var fn = _map[name]; if (del) { delete _map[name]; } return fn; } }; }()); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.Socket * This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/> * The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/> * Internally different stacks will be used depending on the browsers features and the available parameters. * <h2>How to set up</h2> * Setting up the provider: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; local: "name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * Setting up the consumer: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; remote: "http:&#47;&#47;remotedomain/page.html", * &nbsp; remoteHelper: "http:&#47;&#47;remotedomain/name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property * and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports. * @namespace easyXDM * @constructor * @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window. * @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed. * @cfg {String} remote (Consumer only) The url to the providers document. * @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000. * @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300. * @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional. * @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional. * @cfg {Function} onReady A method that should be called when the transport is ready. Optional. * @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional. * @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/> * This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $. * If none of the patterns match an Error will be thrown. * @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>. * Properties such as 'name' and 'src' will be overrided. Optional. */ easyXDM.Socket = function(config){ // create the stack var stack = chainStack(prepareTransportStack(config).concat([{ incoming: function(message, origin){ config.onMessage(message, origin); }, callback: function(success){ if (config.onReady) { config.onReady(success); } } }])), recipient = getLocation(config.remote); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; /** * Posts a message to the remote end of the channel * @param {String} message The message to send */ this.postMessage = function(message){ stack.outgoing(message, recipient); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.Rpc * Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation * of methods to be called from the remote end.<br/> * The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/> * This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods. * <h2>How to set up</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; &#47;&#47; this configuration is equal to that used by the Socket. * &nbsp; remote: "http:&#47;&#47;remotedomain/...", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the proxy * &nbsp; &nbsp; rpc.foo(... * &nbsp; } * },{ * &nbsp; local: {..}, * &nbsp; remote: {..} * }); * </code></pre> * * <h2>Exposing functions (procedures)</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: { * &nbsp; &nbsp; nameOfMethod: { * &nbsp; &nbsp; &nbsp; method: function(arg1, arg2, success, error){ * &nbsp; &nbsp; &nbsp; &nbsp; ... * &nbsp; &nbsp; &nbsp; } * &nbsp; &nbsp; }, * &nbsp; &nbsp; &#47;&#47; with shorthand notation * &nbsp; &nbsp; nameOfAnotherMethod: function(arg1, arg2, success, error){ * &nbsp; &nbsp; } * &nbsp; }, * &nbsp; remote: {...} * }); * </code></pre> * The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/> * To send a successfull result back you can use * <pre><code> * return foo; * </pre></code> * or * <pre><code> * success(foo); * </pre></code> * To return an error you can use * <pre><code> * throw new Error("foo error"); * </code></pre> * or * <pre><code> * error("foo error"); * </code></pre> * * <h2>Defining remotely exposed methods (procedures/notifications)</h2> * The definition of the remote end is quite similar: * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: { * &nbsp; &nbsp; nameOfMethod: {} * &nbsp; } * }); * </code></pre> * To call a remote method use * <pre><code> * rpc.nameOfMethod("arg1", "arg2", function(value) { * &nbsp; alert("success: " + value); * }, function(message) { * &nbsp; alert("error: " + message + ); * }); * </code></pre> * Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/> * When called with no callback a JSON-RPC 2.0 notification will be executed. * Be aware that you will not be notified of any errors with this method. * <br/> * <h2>Specifying a custom serializer</h2> * If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library * then you can specify a custom serializer using <code>serializer: foo</code> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: {...}, * &nbsp; serializer : { * &nbsp; &nbsp; parse: function(string){ ... }, * &nbsp; &nbsp; stringify: function(object) {...} * &nbsp; } * }); * </code></pre> * If <code>serializer</code> is set then the class will not attempt to use the native implementation. * @namespace easyXDM * @constructor * @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters. * @param {Object} jsonRpcConfig The description of the interface to implement. */ easyXDM.Rpc = function(config, jsonRpcConfig){ // expand shorthand notation if (jsonRpcConfig.local) { for (var method in jsonRpcConfig.local) { if (jsonRpcConfig.local.hasOwnProperty(method)) { var member = jsonRpcConfig.local[method]; if (typeof member === "function") { jsonRpcConfig.local[method] = { method: member }; } } } } // create the stack var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), { callback: function(success){ if (config.onReady) { config.onReady(success); } } }])); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.SameOriginTransport * SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/> * This can be useful for testing and for when the main application supports both internal and external sources. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.SameOriginTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send(message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: location.protocol + "//" + location.host + location.pathname, xdm_c: config.channel, xdm_p: 4 // 4 = SameOriginTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); easyXDM.Fn.set(config.channel, function(sendFn){ send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); return function(msg){ pub.up.incoming(msg, targetOrigin); }; }); } else { send = getParentObject().Fn.get(config.channel, true)(function(msg){ pub.up.incoming(msg, targetOrigin); }); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.FlashTransport * FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. * @cfg {String} secret the pre-shared secret used to secure the communication. * @cfg {String} swf The path to the swf file * @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden. * @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed */ easyXDM.stack.FlashTransport = function(config){ var pub, // the public interface frame, send, targetOrigin, swf, swfContainer; function onMessage(message, origin){ setTimeout(function(){ pub.up.incoming(message, targetOrigin); }, 0); } /** * This method adds the SWF to the DOM and prepares the initialization of the channel */ function addSwf(domain){ // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error. var url = config.swf + "?host=" + config.isHost; var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000); // prepare the init function that will fire once the swf is ready easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){ easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild; var queue = easyXDM.stack.FlashTransport[domain].queue; for (var i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; }); if (config.swfContainer) { swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer; } else { // create the container that will hold the swf swfContainer = document.createElement('div'); // http://bugs.adobe.com/jira/browse/FP-4796 // http://tech.groups.yahoo.com/group/flexcoders/message/162365 // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? { height: "20px", width: "20px", position: "fixed", right: 0, top: 0 } : { height: "1px", width: "1px", position: "absolute", overflow: "hidden", right: 0, top: 0 }); document.body.appendChild(swfContainer); } // create the object/embed var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace; swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" + "<param name='allowScriptAccess' value='always'></param>" + "<param name='wmode' value='transparent'>" + "<param name='movie' value='" + url + "'></param>" + "<param name='flashvars' value='" + flashVars + "'></param>" + "<embed type='application/x-shockwave-flash' FlashVars='" + flashVars + "' allowScriptAccess='always' wmode='transparent' src='" + url + "' height='1' width='1'></embed>" + "</object>"; } return (pub = { outgoing: function(message, domain, fn){ swf.postMessage(config.channel, message.toString()); if (fn) { fn(); } }, destroy: function(){ try { swf.destroyChannel(config.channel); } catch (e) { } swf = null; if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = config.remote; // Prepare the code that will be run after the swf has been intialized easyXDM.Fn.set("flash_" + config.channel + "_init", function(){ setTimeout(function(){ pub.up.callback(true); }); }); // set up the omMessage handler easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage); config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths var swfdomain = getDomainName(config.swf); var fn = function(){ // set init to true in case the fn was called was invoked from a separate instance easyXDM.stack.FlashTransport[swfdomain].init = true; swf = easyXDM.stack.FlashTransport[swfdomain].swf; // create the channel swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost); if (config.isHost) { // if Flash is going to be throttled and we want to avoid this if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) { apply(config.props, { position: "fixed", right: 0, top: 0, height: "20px", width: "20px" }); } // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 6, // 6 = FlashTransport xdm_s: config.secret }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } }; if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) { // if the swf is in place and we are the consumer fn(); } else { // if the swf does not yet exist if (!easyXDM.stack.FlashTransport[swfdomain]) { // add the queue to hold the init fn's easyXDM.stack.FlashTransport[swfdomain] = { queue: [fn] }; addSwf(swfdomain); } else { easyXDM.stack.FlashTransport[swfdomain].queue.push(fn); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.PostMessageTransport * PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/> * <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. */ easyXDM.stack.PostMessageTransport = function(config){ var pub, // the public interface frame, // the remote frame, if any callerWindow, // the window that we will call with targetOrigin; // the domain to communicate with /** * Resolves the origin from the event object * @private * @param {Object} event The messageevent * @return {String} The scheme, host and port of the origin */ function _getOrigin(event){ if (event.origin) { // This is the HTML5 property return getLocation(event.origin); } if (event.uri) { // From earlier implementations return getLocation(event.uri); } if (event.domain) { // This is the last option and will fail if the // origin is not using the same schema as we are return location.protocol + "//" + event.domain; } throw "Unable to retrieve the origin of the event"; } /** * This is the main implementation for the onMessage event.<br/> * It checks the validity of the origin and passes the message on if appropriate. * @private * @param {Object} event The messageevent */ function _window_onMessage(event){ var origin = _getOrigin(event); if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") { pub.up.incoming(event.data.substring(config.channel.length + 1), origin); } } return (pub = { outgoing: function(message, domain, fn){ callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin); if (fn) { fn(); } }, destroy: function(){ un(window, "message", _window_onMessage); if (frame) { callerWindow = null; frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // add the event handler for listening var waitForReady = function(event){ if (event.data == config.channel + "-ready") { // replace the eventlistener callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document; un(window, "message", waitForReady); on(window, "message", _window_onMessage); setTimeout(function(){ pub.up.callback(true); }, 0); } }; on(window, "message", waitForReady); // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 1 // 1 = PostMessage }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } else { // add the event handler for listening on(window, "message", _window_onMessage); callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document; callerWindow.postMessage(config.channel + "-ready", targetOrigin); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.FrameElementTransport * FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/> * Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.FrameElementTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send.call(this, message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 5 // 5 = FrameElementTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); frame.fn = function(sendFn){ delete frame.fn; send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); // remove the function so that it cannot be used to overwrite the send function later on return function(msg){ pub.up.incoming(msg, targetOrigin); }; }; } else { // This is to mitigate origin-spoofing if (document.referrer && getLocation(document.referrer) != query.xdm_e) { window.top.location = query.xdm_e; } send = window.frameElement.fn(function(msg){ pub.up.incoming(msg, targetOrigin); }); pub.up.callback(true); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.NameTransport * NameTransport uses the window.name property to relay data. * The <code>local</code> parameter needs to be set on both the consumer and provider,<br/> * and the <code>remoteHelper</code> parameter needs to be set on the consumer. * @constructor * @param {Object} config The transports configuration. * @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host. * @namespace easyXDM.stack */ easyXDM.stack.NameTransport = function(config){ var pub; // the public interface var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl; function _sendMessage(message){ var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel; callerWindow.contentWindow.sendMessage(message, url); } function _onReady(){ if (isHost) { if (++readyCount === 2 || !isHost) { pub.up.callback(true); } } else { _sendMessage("ready"); pub.up.callback(true); } } function _onMessage(message){ pub.up.incoming(message, remoteOrigin); } function _onLoad(){ if (callback) { setTimeout(function(){ callback(true); }, 0); } } return (pub = { outgoing: function(message, domain, fn){ callback = fn; _sendMessage(message); }, destroy: function(){ callerWindow.parentNode.removeChild(callerWindow); callerWindow = null; if (isHost) { remoteWindow.parentNode.removeChild(remoteWindow); remoteWindow = null; } }, onDOMReady: function(){ isHost = config.isHost; readyCount = 0; remoteOrigin = getLocation(config.remote); config.local = resolveUrl(config.local); if (isHost) { // Register the callback easyXDM.Fn.set(config.channel, function(message){ if (isHost && message === "ready") { // Replace the handler easyXDM.Fn.set(config.channel, _onMessage); _onReady(); } }); // Set up the frame that points to the remote instance remoteUrl = appendQueryParameters(config.remote, { xdm_e: config.local, xdm_c: config.channel, xdm_p: 2 }); apply(config.props, { src: remoteUrl + '#' + config.channel, name: IFRAME_PREFIX + config.channel + "_provider" }); remoteWindow = createFrame(config); } else { config.remoteHelper = config.remote; easyXDM.Fn.set(config.channel, _onMessage); } // Set up the iframe that will be used for the transport callerWindow = createFrame({ props: { src: config.local + "#_4" + config.channel }, onLoad: function onLoad(){ // Remove the handler var w = callerWindow || this; un(w, "load", onLoad); easyXDM.Fn.set(config.channel + "_load", _onLoad); (function test(){ if (typeof w.contentWindow.sendMessage == "function") { _onReady(); } else { setTimeout(test, 50); } }()); } }); }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.HashTransport * HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String/Window} local The url to the local file used for proxying messages, or the local window. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. * @cfg {Number} interval The interval used when polling for messages. */ easyXDM.stack.HashTransport = function(config){ var pub; var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow; var useParent, _remoteOrigin; function _sendMessage(message){ if (!_callerWindow) { return; } var url = config.remote + "#" + (_msgNr++) + "_" + message; ((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url; } function _handleHash(hash){ _lastMsg = hash; pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin); } /** * Checks location.hash for a new message and relays this to the receiver. * @private */ function _pollHash(){ if (!_listenerWindow) { return; } var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#"); if (indexOf != -1) { hash = href.substring(indexOf); } if (hash && hash != _lastMsg) { _handleHash(hash); } } function _attachListeners(){ _timer = setInterval(_pollHash, pollInterval); } return (pub = { outgoing: function(message, domain){ _sendMessage(message); }, destroy: function(){ window.clearInterval(_timer); if (isHost || !useParent) { _callerWindow.parentNode.removeChild(_callerWindow); } _callerWindow = null; }, onDOMReady: function(){ isHost = config.isHost; pollInterval = config.interval; _lastMsg = "#" + config.channel; _msgNr = 0; useParent = config.useParent; _remoteOrigin = getLocation(config.remote); if (isHost) { config.props = { src: config.remote, name: IFRAME_PREFIX + config.channel + "_provider" }; if (useParent) { config.onLoad = function(){ _listenerWindow = window; _attachListeners(); pub.up.callback(true); }; } else { var tries = 0, max = config.delay / 50; (function getRef(){ if (++tries > max) { throw new Error("Unable to reference listenerwindow"); } try { _listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"]; } catch (ex) { } if (_listenerWindow) { _attachListeners(); pub.up.callback(true); } else { setTimeout(getRef, 50); } }()); } _callerWindow = createFrame(config); } else { _listenerWindow = window; _attachListeners(); if (useParent) { _callerWindow = parent; pub.up.callback(true); } else { apply(config, { props: { src: config.remote + "#" + config.channel + new Date(), name: IFRAME_PREFIX + config.channel + "_consumer" }, onLoad: function(){ pub.up.callback(true); } }); _callerWindow = createFrame(config); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.ReliableBehavior * This is a behavior that tries to make the underlying transport reliable by using acknowledgements. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. */ easyXDM.stack.ReliableBehavior = function(config){ var pub, // the public interface callback; // the callback to execute when we have a confirmed success/failure var idOut = 0, idIn = 0, currentMessage = ""; return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(","); message = message.substring(indexOf + 1); if (ack[0] == idOut) { currentMessage = ""; if (callback) { callback(true); } } if (message.length > 0) { pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin); if (idIn != ack[1]) { idIn = ack[1]; pub.up.incoming(message, origin); } } }, outgoing: function(message, origin, fn){ currentMessage = message; callback = fn; pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.QueueBehavior * This is a behavior that enables queueing of messages. <br/> * It will buffer incoming messages and dispach these as fast as the underlying transport allows. * This will also fragment/defragment messages so that the outgoing message is never bigger than the * set length. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. Optional. * @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation. */ easyXDM.stack.QueueBehavior = function(config){ var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false; function dispatch(){ if (config.remove && queue.length === 0) { removeFromStack(pub); return; } if (waiting || queue.length === 0 || destroying) { return; } waiting = true; var message = queue.shift(); pub.down.outgoing(message.data, message.origin, function(success){ waiting = false; if (message.callback) { setTimeout(function(){ message.callback(success); }, 0); } dispatch(); }); } return (pub = { init: function(){ if (undef(config)) { config = {}; } if (config.maxLength) { maxLength = config.maxLength; doFragment = true; } if (config.lazy) { lazy = true; } else { pub.down.init(); } }, callback: function(success){ waiting = false; var up = pub.up; // in case dispatch calls removeFromStack dispatch(); up.callback(success); }, incoming: function(message, origin){ if (doFragment) { var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10); incoming += message.substring(indexOf + 1); if (seq === 0) { if (config.encode) { incoming = decodeURIComponent(incoming); } pub.up.incoming(incoming, origin); incoming = ""; } } else { pub.up.incoming(message, origin); } }, outgoing: function(message, origin, fn){ if (config.encode) { message = encodeURIComponent(message); } var fragments = [], fragment; if (doFragment) { // fragment into chunks while (message.length !== 0) { fragment = message.substring(0, maxLength); message = message.substring(fragment.length); fragments.push(fragment); } // enqueue the chunks while ((fragment = fragments.shift())) { queue.push({ data: fragments.length + "_" + fragment, origin: origin, callback: fragments.length === 0 ? fn : null }); } } else { queue.push({ data: message, origin: origin, callback: fn }); } if (lazy) { pub.down.init(); } else { dispatch(); } }, destroy: function(){ destroying = true; pub.down.destroy(); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.VerifyBehavior * This behavior will verify that communication with the remote end is possible, and will also sign all outgoing, * and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. * @cfg {Boolean} initiate If the verification should be initiated from this end. */ easyXDM.stack.VerifyBehavior = function(config){ var pub, mySecret, theirSecret, verified = false; function startVerification(){ mySecret = Math.random().toString(16).substring(2); pub.down.outgoing(mySecret); } return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"); if (indexOf === -1) { if (message === mySecret) { pub.up.callback(true); } else if (!theirSecret) { theirSecret = message; if (!config.initiate) { startVerification(); } pub.down.outgoing(message); } } else { if (message.substring(0, indexOf) === theirSecret) { pub.up.incoming(message.substring(indexOf + 1), origin); } } }, outgoing: function(message, origin, fn){ pub.down.outgoing(mySecret + "_" + message, origin, fn); }, callback: function(success){ if (config.initiate) { startVerification(); } } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /** * @class easyXDM.stack.RpcBehavior * This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/> * Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything. * @namespace easyXDM.stack * @constructor * @param {Object} proxy The object to apply the methods to. * @param {Object} config The definition of the local and remote interface to implement. * @cfg {Object} local The local interface to expose. * @cfg {Object} remote The remote methods to expose through the proxy. * @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON. */ easyXDM.stack.RpcBehavior = function(proxy, config){ var pub, serializer = config.serializer || getJSON(); var _callbackCounter = 0, _callbacks = {}; /** * Serializes and sends the message * @private * @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added. */ function _send(data){ data.jsonrpc = "2.0"; pub.down.outgoing(serializer.stringify(data)); } /** * Creates a method that implements the given definition * @private * @param {Object} The method configuration * @param {String} method The name of the method * @return {Function} A stub capable of proxying the requested method call */ function _createMethod(definition, method){ var slice = Array.prototype.slice; return function(){ var l = arguments.length, callback, message = { method: method }; if (l > 0 && typeof arguments[l - 1] === "function") { //with callback, procedure if (l > 1 && typeof arguments[l - 2] === "function") { // two callbacks, success and error callback = { success: arguments[l - 2], error: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 2); } else { // single callback, success callback = { success: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 1); } _callbacks["" + (++_callbackCounter)] = callback; message.id = _callbackCounter; } else { // no callbacks, a notification message.params = slice.call(arguments, 0); } if (definition.namedParams && message.params.length === 1) { message.params = message.params[0]; } // Send the method request _send(message); }; } /** * Executes the exposed method * @private * @param {String} method The name of the method * @param {Number} id The callback id to use * @param {Function} method The exposed implementation * @param {Array} params The parameters supplied by the remote end */ function _executeMethod(method, id, fn, params){ if (!fn) { if (id) { _send({ id: id, error: { code: -32601, message: "Procedure not found." } }); } return; } var success, error; if (id) { success = function(result){ success = emptyFn; _send({ id: id, result: result }); }; error = function(message, data){ error = emptyFn; var msg = { id: id, error: { code: -32099, message: message } }; if (data) { msg.error.data = data; } _send(msg); }; } else { success = error = emptyFn; } // Call local method if (!isArray(params)) { params = [params]; } try { var result = fn.method.apply(fn.scope, params.concat([success, error])); if (!undef(result)) { success(result); } } catch (ex1) { error(ex1.message); } } return (pub = { incoming: function(message, origin){ var data = serializer.parse(message); if (data.method) { // A method call from the remote end if (config.handle) { config.handle(data, _send); } else { _executeMethod(data.method, data.id, config.local[data.method], data.params); } } else { // A method response from the other end var callback = _callbacks[data.id]; if (data.error) { if (callback.error) { callback.error(data.error); } } else if (callback.success) { callback.success(data.result); } delete _callbacks[data.id]; } }, init: function(){ if (config.remote) { // Implement the remote sides exposed methods for (var method in config.remote) { if (config.remote.hasOwnProperty(method)) { proxy[method] = _createMethod(config.remote[method], method); } } } pub.down.init(); }, destroy: function(){ for (var method in config.remote) { if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) { delete proxy[method]; } } pub.down.destroy(); } }); }; global.easyXDM = easyXDM; })(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent); /*! * F2 v1.4.0 01-23-2014 * Copyright (c) 2014 Markit On Demand, Inc. http://www.openf2.org * * "F2" is 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. * * Please note that F2 ("Software") may contain third party material that Markit * On Demand Inc. has a license to use and include within the Software (the * "Third Party Material"). A list of the software comprising the Third Party Material * and the terms and conditions under which such Third Party Material is distributed * are reproduced in the ThirdPartyMaterial.md file available at: * * https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md * * The inclusion of the Third Party Material in the Software does not grant, provide * nor result in you having acquiring any rights whatsoever, other than as stipulated * in the terms and conditions related to the specific Third Party Material, if any. * */ var F2; /** * Open F2 * @module f2 * @main f2 */ F2 = (function() { /** * Abosolutizes a relative URL * @method _absolutizeURI * @private * @param {e.g., location.href} base * @param {URL to absolutize} href * @returns {string} URL * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _absolutizeURI = function(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = _parseURI(href || ''); base = _parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; }; /** * Parses URI * @method _parseURI * @private * @param {The URL to parse} url * @returns {Parsed URL} string * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _parseURI = function(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); }; return { /** * A function to pass into F2.stringify which will prevent circular * reference errors when serializing objects * @method appConfigReplacer */ appConfigReplacer: function(key, value) { if (key == 'root' || key == 'ui' || key == 'height') { return undefined; } else { return value; } }, /** * The apps namespace is a place for app developers to put the javascript * class that is used to initialize their app. The javascript classes should * be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId. * It is recommended that the code be placed in a closure to help keep the * global namespace clean. * * If the class has an 'init' function, that function will be called * automatically by F2. * @property Apps * @type object * @example * F2.Apps["com_example_helloworld"] = (function() { * var App_Class = function(appConfig, appContent, root) { * this._app = appConfig; // the F2.AppConfig object * this._appContent = appContent // the F2.AppManifest.AppContent object * this.$root = $(root); // the root DOM Element that contains this app * } * * App_Class.prototype.init = function() { * // perform init actions * } * * return App_Class; * })(); * @example * F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) { * return { * init:function() { * // perform init actions * } * }; * }; * @for F2 */ Apps: {}, /** * Creates a namespace on F2 and copies the contents of an object into * that namespace optionally overwriting existing properties. * @method extend * @param {string} ns The namespace to create. Pass a falsy value to * add properties to the F2 namespace directly. * @param {object} obj The object to copy into the namespace. * @param {bool} overwrite True if object properties should be overwritten * @return {object} The created object */ extend: function (ns, obj, overwrite) { var isFunc = typeof obj === 'function'; var parts = ns ? ns.split('.') : []; var parent = this; obj = obj || {}; // ignore leading global if (parts[0] === 'F2') { parts = parts.slice(1); } // create namespaces for (var i = 0, len = parts.length; i < len; i++) { if (!parent[parts[i]]) { parent[parts[i]] = isFunc && i + 1 == len ? obj : {}; } parent = parent[parts[i]]; } // copy object into namespace if (!isFunc) { for (var prop in obj) { if (typeof parent[prop] === 'undefined' || overwrite) { parent[prop] = obj[prop]; } } } return parent; }, /** * Generates a somewhat random id * @method guid * @return {string} A random id * @for F2 */ guid: function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4()); }, /** * Search for a value within an array. * @method inArray * @param {object} value The value to search for * @param {Array} array The array to search * @return {bool} True if the item is in the array */ inArray: function(value, array) { return jQuery.inArray(value, array) > -1; }, /** * Tests a URL to see if it's on the same domain (local) or not * @method isLocalRequest * @param {URL to test} url * @returns {bool} Whether the URL is local or not * Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js */ isLocalRequest: function(url){ var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, urlLower = url.toLowerCase(), parts = rurl.exec( urlLower ), ajaxLocation, ajaxLocParts; 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; } ajaxLocation = ajaxLocation.toLowerCase(); // uh oh, the url must be relative // make it fully qualified and re-regex url if (!parts){ urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase(); parts = rurl.exec( urlLower ); } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation ) || []; // do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain) var matched = !(parts && (parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || (parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !== (ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443')))); return matched; }, /** * Utility method to determine whether or not the argument passed in is or is not a native dom node. * @method isNativeDOMNode * @param {object} testObject The object you want to check as native dom node. * @return {bool} Returns true if the object passed is a native dom node. */ isNativeDOMNode: function(testObject) { var bIsNode = ( typeof Node === 'object' ? testObject instanceof Node : testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string' ); var bIsElement = ( typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2 testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string' ); return (bIsNode || bIsElement); }, /** * A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console). * @method log * @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api). * @param {object} [obj2]* An object to be logged * @example //Pass any object (string, int, array, object, bool) to .log() F2.log('foo'); F2.log(myArray); //Use a console method name as the first argument. F2.log('error', err); F2.log('info', 'The session ID is ' + sessionId); * Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js) */ log: function() { var _log; var _logMethod = 'log'; var method; var noop = function () { }; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); var args; while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } //if first arg is a console function, use it. //defaults to console.log() if (arguments && arguments.length > 1 && arguments[0] == method){ _logMethod = method; //remove console func from args args = Array.prototype.slice.call(arguments, 1); } } if (Function.prototype.bind) { _log = Function.prototype.bind.call(console[_logMethod], console); } else { _log = function() { Function.prototype.apply.call(console[_logMethod], console, (args || arguments)); }; } _log.apply(this, (args || arguments)); }, /** * Wrapper to convert a JSON string to an object * @method parse * @param {string} str The JSON string to convert * @return {object} The parsed object */ parse: function(str) { return JSON.parse(str); }, /** * Wrapper to convert an object to JSON * * **Note: When using F2.stringify on an F2.AppConfig object, it is * recommended to pass F2.appConfigReplacer as the replacer function in * order to prevent circular serialization errors.** * @method stringify * @param {object} value The object to convert * @param {function|Array} replacer An optional parameter that determines * how object values are stringified for objects. It can be a function or an * array of strings. * @param {int|string} 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 '&nbsp;'), it contains the characters used to indent at each level. * @return {string} The JSON string */ stringify: function(value, replacer, space) { return JSON.stringify(value, replacer, space); }, /** * Function to get the F2 version number * @method version * @return {string} F2 version number */ version: function() { return '1.3.3'; } }; })(); /** * The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction. * *<p class="alert alert-block alert-warning"> *The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated&mdash;but not removed&mdash;in version 1.2. They will be permanently removed in a future version of F2. *</p> * *<p class="alert alert-block alert-info"> *Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout. *</p> * * ### Order of Execution * * **App Rendering** * * 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed. * 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached. * 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached. * 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired. * 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached. * 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached. * * * **App Removal** * 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run. * 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached. * 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached. * 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached. * * **Error Handling** * 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached. * * @class F2.AppHandlers */ F2.extend('AppHandlers', (function() { // the hidden token that we will check against every time someone tries to add, remove, fire handler var _ct = F2.guid(); var _f2t = F2.guid(); var _handlerCollection = { appCreateRoot: [], appRenderBefore: [], appDestroyBefore: [], appRenderAfter: [], appDestroyAfter: [], appRender: [], appDestroy: [], appScriptLoadFailed: [] }; var _defaultMethods = { appRender: function(appConfig, appHtml) { var $root = null; // if no app root is defined use the app's outer most node if(!F2.isNativeDOMNode(appConfig.root)) { appConfig.root = jQuery(appHtml).get(0); // get a handle on the root in jQuery $root = jQuery(appConfig.root); } else { // get a handle on the root in jQuery $root = jQuery(appConfig.root); // append the app html to the root $root.append(appHtml); } // append the root to the body by default. jQuery('body').append($root); }, appDestroy: function(appInstance) { // call the apps destroy method, if it has one if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') { appInstance.app.destroy(); } // warn the Container and App Developer that even though they have a destroy method it hasn't been else if(appInstance && appInstance.app && appInstance.app.destroy) { F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); } // fade out and remove the root jQuery(appInstance.config.root).fadeOut(500, function() { jQuery(this).remove(); }); } }; var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate) { // will throw an exception and stop execution if the token is invalid _validateToken(token); // create handler structure. Not all arguments properties will be populated/used. var handler = { func: (typeof(func_or_element)) ? func_or_element : null, namespace: sNamespace, domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null }; if(!handler.func && !handler.domNode) { throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.'); } if(handler.domNode && !bDomNodeAppropriate) { throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.'); } return handler; }; var _validateToken = function(sToken) { // check token against F2 and container if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); } }; var _removeHandler = function(sToken, eventKey, sNamespace) { // will throw an exception and stop execution if the token is invalid _validateToken(sToken); if(!sNamespace && !eventKey) { return; } // remove by event key else if(!sNamespace && eventKey) { _handlerCollection[eventKey] = []; } // remove by namespace only else if(sNamespace && !eventKey) { sNamespace = sNamespace.toLowerCase(); for(var currentEventKey in _handlerCollection) { var eventCollection = _handlerCollection[currentEventKey]; var newEvents = []; for(var i = 0, ec = eventCollection.length; i < ec; i++) { var currentEventHandler = eventCollection[i]; if(currentEventHandler) { if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace) { newEvents.push(currentEventHandler); } } } eventCollection = newEvents; } } else if(sNamespace && _handlerCollection[eventKey]) { sNamespace = sNamespace.toLowerCase(); var newHandlerCollection = []; for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++) { var currentHandler = _handlerCollection[eventKey][iCounter]; if(currentHandler) { if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace) { newHandlerCollection.push(currentHandler); } } } _handlerCollection[eventKey] = newHandlerCollection; } }; return { /** * Allows Container Developer to retrieve a unique token which must be passed to * all `on` and `off` methods. This function will self destruct and can only be called * one time. Container Developers must store the return value inside of a closure. * @method getToken **/ getToken: function() { // delete this method for security that way only the container has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.getToken; // return the token, which we validate against. return _ct; }, /** * Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}. * This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}} * and additional internal methods. * @method __f2GetToken * @private **/ __f2GetToken: function() { // delete this method for security that way only the F2 internally has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.__f2GetToken; // return the token, which we validate against. return _f2t; }, /** * Allows F2 to trigger specific events internally. * @method __trigger * @private * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}. * @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. **/ __trigger: function(token, eventKey) // additional arguments will likely be passed { // will throw an exception and stop execution if the token is invalid if(token != _f2t) { throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().'); } if(_handlerCollection && _handlerCollection[eventKey]) { // create a collection of arguments that are safe to pass to the callback. var passableArgs = []; // populate that collection with all arguments except token and eventKey for(var i = 2, j = arguments.length; i < j; i++) { passableArgs.push(arguments[i]); } if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey]) { _defaultMethods[eventKey].apply(F2, passableArgs); return this; } else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey]) { return this; } // fire all event listeners in the order that they were added. for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++) { var handler = _handlerCollection[eventKey][iCounter]; // appRender where root is already defined if (handler.domNode && arguments[2] && arguments[2].root && arguments[3]) { var $appRoot = jQuery(arguments[2].root).append(arguments[3]); jQuery(handler.domNode).append($appRoot); } else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3]) { // set the root to the actual HTML of the app arguments[2].root = jQuery(arguments[3]).get(0); // appends the root to the dom node specified jQuery(handler.domNode).append(arguments[2].root); } else { handler.func.apply(F2, passableArgs); } } } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {HTMLElement} element Specific DOM element to which app gets appended. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRender', * document.getElementById('my_app') * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRender.myNamespace', * document.getElementById('my_app') * ); **/ /** * Allows Container Developer to add listener method that will be triggered when a specific event occurs. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRenderBefore' * function() { F2.log('before app rendered!'); } * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRenderBefore.myNamespace', * function() { F2.log('before app rendered!'); } * ); **/ on: function(token, eventKey, func_or_element) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _handlerCollection[eventKey].push( _createHandler( token, sNamespace, func_or_element, (eventKey == 'appRender') ) ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to remove listener methods for specific events * @method off * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all * listeners for the specified event type will be removed. * Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.off(_token,'appRenderBefore'); * **/ off: function(token, eventKey) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _removeHandler( token, eventKey, sNamespace ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; } }; })()); F2.extend('Constants', { /** * A convenient collection of all available appHandler events. * @class F2.Constants.AppHandlers **/ AppHandlers: (function() { return { /** * Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_CREATE_ROOT * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_CREATE_ROOT, * function(appConfig) * { * // If you want to create a custom root. By default F2 uses the app's outermost HTML element. * // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER * appConfig.root = jQuery('<section></section>').get(0); * } * ); */ APP_CREATE_ROOT: 'appCreateRoot', /** * Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_BEFORE, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_BEFORE: 'appRenderBefore', /** * Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) ) * @property APP_RENDER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER, * function(appConfig, appHtml) * { * var $root = null; * * // if no app root is defined use the app's outer most node * if(!F2.isNativeDOMNode(appConfig.root)) * { * appConfig.root = jQuery(appHtml).get(0); * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * } * else * { * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * * // append the app html to the root * $root.append(appHtml); * } * * // append the root to the body by default. * jQuery('body').append($root); * } * ); */ APP_RENDER: 'appRender', /** * Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_AFTER, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_AFTER: 'appRenderAfter', /** * Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_BEFORE, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_BEFORE: 'appDestroyBefore', /** * Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY, * function(appInstance) * { * // call the apps destroy method, if it has one * if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') * { * appInstance.app.destroy(); * } * else if(appInstance && appInstance.app && appInstance.app.destroy) * { * F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); * } * * // fade out and remove the root * jQuery(appInstance.config.root).fadeOut(500, function() { * jQuery(this).remove(); * }); * } * ); */ APP_DESTROY: 'appDestroy', /** * Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_AFTER, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_AFTER: 'appDestroyAfter', /** * Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo ) * @property APP_SCRIPT_LOAD_FAILED * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, * function(appConfig, scriptInfo) * { * F2.log(appConfig.appId); * } * ); */ APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed' }; })() }); /** * Class stubs for documentation purposes * @main F2 */ F2.extend('', { /** * The App Class is an optional class that can be namespaced onto the * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The * [F2 Docs](../../app-development.html#app-class) * has more information on the usage of the App Class. * @class F2.App * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object for the app * @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent * object * @param {Element} root The root DOM Element for the app */ App: function(appConfig, appContent, root) { return { /** * An optional init function that will automatically be called when * F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called. * @method init * @optional */ init:function() {} }; }, /** * The AppConfig object represents an app's meta data * @class F2.AppConfig */ AppConfig: { /** * The unique ID of the app. More information can be found * [here](../../app-development.html#f2-appid) * @property appId * @type string * @required */ appId: '', /** * An object that represents the context of an app * @property context * @type object */ context: {}, /** * True if the app should be requested in a single request with other apps. * @property enableBatchRequests * @type bool * @default false */ enableBatchRequests: false, /** * The height of the app. The initial height will be pulled from * the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later * modified by calling * F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used * for secure apps to be able to set the initial height of the iframe. * @property height * @type int */ height: 0, /** * The unique runtime ID of the app. * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property instanceId * @type string */ instanceId: '', /** * True if the app will be loaded in an iframe. This property * will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object * sets isSecure = true. It will also be true if the * [container](../../container-development.html) has made the decision to * run apps in iframes. * @property isSecure * @type bool * @default false */ isSecure: false, /** * The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}} * object. * @property manifestUrl * @type string * @required */ manifestUrl: '', /** * The recommended maximum width in pixels that this app should be run. * **It is up to the [container](../../container-development.html) to * implement the logic to prevent an app from being run when the maxWidth * requirements are not met.** * @property maxWidth * @type int */ maxWidth: 0, /** * The recommended minimum grid size that this app should be run. This * value corresponds to the 12-grid system that is used by the * [container](../../container-development.html). This property should be * set by apps that require a certain number of columns in their layout. * @property minGridSize * @type int * @default 4 */ minGridSize: 4, /** * The recommended minimum width in pixels that this app should be run. **It * is up to the [container](../../container-development.html) to implement * the logic to prevent an app from being run when the minWidth requirements * are not met. * @property minWidth * @type int * @default 300 */ minWidth: 300, /** * The name of the app * @property name * @type string * @required */ name: '', /** * The root DOM element that contains the app * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property root * @type Element */ root: undefined, /** * The instance of F2.UI providing easy access to F2.UI methods * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property ui * @type F2.UI */ ui: undefined, /** * The views that this app supports. Available views * are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The * presence of a view can be checked via * F2.{{#crossLink "F2/inArray"}}{{/crossLink}}: * * F2.inArray(F2.Constants.Views.SETTINGS, app.views) * * @property views * @type Array */ views: [] }, /** * The assets needed to render an app on the page * @class F2.AppManifest */ AppManifest: { /** * The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}} * objects * @property apps * @type Array * @required */ apps: [], /** * Any inline javascript tha should initially be run * @property inlineScripts * @type Array * @optional */ inlineScripts: [], /** * Urls to javascript files required by the app * @property scripts * @type Array * @optional */ scripts: [], /** * Urls to CSS files required by the app * @property styles * @type Array * @optional */ styles: [] }, /** * The AppContent object * @class F2.AppManifest.AppContent **/ AppContent: { /** * Arbitrary data to be passed along with the app * @property data * @type object * @optional */ data: {}, /** * The string of HTML representing the app * @property html * @type string * @required */ html: '', /** * A status message * @property status * @type string * @optional */ status: '' }, /** * An object containing configuration information for the * [container](../../container-development.html) * @class F2.ContainerConfig */ ContainerConfig: { /** * Allows the [container](../../container-development.html) to override how * an app's html is inserted into the page. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html * @method afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app * @return {Element} The DOM Element surrounding the app */ afterAppRender: function(appConfig, html) {}, /** * Allows the [container](../../container-development.html) to wrap an app * in extra html. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html. The extra html can provide links to edit app settings and remove an * app from the container. See * {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that * should be applied to elements. * @method appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app */ appRender: function(appConfig, html) {}, /** * Allows the container to render html for an app before the AppManifest for * an app has loaded. This can be useful if the design calls for loading * icons to appear for each app before each app is loaded and rendered to * the page. * @method beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ beforeAppRender: function(appConfig) {}, /** * True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc. * @property debugMode * @type bool * @default false */ debugMode: false, /** * Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire. * @property scriptErrorTimeout * @type milliseconds * @default 7000 (7 seconds) */ scriptErrorTimeout: 7000, /** * Tells the container that it is currently running within * a secure app page * @property isSecureAppPage * @type bool */ isSecureAppPage: false, /** * Allows the container to specify which page is used when * loading a secure app. The page must reside on a different domain than the * container * @property secureAppPagePath * @type string * @for F2.ContainerConfig */ secureAppPagePath: '', /** * Specifies what views a container will provide buttons * or links to. Generally, the views will be switched via buttons or links * in the app's header. * @property supportedViews * @type Array * @required */ supportedViews: [], /** * An object containing configuration defaults for F2.UI * @class F2.ContainerConfig.UI */ UI: { /** * An object containing configuration defaults for the * F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and * F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods. * @class F2.ContainerConfig.UI.Mask */ Mask: { /** * The backround color of the overlay * @property backgroundColor * @type string * @default #FFF */ backgroundColor: '#FFF', /** * The path to the loading icon * @property loadingIcon * @type string */ loadingIcon: '', /** * The opacity of the background overlay * @property opacity * @type int * @default 0.6 */ opacity: 0.6, /** * Do not use inline styles for mask functinality. Instead classes will * be applied to the elements and it is up to the container provider to * implement the class definitions. * @property useClasses * @type bool * @default false */ useClasses: false, /** * The z-index to use for the overlay * @property zIndex * @type int * @default 2 */ zIndex: 2 } }, /** * Allows the container to fully override how the AppManifest request is * made inside of F2. * * @method xhr * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {function} success The function to be called if the request * succeeds * @param {function} error The function to be called if the request fails * @param {function} complete The function to be called when the request * finishes (after success and error callbacks have been executed) * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has * an `abort` function (such as the jqXHR object in jQuery) to abort the * request) * * @example * F2.init({ * xhr: function(url, appConfigs, success, error, complete) { * $.ajax({ * url: url, * type: 'POST', * data: { * params: F2.stringify(appConfigs, F2.appConfigReplacer) * }, * jsonp: false, // do not put 'callback=' in the query string * jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name * dataType: 'json', * success: function(appManifest) { * // custom success logic * success(appManifest); // fire success callback * }, * error: function() { * // custom error logic * error(); // fire error callback * }, * complete: function() { * // custom complete logic * complete(); // fire complete callback * } * }); * } * }); * * @for F2.ContainerConfig */ //xhr: function(url, appConfigs, success, error, complete) {}, /** * Allows the container to override individual parts of the AppManifest * request. See properties and methods with the `xhr.` prefix. * @property xhr * @type Object * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ xhr: { /** * Allows the container to override the request data type (JSON or JSONP) * that is used for the request * @method xhr.dataType * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request data type that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ dataType: function(url, appConfigs) {}, /** * Allows the container to override the request method that is used (just * like the `type` parameter to `jQuery.ajax()`. * @method xhr.type * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request method that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ type: function(url, appConfigs) {}, /** * Allows the container to override the url that is used to request an * app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}} * @method xhr.url * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The url that should be used for the request * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ url: function(url, appConfigs) {} }, /** * Allows the container to override the script loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadScripts * @type function * * @example * F2.init({ * loadScripts: function(scripts,inlines,callback){ * //load scripts using $.load() for each script or require(scripts) * callback(); * } * }); */ loadScripts: function(scripts,inlines,callback){}, /** * Allows the container to override the stylesheet loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadStyles * @type function * * @example * F2.init({ * loadStyles: function(styles,callback){ * //load styles using $.load() for each stylesheet or another method * callback(); * } * }); */ loadStyles: function(styles,callback){} } }); /** * Constants used throughout the Open Financial Framework * @class F2.Constants * @static */ F2.extend('Constants', { /** * CSS class constants * @class F2.Constants.Css */ Css: (function() { /** @private */ var _PREFIX = 'f2-'; return { /** * The APP class should be applied to the DOM Element that surrounds the * entire app, including any extra html that surrounds the APP\_CONTAINER * that is inserted by the container. See the * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object. * @property APP * @type string * @static * @final */ APP: _PREFIX + 'app', /** * The APP\_CONTAINER class should be applied to the outermost DOM Element * of the app. * @property APP_CONTAINER * @type string * @static * @final */ APP_CONTAINER: _PREFIX + 'app-container', /** * The APP\_TITLE class should be applied to the DOM Element that contains * the title for an app. If this class is not present, then * F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function. * @property APP_TITLE * @type string * @static * @final */ APP_TITLE: _PREFIX + 'app-title', /** * The APP\_VIEW class should be applied to the DOM Element that contains * a view for an app. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is. * @property APP_VIEW * @type string * @static * @final */ APP_VIEW: _PREFIX + 'app-view', /** * APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that * trigger an * {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE * event. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger. * @property APP_VIEW_TRIGGER * @type string * @static * @final */ APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger', /** * The MASK class is applied to the overlay element that is created * when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is * fired. * @property MASK * @type string * @static * @final */ MASK: _PREFIX + 'mask', /** * The MASK_CONTAINER class is applied to the Element that is passed into * the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method. * @property MASK_CONTAINER * @type string * @static * @final */ MASK_CONTAINER: _PREFIX + 'mask-container' }; })(), /** * Events constants * @class F2.Constants.Events */ Events: (function() { /** @private */ var _APP_EVENT_PREFIX = 'App.'; /** @private */ var _CONTAINER_EVENT_PREFIX = 'Container.'; return { /** * The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an * app. It is up to the app developer to fire this event. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property APP_SYMBOL_CHANGE * @type string * @static * @final */ APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange', /** * The APP\_WIDTH\_CHANGE event will be fired by the container when the * width of an app is changed. The app's instanceId should be concatenated * to this constant. * Returns an object with the gridSize and width in pixels: * * { gridSize:8, width:620 } * * @property APP_WIDTH_CHANGE * @type string * @static * @final */ APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.', /** * The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed * at the container level. This event should only be fired by the * container or container provider. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property CONTAINER_SYMBOL_CHANGE * @type string * @static * @final */ CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange', /** * The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when * the width of the container has changed. * @property CONTAINER_WIDTH_CHANGE * @type string * @static * @final */ CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange' }; })(), JSONP_CALLBACK: 'F2_jsonpCallback_', /** * Constants for use with cross-domain sockets * @class F2.Constants.Sockets * @protected */ Sockets: { /** * The EVENT message is sent whenever * F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired * @property EVENT * @type string * @static * @final */ EVENT: '__event__', /** * The LOAD message is sent when an iframe socket initially loads. * Returns a JSON string that represents: * * [ App, AppManifest] * * @property LOAD * @type string * @static * @final */ LOAD: '__socketLoad__', /** * The RPC message is sent when a method is passed up from within a secure * app page. * @property RPC * @type string * @static * @final */ RPC: '__rpc__', /** * The RPC\_CALLBACK message is sent when a call back from an RPC method is * fired. * @property RPC_CALLBACK * @type string * @static * @final */ RPC_CALLBACK: '__rpcCallback__', /** * The UI\_RPC message is sent when a UI method called. * @property UI_RPC * @type string * @static * @final */ UI_RPC: '__uiRpc__' }, /** * The available view types to apps. The view should be specified by applying * the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the * containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the * Element as well which defines what view type is represented. * The `hide` class can be applied to views that should be hidden by default. * @class F2.Constants.Views */ Views: { /** * The DATA_ATTRIBUTE should be placed on the DOM Element that contains the * view. * @property DATA_ATTRIBUTE * @type string * @static * @final */ DATA_ATTRIBUTE: 'data-f2-view', /** * The ABOUT view gives details about the app. * @property ABOUT * @type string * @static * @final */ ABOUT: 'about', /** * The HELP view provides users with help information for using an app. * @property HELP * @type string * @static * @final */ HELP: 'help', /** * The HOME view is the main view for an app. This view should always * be provided by an app. * @property HOME * @type string * @static * @final */ HOME: 'home', /** * The REMOVE view is a special view that handles the removal of an app * from the container. * @property REMOVE * @type string * @static * @final */ REMOVE: 'remove', /** * The SETTINGS view provides users the ability to modify advanced settings * for an app. * @property SETTINGS * @type string * @static * @final */ SETTINGS: 'settings' } }); /** * Handles [Context](../../app-development.html#context) passing from * containers to apps and apps to apps. * @class F2.Events */ F2.extend('Events', (function() { // init EventEmitter var _events = new EventEmitter2({ wildcard:true }); // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); return { /** * Same as F2.Events.emit except that it will not send the event * to all sockets. * @method _socketEmit * @private * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ _socketEmit: function() { return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Execute each of the listeners that may be listening for the specified * event name in order with the list of arguments. * @method emit * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ emit: function() { F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments)); return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Adds a listener that will execute n times for the event before being * removed. The listener is invoked only the first time the event is * fired, after which it is removed. * @method many * @param {string} event The event name * @param {int} timesToListen The number of times to execute the event * before being removed * @param {function} listener The function to be fired when the event is * emitted */ many: function(event, timesToListen, listener) { return _events.many(event, timesToListen, listener); }, /** * Remove a listener for the specified event. * @method off * @param {string} event The event name * @param {function} listener The function that will be removed */ off: function(event, listener) { return _events.off(event, listener); }, /** * Adds a listener for the specified event * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ on: function(event, listener){ return _events.on(event, listener); }, /** * Adds a one time listener for the event. The listener is invoked only * the first time the event is fired, after which it is removed. * @method once * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ once: function(event, listener) { return _events.once(event, listener); } }; })()); /** * Handles socket communication between the container and secure apps * @class F2.Rpc */ F2.extend('Rpc', (function(){ var _callbacks = {}; var _secureAppPagePath = ''; var _apps = {}; var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT); var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC); var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK); var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD); var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC); /** * Creates a socket connection from the app to the container using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createAppToContainerSocket * @private */ var _createAppToContainerSocket = function() { var appConfig; // socket closure var isLoaded = false; // its possible for messages to be received before the socket load event has // happened. We'll save off these messages and replay them once the socket // is ready var messagePlayback = []; var socket = new easyXDM.Socket({ onMessage: function(message, origin){ // handle Socket Load if (!isLoaded && _rSocketLoad.test(message)) { message = message.replace(_rSocketLoad, ''); var appParts = F2.parse(message); // make sure we have the AppConfig and AppManifest if (appParts.length == 2) { appConfig = appParts[0]; // save socket _apps[appConfig.instanceId] = { config:appConfig, socket:socket }; // register app F2.registerApps([appConfig], [appParts[1]]); // socket message playback jQuery.each(messagePlayback, function(i, e) { _onMessage(appConfig, message, origin); }); isLoaded = true; } } else if (isLoaded) { // pass everyting else to _onMessage _onMessage(appConfig, message, origin); } else { //F2.log('socket not ready, queuing message', message); messagePlayback.push(message); } } }); }; /** * Creates a socket connection from the container to the app using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createContainerToAppSocket * @private * @param {appConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The F2.AppManifest object */ var _createContainerToAppSocket = function(appConfig, appManifest) { var container = jQuery(appConfig.root); if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) { container.find('.' + F2.Constants.Css.APP_CONTAINER); } if (!container.length) { F2.log('Unable to locate app in order to establish secure connection.'); return; } var iframeProps = { scrolling:'no', style:{ width:'100%' } }; if (appConfig.height) { iframeProps.style.height = appConfig.height + 'px'; } var socket = new easyXDM.Socket({ remote: _secureAppPagePath, container: container.get(0), props:iframeProps, onMessage: function(message, origin) { // pass everything to _onMessage _onMessage(appConfig, message, origin); }, onReady: function() { socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer)); } }); return socket; }; /** * @method _createRpcCallback * @private * @param {string} instanceId The app's Instance ID * @param {function} callbackId The callback ID * @return {function} A function to make the RPC call */ var _createRpcCallback = function(instanceId, callbackId) { return function() { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC_CALLBACK, callbackId, [].slice.call(arguments).slice(2) ); }; }; /** * Handles messages that come across the sockets * @method _onMessage * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} message The socket message * @param {string} origin The originator */ var _onMessage = function(appConfig, message, origin) { var obj, func; function parseFunction(parent, functionName) { var path = String(functionName).split('.'); for (var i = 0; i < path.length; i++) { if (parent[path[i]] === undefined) { parent = undefined; break; } parent = parent[path[i]]; } return parent; } function parseMessage(regEx, message, instanceId) { var o = F2.parse(message.replace(regEx, '')); // if obj.callbacks // for each callback // for each params // if callback matches param // replace param with _createRpcCallback(app.instanceId, callback) if (o.params && o.params.length && o.callbacks && o.callbacks.length) { jQuery.each(o.callbacks, function(i, c) { jQuery.each(o.params, function(i, p) { if (c == p) { o.params[i] = _createRpcCallback(instanceId, c); } }); }); } return o; } // handle UI Call if (_rUiCall.test(message)) { obj = parseMessage(_rUiCall, message, appConfig.instanceId); func = parseFunction(appConfig.ui, obj.functionName); // if we found the function, call it if (func !== undefined) { func.apply(appConfig.ui, obj.params); } else { F2.log('Unable to locate UI RPC function: ' + obj.functionName); } // handle RPC } else if (_rRpc.test(message)) { obj = parseMessage(_rRpc, message, appConfig.instanceId); func = parseFunction(window, obj.functionName); if (func !== undefined) { func.apply(func, obj.params); } else { F2.log('Unable to locate RPC function: ' + obj.functionName); } // handle RPC Callback } else if (_rRpcCallback.test(message)) { obj = parseMessage(_rRpcCallback, message, appConfig.instanceId); if (_callbacks[obj.functionName] !== undefined) { _callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params); delete _callbacks[obj.functionName]; } // handle Events } else if (_rEvents.test(message)) { obj = parseMessage(_rEvents, message, appConfig.instanceId); F2.Events._socketEmit.apply(F2.Events, obj); } }; /** * Registers a callback function * @method _registerCallback * @private * @param {function} callback The callback function * @return {string} The callback ID */ var _registerCallback = function(callback) { var callbackId = F2.guid(); _callbacks[callbackId] = callback; return callbackId; }; return { /** * Broadcast an RPC function to all sockets * @method broadcast * @param {string} messageType The message type * @param {Array} params The parameters to broadcast */ broadcast: function(messageType, params) { // check valid messageType var message = messageType + F2.stringify(params); jQuery.each(_apps, function(i, a) { a.socket.postMessage(message); }); }, /** * Calls a remote function * @method call * @param {string} instanceId The app's Instance ID * @param {string} messageType The message type * @param {string} functionName The name of the remote function * @param {Array} params An array of parameters to pass to the remote * function. Any functions found within the params will be treated as a * callback function. */ call: function(instanceId, messageType, functionName, params) { // loop through params and find functions and convert them to callbacks var callbacks = []; jQuery.each(params, function(i, e) { if (typeof e === 'function') { var cid = _registerCallback(e); params[i] = cid; callbacks.push(cid); } }); // check valid messageType _apps[instanceId].socket.postMessage( messageType + F2.stringify({ functionName:functionName, params:params, callbacks:callbacks }) ); }, /** * Init function which tells F2.Rpc whether it is running at the container- * level or the app-level. This method is generally called by * F2.{{#crossLink "F2/init"}}{{/crossLink}} * @method init * @param {string} [secureAppPagePath] The * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath * property */ init: function(secureAppPagePath) { _secureAppPagePath = secureAppPagePath; if (!_secureAppPagePath) { _createAppToContainerSocket(); } }, /** * Determines whether the Instance ID is considered to be 'remote'. This is * determined by checking if 1) the app has an open socket and 2) whether * F2.Rpc is running inside of an iframe * @method isRemote * @param {string} instanceId The Instance ID * @return {bool} True if there is an open socket */ isRemote: function(instanceId) { return ( // we have an app _apps[instanceId] !== undefined && // the app is secure _apps[instanceId].config.isSecure && // we can't access the iframe jQuery(_apps[instanceId].config.root).find('iframe').length === 0 ); }, /** * Creates a container-to-app or app-to-container socket for communication * @method register * @param {F2.AppConfig} [appConfig] The F2.AppConfig object * @param {F2.AppManifest} [appManifest] The F2.AppManifest object */ register: function(appConfig, appManifest) { if (!!appConfig && !!appManifest) { _apps[appConfig.instanceId] = { config:appConfig, socket:_createContainerToAppSocket(appConfig, appManifest) }; } else { F2.log('Unable to register socket connection. Please check container configuration.'); } } }; })()); F2.extend('UI', (function(){ var _containerConfig; /** * UI helper methods * @class F2.UI * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object */ var UI_Class = function(appConfig) { var _appConfig = appConfig; var $root = jQuery(appConfig.root); var _updateHeight = function(height) { height = height || jQuery(_appConfig.root).outerHeight(); if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'updateHeight', [ height ] ); } else { _appConfig.height = height; $root.find('iframe').height(_appConfig.height); } }; return { /** * Removes a overlay from an Element on the page * @method hideMask * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader */ hideMask: function(selector) { F2.UI.hideMask(_appConfig.instanceId, selector); }, /** * Helper methods for creating and using Modals * @class F2.UI.Modals * @for F2.UI */ Modals: (function(){ var _renderAlert = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Alert!</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button class="btn btn-primary btn-ok">OK</button>', '</div>', '</div>' ].join(''); }; var _renderConfirm = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Confirm</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button type="button" class="btn btn-primary btn-ok">OK</button>', '<button type="button" class="btn btn-cancel">Cancel</button">', '</div>', '</div>' ].join(''); }; return { /** * Display an alert message on the page * @method alert * @param {string} message The message to be displayed * @param {function} [callback] The callback to be fired when the user * closes the dialog * @for F2.UI.Modals */ alert: function(message, callback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.alert()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.alert', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderAlert(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-primary').on('click', function() { jQuery(modal).modal('hide').remove(); (callback || jQuery.noop)(); }); }) .modal({backdrop:true}); } }, /** * Display a confirm message on the page * @method confirm * @param {string} message The message to be displayed * @param {function} okCallback The function that will be called when the OK * button is pressed * @param {function} cancelCallback The function that will be called when * the Cancel button is pressed * @for F2.UI.Modals */ confirm: function(message, okCallback, cancelCallback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.confirm()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.confirm', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderConfirm(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-ok').on('click', function() { jQuery(modal).modal('hide').remove(); (okCallback || jQuery.noop)(); }); jQuery(modal).find('.btn-cancel').on('click', function() { jQuery(modal).modal('hide').remove(); (cancelCallback || jQuery.noop)(); }); }) .modal({backdrop:true}); } } }; })(), /** * Sets the title of the app as shown in the browser. Depending on the * container HTML, this method may do nothing if the container has not been * configured properly or else the container provider does not allow Title's * to be set. * @method setTitle * @params {string} title The title of the app * @for F2.UI */ setTitle: function(title) { if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'setTitle', [ title ] ); } else { jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title); } }, /** * Display an ovarlay over an Element on the page * @method showMask * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ showMask: function(selector, showLoader) { F2.UI.showMask(_appConfig.instanceId, selector, showLoader); }, /** * For secure apps, this method updates the size of the iframe that * contains the app. **Note: It is recommended that app developers call * this method anytime Elements are added or removed from the DOM** * @method updateHeight * @params {int} height The height of the app */ updateHeight: _updateHeight, /** * Helper methods for creating and using Views * @class F2.UI.Views * @for F2.UI */ Views: (function(){ var _events = new EventEmitter2(); var _rValidEvents = /change/i; // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); var _isValid = function(eventName) { if (_rValidEvents.test(eventName)) { return true; } else { F2.log('"' + eventName + '" is not a valid F2.UI.Views event name'); return false; } }; return { /** * Change the current view for the app or add an event listener * @method change * @param {string|function} [input] If a string is passed in, the view * will be changed for the app. If a function is passed in, a change * event listener will be added. * @for F2.UI.Views */ change: function(input) { if (typeof input === 'function') { this.on('change', input); } else if (typeof input === 'string') { if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Views.change', [].slice.call(arguments) ); } else if (F2.inArray(input, _appConfig.views)) { jQuery('.' + F2.Constants.Css.APP_VIEW, $root) .addClass('hide') .filter('[data-f2-view="' + input + '"]', $root) .removeClass('hide'); _updateHeight(); _events.emit('change', input); } } }, /** * Removes a view event listener * @method off * @param {string} event The event name * @param {function} listener The function that will be removed * @for F2.UI.Views */ off: function(event, listener) { if (_isValid(event)) { _events.off(event, listener); } }, /** * Adds a view event listener * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted * @for F2.UI.Views */ on: function(event, listener) { if (_isValid(event)) { _events.on(event, listener); } } }; })() }; }; /** * Removes a overlay from an Element on the page * @method hideMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader * @for F2.UI */ UI_Class.hideMask = function(instanceId, selector) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.hideMask()'); return; } if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.hideMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector ] ); } else { var container = jQuery(selector); container.find('> .' + F2.Constants.Css.MASK).remove(); container.removeClass(F2.Constants.Css.MASK_CONTAINER); // if the element contains this data property, we need to reset static // position if (container.data(F2.Constants.Css.MASK_CONTAINER)) { container.css({'position':'static'}); } } }; /** * * @method init * @static * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ UI_Class.init = function(containerConfig) { _containerConfig = containerConfig; // set defaults _containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {}); }; /** * Display an ovarlay over an Element on the page * @method showMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ UI_Class.showMask = function(instanceId, selector, showLoading) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.showMask()'); return; } if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.showMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector, showLoading ] ); } else { if (showLoading && !_containerConfig.UI.Mask.loadingIcon) { F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();'); } var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER); var mask = jQuery('<div>') .height('100%' /*container.outerHeight()*/) .width('100%' /*container.outerWidth()*/) .addClass(F2.Constants.Css.MASK); // set inline styles if useClasses is false if (!_containerConfig.UI.Mask.useClasses) { mask.css({ 'background-color':_containerConfig.UI.Mask.backgroundColor, 'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '', 'background-position':'50% 50%', 'background-repeat':'no-repeat', 'display':'block', 'left':0, 'min-height':30, 'padding':0, 'position':'absolute', 'top':0, 'z-index':_containerConfig.UI.Mask.zIndex, 'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')', 'opacity':_containerConfig.UI.Mask.opacity }); } // only set the position if the container is currently static if (container.css('position') === 'static') { container.css({'position':'relative'}); // setting this data property tells hideMask to set the position // back to static container.data(F2.Constants.Css.MASK_CONTAINER, true); } // add the mask to the container container.append(mask); } }; return UI_Class; })()); /** * Root namespace of the F2 SDK * @module f2 * @class F2 */ F2.extend('', (function() { var _apps = {}; var _config = false; var _bUsesAppHandlers = false; var _sAppHandlerToken = F2.AppHandlers.__f2GetToken(); /** * Appends the app's html to the DOM * @method _afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html * @return {Element} The DOM Element that contains the app */ var _afterAppRender = function(appConfig, html) { var handler = _config.afterAppRender || function(appConfig, html) { return jQuery(html).appendTo('body'); }; var appContainer = handler(appConfig, html); if ( !! _config.afterAppRender && !appContainer) { F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app'); return; } else { // apply APP class and Instance ID jQuery(appContainer).addClass(F2.Constants.Css.APP); return appContainer.get(0); } }; /** * Renders the html for an app. * @method _appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html */ var _appRender = function(appConfig, html) { // apply APP_CONTAINER class html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); // optionally apply wrapper html if (_config.appRender) { html = _config.appRender(appConfig, html); } // apply APP class and instanceId return _outerHtml(html); }; /** * Rendering hook to allow containers to render some html prior to an app * loading * @method _beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ var _beforeAppRender = function(appConfig) { var handler = _config.beforeAppRender || jQuery.noop; return handler(appConfig); }; /** * Handler to inform the container that a script failed to load * @method _onScriptLoadFailure * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param scriptInfo The path of the script that failed to load or the exception info * for the inline script that failed to execute */ var _appScriptLoadFailed = function(appConfig, scriptInfo) { var handler = _config.appScriptLoadFailed || jQuery.noop; return handler(appConfig, scriptInfo); }; /** * Adds properties to the AppConfig object * @method _createAppConfig * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with * necessary properties */ var _createAppConfig = function(appConfig) { // make a copy of the app config to ensure that the original is not modified appConfig = jQuery.extend(true, {}, appConfig); // create the instanceId for the app appConfig.instanceId = appConfig.instanceId || F2.guid(); // default the views if not provided appConfig.views = appConfig.views || []; if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) { appConfig.views.push(F2.Constants.Views.HOME); } return appConfig; }; /** * Adds properties to the ContainerConfig object to take advantage of defaults * @method _hydrateContainerConfig * @private * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ var _hydrateContainerConfig = function(containerConfig) { if (!containerConfig.scriptErrorTimeout) { containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout; } if (containerConfig.debugMode !== true) { containerConfig.debugMode = F2.ContainerConfig.debugMode; } }; /** * Attach app events * @method _initAppEvents * @private */ var _initAppEvents = function(appConfig) { jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) { event.preventDefault(); var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase(); // handle the special REMOVE view if (view == F2.Constants.Views.REMOVE) { F2.removeApp(appConfig.instanceId); } else { appConfig.ui.Views.change(view); } }); }; /** * Attach container Events * @method _initContainerEvents * @private */ var _initContainerEvents = function() { var resizeTimeout; var resizeHandler = function() { F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE); }; jQuery(window).on('resize', function() { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(resizeHandler, 100); }); }; /** * Has the container been init? * @method _isInit * @private * @return {bool} True if the container has been init */ var _isInit = function() { return !!_config; }; /** * Instantiates each app from it's appConfig and stores that in a local private collection * @method _createAppInstance * @private * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects */ var _createAppInstance = function(appConfig, appContent) { // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // instantiate F2.App if (F2.Apps[appConfig.appId] !== undefined) { if (typeof F2.Apps[appConfig.appId] === 'function') { // IE setTimeout(function() { _apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root); if (_apps[appConfig.instanceId].app['init'] !== undefined) { _apps[appConfig.instanceId].app.init(); } }, 0); } else { F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')'); } } }; /** * Loads the app's html/css/javascript * @method loadApp * @private * @param {Array} appConfigs An array of * {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects * @param {F2.AppManifest} [appManifest] The AppManifest object */ var _loadApps = function(appConfigs, appManifest) { appConfigs = [].concat(appConfigs); // check for secure app if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) { _loadSecureApp(appConfigs[0], appManifest); return; } // check that the number of apps in manifest matches the number requested if (appConfigs.length != appManifest.apps.length) { F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest); return; } // Fn for loading manifest Styles var _loadStyles = function(styles, cb) { // Attempt to use the user provided method if (_config.loadStyles) { _config.loadStyles(styles, cb); } else { // load styles, see #101 var stylesFragment = null, useCreateStyleSheet = !! document.createStyleSheet; jQuery.each(styles, function(i, e) { if (useCreateStyleSheet) { document.createStyleSheet(e); } else { stylesFragment = stylesFragment || []; stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>'); } }); if (stylesFragment) { jQuery('head').append(stylesFragment.join('')); } cb(); } }; // Fn for loading manifest Scripts var _loadScripts = function(scripts, cb) { // Attempt to use the user provided method if (_config.loadScripts) { _config.loadScripts(scripts, cb); } else { if (scripts.length) { var scriptCount = scripts.length; var scriptsLoaded = 0; // Check for IE10+ so that we don't rely on onreadystatechange var readyStates = ('addEventListener' in window) ? {} : { 'loaded': true, 'complete': true }; // Log and emit event for the failed (400,500) scripts var _error = function(e) { setTimeout(function() { var evtData = { src: e.target.src, appId: appConfigs[0].appId }; // Send error to console F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\''); // Emit event F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], evtData.src); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], evtData.src ); } }, _config.scriptErrorTimeout); // Defaults to 7000 }; // Load scripts and eval inlines once complete jQuery.each(scripts, function(i, e) { var doc = document, script = doc.createElement('script'), resourceUrl = e; // If in debugMode, add cache buster to each script URL if (_config.debugMode) { resourceUrl += '?cachebuster=' + new Date().getTime(); } // Scripts needed to be loaded in order they're defined in the AppManifest script.async = false; // Add other attrs script.src = resourceUrl; script.type = 'text/javascript'; script.charset = 'utf-8'; script.onerror = _error; // Use a closure for the load event so that we can dereference the original script script.onload = script.onreadystatechange = function(e) { e = e || window.event; // For older IE if (e.type == 'load' || readyStates[script.readyState]) { // Done, cleanup script.onload = script.onreadystatechange = script.onerror = null; // Dereference script script = null; // Are we done loading all scripts for this app? if (++scriptsLoaded === scriptCount) { cb(); } } }; doc.body.appendChild(script); }); } else { cb(); } } }; var _loadInlineScripts = function(inlines, cb) { // Attempt to use the user provided method if (_config.loadInlineScripts) { _config.loadInlineScripts(inlines, cb); } else { for (var i = 0, len = inlines.length; i < len; i++) { try { eval(inlines[i]); } catch (exception) { F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], exception); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], exception ); } } } cb(); } }; // Determine whether an element has been added to the page var elementInDocument = function(element) { if (element) { while (element.parentNode) { element = element.parentNode; if (element === document) { return true; } } } return false; }; // Fn for loading manifest app html var _loadHtml = function(apps) { jQuery.each(apps, function(i, a) { if (!_bUsesAppHandlers) { // load html and save the root node appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html)); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfigs[i], // the app config _outerHtml(a.html) ); var appId = appConfigs[i].appId; var root = appConfigs[i].root; if (!root) { throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.'); } if (!elementInDocument(root)) { throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfigs[i] // the app config ); if (!F2.isNativeDOMNode(root)) { throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.'); } $(root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId); } // init events _initAppEvents(appConfigs[i]); }); }; // Pull out the manifest data var scripts = appManifest.scripts || []; var styles = appManifest.styles || []; var inlines = appManifest.inlineScripts || []; var apps = appManifest.apps || []; // Finally, load the styles, html, and scripts _loadStyles(styles, function() { // Put the html on the page _loadHtml(apps); // Add the script content to the page _loadScripts(scripts, function() { // Load any inline scripts _loadInlineScripts(inlines, function() { // Create the apps jQuery.each(appConfigs, function(i, a) { _createAppInstance(a, appManifest.apps[i]); }); }); }); }); }; /** * Loads the app's html/css/javascript into an iframe * @method loadSecureApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the * page. */ var _loadSecureApp = function(appConfig, appManifest) { // make sure the container is configured for secure apps if (_config.secureAppPagePath) { if (!_bUsesAppHandlers) { // create the html container for the iframe appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>')); } else { var $root = jQuery(appConfig.root); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfig, // the app config appManifest.html ); if ($root.parents('body:first').length === 0) { throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfig // the app config ); if (!appConfig.root) { throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } if (!F2.isNativeDOMNode(appConfig.root)) { throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId); } // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // init events _initAppEvents(appConfig); // create RPC socket F2.Rpc.register(appConfig, appManifest); } else { F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.'); } }; var _outerHtml = function(html) { return jQuery('<div></div>').append(html).html(); }; /** * Checks if the app is valid * @method _validateApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @returns {bool} True if the app is valid */ var _validateApp = function(appConfig) { // check for valid app configurations if (!appConfig.appId) { F2.log('"appId" missing from app object'); return false; } else if (!appConfig.root && !appConfig.manifestUrl) { F2.log('"manifestUrl" missing from app object'); return false; } return true; }; /** * Checks if the ContainerConfig is valid * @method _validateContainerConfig * @private * @returns {bool} True if the config is valid */ var _validateContainerConfig = function() { if (_config) { if (_config.xhr) { if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) { throw ('ContainerConfig.xhr should be a function or an object'); } if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') { throw ('ContainerConfig.xhr.dataType should be a function'); } if (_config.xhr.type && typeof _config.xhr.type !== 'function') { throw ('ContainerConfig.xhr.type should be a function'); } if (_config.xhr.url && typeof _config.xhr.url !== 'function') { throw ('ContainerConfig.xhr.url should be a function'); } } } return true; }; return { /** * Gets the current list of apps in the container * @method getContainerState * @returns {Array} An array of objects containing the appId */ getContainerState: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.getContainerState()'); return; } return jQuery.map(_apps, function(app) { return { appId: app.config.appId }; }); }, /** * Initializes the container. This method must be called before performing * any other actions in the container. * @method init * @param {F2.ContainerConfig} config The configuration object */ init: function(config) { _config = config || {}; _validateContainerConfig(); _hydrateContainerConfig(_config); // dictates whether we use the old logic or the new logic. // TODO: Remove in v2.0 _bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed); // only establish RPC connection if the container supports the secure app page if ( !! _config.secureAppPagePath || _config.isSecureAppPage) { F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false); } F2.UI.init(_config); if (!_config.isSecureAppPage) { _initContainerEvents(); } }, /** * Has the container been init? * @method isInit * @return {bool} True if the container has been init */ isInit: _isInit, /** * Begins the loading process for all apps and/or initialization process for pre-loaded apps. * The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will * contain the app's unique instanceId within the container. If the * {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered * to be a pre-loaded app and will be handled accordingly. Optionally, the * {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those * assets will be used instead of making a request. * @method registerApps * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {Array} [appManifests] An array of * {{#crossLink "F2.AppManifest"}}{{/crossLink}} * objects. This array must be the same length as the apps array that is * objects. This array must be the same length as the apps array that is * passed in. This can be useful if apps are loaded on the server-side and * passed down to the client. * @example * Traditional App requests. * * // Traditional f2 app configs * var arConfigs = [ * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app2', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Pre-loaded and tradition apps mixed. * * // Pre-loaded apps and traditional f2 app configs * // you can preload the same app multiple times as long as you have a unique root for each * var arConfigs = [ * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-1', * manifestUrl: '' * }, * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-2', * manifestUrl: '' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Apps with predefined manifests. * * // Traditional f2 app configs * var arConfigs = [ * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app2', context: {}} * ]; * * // Pre requested manifest responses * var arManifests = [ * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App 2!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/App2Class.js'], * styles: ['http://www.domain.com/css/App2Styles.css'] * } * ]; * * F2.init(); * F2.registerApps(arConfigs, arManifests); */ registerApps: function(appConfigs, appManifests) { if (!_isInit()) { F2.log('F2.init() must be called before F2.registerApps()'); return; } else if (!appConfigs) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; } var appStack = []; var batches = {}; var callbackStack = {}; var haveManifests = false; appConfigs = [].concat(appConfigs); appManifests = [].concat(appManifests || []); haveManifests = !! appManifests.length; // appConfigs must have a length if (!appConfigs.length) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; // ensure that the array of apps and manifests are qual } else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) { F2.log('The length of "apps" does not equal the length of "appManifests"'); return; } // validate each app and assign it an instanceId // then determine which apps can be batched together jQuery.each(appConfigs, function(i, a) { // add properties and methods a = _createAppConfig(a); // Will set to itself, for preloaded apps, or set to null for apps that aren't already // on the page. a.root = a.root || null; // we validate the app after setting the root property because pre-load apps do no require // manifest url if (!_validateApp(a)) { return; // move to the next app } // save app _apps[a.instanceId] = { config: a }; // If the root property is defined then this app is considered to be preloaded and we will // run it through that logic. if (a.root) { if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) { F2.log('AppConfig invalid for pre-load, not a valid string and not dom node'); F2.log('AppConfig instance:', a); throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.'); } else if (jQuery(a.root).length != 1) { F2.log('AppConfig invalid for pre-load, root not unique'); F2.log('AppConfig instance:', a); F2.log('Number of dom node instances:', jQuery(a.root).length); throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.'); } // instantiate F2.App _createAppInstance(a); // init events _initAppEvents(a); // Continue on in the .each loop, no need to continue because the app is on the page // the js in initialized, and it is ready to role. return; // equivalent to continue in .each } if (!_bUsesAppHandlers) { // fire beforeAppRender a.root = _beforeAppRender(a); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_CREATE_ROOT, a // the app config ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_BEFORE, a // the app config ); } // if we have the manifest, go ahead and load the app if (haveManifests) { _loadApps(a, appManifests[i]); } else { // check if this app can be batched if (a.enableBatchRequests && !a.isSecure) { batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || []; batches[a.manifestUrl.toLowerCase()].push(a); } else { appStack.push({ apps: [a], url: a.manifestUrl }); } } }); // we don't have the manifests, go ahead and load them if (!haveManifests) { // add the batches to the appStack jQuery.each(batches, function(i, b) { appStack.push({ url: i, apps: b }); }); // if an app is being loaded more than once on the page, there is the // potential that the jsonp callback will be clobbered if the request // for the AppManifest for the app comes back at the same time as // another request for the same app. We'll create a callbackStack // that will ensure that requests for the same app are loaded in order // rather than at the same time jQuery.each(appStack, function(i, req) { // define the callback function based on the first app's App ID var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId; // push the request onto the callback stack callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || []; callbackStack[jsonpCallback].push(req); }); // loop through each item in the callback stack and make the request // for the AppManifest. When the request is complete, pop the next // request off the stack and make the request. jQuery.each(callbackStack, function(i, requests) { var manifestRequest = function(jsonpCallback, req) { if (!req) { return; } // setup defaults and callbacks var url = req.url, type = 'GET', dataType = 'jsonp', completeFunc = function() { manifestRequest(i, requests.pop()); }, errorFunc = function() { jQuery.each(req.apps, function(idx, item) { F2.log('Removed failed ' + item.name + ' app', item); F2.removeApp(item.instanceId); }); }, successFunc = function(appManifest) { _loadApps(req.apps, appManifest); }; // optionally fire xhr overrides if (_config.xhr && _config.xhr.dataType) { dataType = _config.xhr.dataType(req.url, req.apps); if (typeof dataType !== 'string') { throw ('ContainerConfig.xhr.dataType should return a string'); } } if (_config.xhr && _config.xhr.type) { type = _config.xhr.type(req.url, req.apps); if (typeof type !== 'string') { throw ('ContainerConfig.xhr.type should return a string'); } } if (_config.xhr && _config.xhr.url) { url = _config.xhr.url(req.url, req.apps); if (typeof url !== 'string') { throw ('ContainerConfig.xhr.url should return a string'); } } // setup the default request function if an override is not present var requestFunc = _config.xhr; if (typeof requestFunc !== 'function') { requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) { jQuery.ajax({ url: url, type: type, data: { params: F2.stringify(req.apps, F2.appConfigReplacer) }, jsonp: false, // do not put 'callback=' in the query string jsonpCallback: jsonpCallback, // Unique function name dataType: dataType, success: successCallback, error: function(jqxhr, settings, exception) { F2.log('Failed to load app(s)', exception.toString(), req.apps); errorCallback(); }, complete: completeCallback }); }; } requestFunc(url, req.apps, successFunc, errorFunc, completeFunc); }; manifestRequest(i, requests.pop()); }); } }, /** * Removes all apps from the container * @method removeAllApps */ removeAllApps: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeAllApps()'); return; } jQuery.each(_apps, function(i, a) { F2.removeApp(a.config.instanceId); }); }, /** * Removes an app from the container * @method removeApp * @param {string} instanceId The app's instanceId */ removeApp: function(instanceId) { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeApp()'); return; } if (_apps[instanceId]) { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_BEFORE, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_AFTER, _apps[instanceId] // the app instance ); delete _apps[instanceId]; } } }; })()); exports.F2 = F2; if (typeof define !== 'undefined' && define.amd) { define(function() { return F2; }); } })(typeof exports !== 'undefined' ? exports : window);
import React, { Component } from 'react'; import Ability from './AbilityComponent'; class Member extends React.Component { constructor(props) { super(props); this.props = props; this.api = props.api; } render() { return ( <tr><td> <a href={this.props.member.profile_url}> <span>@</span>{this.props.member.name} <img className="user-profile-image" src={this.props.member.profile_image_url} alt="" width="20px"/> {" "} </a> <span> <MemberControlPanel key={this.props.member.name} api={this.api} member={this.props.member} canDelete={this.props.canDelete} canManage={this.props.canManage} detach={this.props.links.detach+'/'+this.props.member.name} detachUser={this.props.detachUser.bind(this)} updateMembers={this.props.updateMembers.bind(this)}/> </span> </td></tr> ) } } class MemberControlPanel extends React.Component { constructor(props) { super(props); } roles() { let roles = []; if (this.props.member.abilities['create'] === true) { roles.push(<CreatorBadge key={'creator_badge_'+this.props.member.name} />); } if (this.props.member.abilities['manage'] === true) { roles.push(<ManagerBadge key={'manager_badge_'+this.props.member.name} />); } return roles; } render() { return ( <span className="controls"> <span> {(this.props.canManage || this.props.canDelete) && <DeleteButton key={'delete_button_'+this.props.member.name} detach={this.props.detach} detachUser={this.props.detachUser.bind(this)} /> } </span> {(this.props.canDelete) && <Ability key={'ability_'+this.props.member.name} api={this.props.api} member={this.props.member} abilities={this.props.member.abilities} updateMembers={this.props.updateMembers.bind(this)} /> } {this.roles()} </span> ) } } function DeleteButton(props) { return ( <a href={props.detach} className="member-delete-form btn btn-danger btn-xs glyphicon glyphicon-remove" onClick={props.detachUser}></a> ); } function CreatorBadge(props) { return ( <span className="small creator-badge ability-badge member-control-element">creator</span> ); } function ManagerBadge(props) { return ( <span className="small manager-badge ability-badge member-control-element">manager</span> ); } export default Member;
/*! * js-data * @version 2.0.0-beta.8 - Homepage <http://www.js-data.io/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["JSData"] = factory(); else root["JSData"] = factory(); })(this, function() { 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__) { var _datastoreIndex = __webpack_require__(1); var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); /** * The library export. * - window.JSData * - require('js-data') * - define(['js-data', function (JSData) { ... }]); * - import JSData from 'js-data' */ module.exports = { DS: _datastoreIndex['default'], DSUtils: _utils['default'], DSErrors: _errors['default'], createStore: function createStore(options) { return new _datastoreIndex['default'](options); }, version: { full: '2.0.0-beta.8', major: parseInt('2', 10), minor: parseInt('0', 10), patch: parseInt('0', 10), alpha: true ? 'false' : false, beta: true ? '8' : false } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 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'); } } /* jshint eqeqeq:false */ var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); var _sync_methodsIndex = __webpack_require__(4); var _async_methodsIndex = __webpack_require__(5); function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(_x, _x2, _x3, _x4) { var _again = true; _function: while (_again) { var orderBy = _x, index = _x2, a = _x3, b = _x4; def = cA = cB = undefined; _again = false; var def = orderBy[index]; var cA = _utils['default'].get(a, def[0]), cB = _utils['default'].get(b, def[0]); if (_utils['default']._s(cA)) { cA = _utils['default'].upperCase(cA); } if (_utils['default']._s(cB)) { cB = _utils['default'].upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } } } var Defaults = (function () { function Defaults() { _classCallCheck(this, Defaults); } _createClass(Defaults, [{ key: 'errorFn', value: function errorFn(a, b) { if (this.error && typeof this.error === 'function') { try { if (typeof a === 'string') { throw new Error(a); } else { throw a; } } catch (err) { a = err; } this.error(this.name || null, a || null, b || null); } } }]); return Defaults; })(); var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateCollection = lifecycleNoop; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.basePath = ''; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.beforeCreateCollection = lifecycleNoop; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.bypassCache = false; defaultsPrototype.cacheResponse = !!_utils['default'].w; defaultsPrototype.clearEmptyQueries = true; defaultsPrototype.computed = {}; defaultsPrototype.defaultAdapter = 'http'; defaultsPrototype.debug = false; defaultsPrototype.defaultValues = {}; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ''; defaultsPrototype.error = console ? function (a, b, c) { return console[typeof console.error === 'function' ? 'error' : 'log'](a, b, c); } : false; defaultsPrototype.instanceEvents = !!_utils['default'].w; defaultsPrototype.fallbackAdapters = ['http']; defaultsPrototype.findStrictCache = false; defaultsPrototype.idAttribute = 'id'; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.linkRelations = true; defaultsPrototype.log = console ? function (a, b, c, d, e) { return console[typeof console.info === 'function' ? 'info' : 'log'](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { var _this = this; if (_this.debug && _this.log && typeof _this.log === 'function') { _this.log(_this.name || null, a || null, b || null, c || null, d || null); } }; defaultsPrototype.maxAge = false; defaultsPrototype.methods = {}; defaultsPrototype.notify = !!_utils['default'].w; defaultsPrototype.reapAction = !!_utils['default'].w ? 'inject' : 'none'; defaultsPrototype.reapInterval = !!_utils['default'].w ? 30000 : false; defaultsPrototype.relationsEnumerable = false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = 'single'; defaultsPrototype.upsert = !!_utils['default'].w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; params = params || {}; options = options || {}; if (_utils['default']._o(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { _utils['default'].forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (_utils['default'].isEmpty(where)) { where = null; } if (where) { filtered = _utils['default'].filter(filtered, function (attrs) { var first = true; var keep = true; _utils['default'].forOwn(where, function (clause, field) { if (_utils['default']._s(clause)) { clause = { '===': clause }; } else if (_utils['default']._n(clause) || _utils['default'].isBoolean(clause)) { clause = { '==': clause }; } if (_utils['default']._o(clause)) { _utils['default'].forOwn(clause, function (term, op) { var expr = undefined; var isOr = op[0] === '|'; var val = _utils['default'].get(attrs, field); op = isOr ? op.substr(1) : op; if (op === '==') { expr = val == term; } else if (op === '===') { expr = val === term; } else if (op === '!=') { expr = val != term; } else if (op === '!==') { expr = val !== term; } else if (op === '>') { expr = val > term; } else if (op === '>=') { expr = val >= term; } else if (op === '<') { expr = val < term; } else if (op === '<=') { expr = val <= term; } else if (op === 'isectEmpty') { expr = !_utils['default'].intersection(val || [], term || []).length; } else if (op === 'isectNotEmpty') { expr = _utils['default'].intersection(val || [], term || []).length; } else if (op === 'in') { if (_utils['default']._s(term)) { expr = term.indexOf(val) !== -1; } else { expr = _utils['default'].contains(term, val); } } else if (op === 'notIn') { if (_utils['default']._s(term)) { expr = term.indexOf(val) === -1; } else { expr = !_utils['default'].contains(term, val); } } else if (op === 'contains') { if (_utils['default']._s(val)) { expr = val.indexOf(term) !== -1; } else { expr = _utils['default'].contains(val, term); } } else if (op === 'notContains') { if (_utils['default']._s(val)) { expr = val.indexOf(term) === -1; } else { expr = !_utils['default'].contains(val, term); } } if (expr !== undefined) { keep = first ? expr : isOr ? keep || expr : keep && expr; } first = false; }); } }); return keep; }); } var orderBy = null; if (_utils['default']._s(params.orderBy)) { orderBy = [[params.orderBy, 'ASC']]; } else if (_utils['default']._a(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && _utils['default']._s(params.sort)) { orderBy = [[params.sort, 'ASC']]; } else if (!orderBy && _utils['default']._a(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { (function () { var index = 0; _utils['default'].forEach(orderBy, function (def, i) { if (_utils['default']._s(def)) { orderBy[i] = [def, 'ASC']; } else if (!_utils['default']._a(def)) { throw new _errors['default'].IA('DS.filter("' + resourceName + '"[, params][, options]): ' + _utils['default'].toJson(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } }); filtered = _utils['default'].sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); })(); } var limit = _utils['default']._n(params.limit) ? params.limit : null; var skip = null; if (_utils['default']._n(params.skip)) { skip = params.skip; } else if (_utils['default']._n(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = _utils['default'].slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (_utils['default']._n(limit)) { filtered = _utils['default'].slice(filtered, 0, Math.min(filtered.length, limit)); } else if (_utils['default']._n(skip)) { if (skip < filtered.length) { filtered = _utils['default'].slice(filtered, skip); } else { filtered = []; } } return filtered; }; var DS = (function () { function DS(options) { _classCallCheck(this, DS); var _this = this; options = options || {}; _this.store = {}; // alias store, shaves 0.1 kb off the minified build _this.s = _this.store; _this.definitions = {}; // alias definitions, shaves 0.3 kb off the minified build _this.defs = _this.definitions; _this.adapters = {}; _this.defaults = new Defaults(); _this.observe = _utils['default'].observe; _utils['default'].forOwn(options, function (v, k) { _this.defaults[k] = v; }); } _createClass(DS, [{ key: 'getAdapter', value: function getAdapter(options) { var errorIfNotExist = false; options = options || {}; if (_utils['default']._s(options)) { errorIfNotExist = true; options = { adapter: options }; } var adapter = this.adapters[options.adapter]; if (adapter) { return adapter; } else if (errorIfNotExist) { throw new Error('' + options.adapter + ' is not a registered adapter!'); } else { return this.adapters[options.defaultAdapter]; } } }, { key: 'registerAdapter', value: function registerAdapter(name, Adapter, options) { var _this = this; options = options || {}; if (_utils['default'].isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options['default']) { _this.defaults.defaultAdapter = name; } } }, { key: 'is', value: function is(resourceName, instance) { var definition = this.defs[resourceName]; if (!definition) { throw new _errors['default'].NER(resourceName); } return instance instanceof definition[definition['class']]; } }]); return DS; })(); var dsPrototype = DS.prototype; dsPrototype.getAdapter.shorthand = false; dsPrototype.registerAdapter.shorthand = false; dsPrototype.errors = _errors['default']; dsPrototype.utils = _utils['default']; function addMethods(target, obj) { _utils['default'].forOwn(obj, function (v, k) { target[k] = v; target[k].before = function (fn) { var orig = target[k]; target[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return orig.apply(this, fn.apply(this, args) || args); }; }; }); } addMethods(dsPrototype, _sync_methodsIndex['default']); addMethods(dsPrototype, _async_methodsIndex['default']); exports['default'] = DS; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } /* jshint eqeqeq:false */ /** * Mix of ES6 and CommonJS module imports because the interop of Babel + Webpack + ES6 modules + CommonJS isn't very good. */ var _errors = __webpack_require__(3); var BinaryHeap = __webpack_require__(7); var forEach = __webpack_require__(8); var slice = __webpack_require__(9); var forOwn = __webpack_require__(13); var contains = __webpack_require__(10); var deepMixIn = __webpack_require__(14); var pascalCase = __webpack_require__(18); var remove = __webpack_require__(11); var pick = __webpack_require__(15); var sort = __webpack_require__(12); var upperCase = __webpack_require__(19); var get = __webpack_require__(16); var set = __webpack_require__(17); var observe = __webpack_require__(6); var w = undefined; var objectProto = Object.prototype; var toString = objectProto.toString; var P = undefined; /** * Attempt to detect the global Promise constructor. * JSData will still work without one, as long you do something like this: * * var JSData = require('js-data'); * JSData.DSUtils.Promise = MyPromiseLib; */ try { P = Promise; } catch (err) { console.error('js-data requires a global Promise constructor!'); } var isArray = Array.isArray || function isArray(value) { return toString.call(value) == '[object Array]' || false; }; var isRegExp = function isRegExp(value) { return toString.call(value) == '[object RegExp]' || false; }; // adapted from lodash.isBoolean var isBoolean = function isBoolean(value) { return value === true || value === false || value && typeof value == 'object' && toString.call(value) == '[object Boolean]' || false; }; // adapted from lodash.isString var isString = function isString(value) { return typeof value == 'string' || value && typeof value == 'object' && toString.call(value) == '[object String]' || false; }; var isObject = function isObject(value) { return toString.call(value) == '[object Object]' || false; }; // adapted from lodash.isDate var isDate = function isDate(value) { return value && typeof value == 'object' && toString.call(value) == '[object Date]' || false; }; // adapted from lodash.isNumber var isNumber = function isNumber(value) { var type = typeof value; return type == 'number' || value && type == 'object' && toString.call(value) == '[object Number]' || false; }; // adapted from lodash.isFunction var isFunction = function isFunction(value) { return typeof value == 'function' || value && toString.call(value) === '[object Function]' || false; }; // shorthand argument checking functions, using these shaves 1.18 kb off of the minified build var isStringOrNumber = function isStringOrNumber(value) { return isString(value) || isNumber(value); }; var isStringOrNumberErr = function isStringOrNumberErr(field) { return new _errors['default'].IA('"' + field + '" must be a string or a number!'); }; var isObjectErr = function isObjectErr(field) { return new _errors['default'].IA('"' + field + '" must be an object!'); }; var isArrayErr = function isArrayErr(field) { return new _errors['default'].IA('"' + field + '" must be an array!'); }; // adapted from mout.isEmpty var isEmpty = function isEmpty(val) { if (val == null) { // jshint ignore:line // typeof null == 'object' so we check it first return true; } else if (typeof val === 'string' || isArray(val)) { return !val.length; } else if (typeof val === 'object') { var _ret = (function () { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return { v: result }; })(); if (typeof _ret === 'object') return _ret.v; } else { return true; } }; // Find the intersection between two arrays var intersection = function intersection(array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item = undefined; for (var i = 0, _length = array1.length; i < _length; i++) { item = array1[i]; if (contains(result, item)) { continue; } if (contains(array2, item)) { result.push(item); } } return result; }; var filter = function filter(array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; }; /** * Attempt to detect whether we are in the browser. */ try { w = window; w = {}; } catch (e) { w = null; } /** * Event mixin. Usage: * * function handler() { ... } * Events(myObject); * myObject.on('foo', handler); * myObject.emit('foo', 'some', 'data'); * myObject.off('foo', handler); */ function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } /** * Lifecycle hooks that should support promises. */ var toPromisify = ['beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy']; /** * Return whether "prop" is in the blacklist. */ var isBlacklisted = function isBlacklisted(prop, bl) { var i = undefined; if (!bl || !bl.length) { return false; } for (i = 0; i < bl.length; i++) { if (bl[i] === prop) { return true; } } return false; }; // adapted from angular.copy var copy = function copy(source, destination, stackSource, stackDest, blacklist) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest, blacklist); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { destination = copy(source, Object.create(Object.getPrototypeOf(source)), stackSource, stackDest, blacklist); } } } else { if (source === destination) { throw new Error('Cannot copy! Source and destination are identical.'); } stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) { return stackDest[index]; } stackSource.push(source); stackDest.push(destination); } var result = undefined; if (isArray(source)) { var i = undefined; destination.length = 0; for (i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest, blacklist); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function (value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { if (isBlacklisted(key, blacklist)) { continue; } result = copy(source[key], null, stackSource, stackDest, blacklist); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; }; // adapted from angular.equals var equals = function equals(_x, _x2) { var _again = true; _function: while (_again) { var o1 = _x, o2 = _x2; t1 = t2 = length = key = keySet = undefined; _again = false; if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if (o1 !== o1 && o2 !== o2) { return true; } // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if (!isArray(o2)) { return false; } if ((length = o1.length) == o2.length) { // jshint ignore:line for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) { return false; } } return true; } } else if (isDate(o1)) { if (!isDate(o2)) { return false; } _x = o1.getTime(); _x2 = o2.getTime(); _again = true; continue _function; } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(o2)) { return false; } keySet = {}; for (key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) { continue; } if (!equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) { return false; } } return true; } } } return false; } }; /** * Given either an instance or the primary key of an instance, return the primary key. */ var resolveId = function resolveId(definition, idOrInstance) { if (isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }; /** * Given either an instance or the primary key of an instance, return the instance. */ var resolveItem = function resolveItem(resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }; var isValidString = function isValidString(val) { return val != null && val !== ''; // jshint ignore:line }; var join = function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); }; var makePath = function makePath() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var result = join(args, '/'); return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); }; exports['default'] = { Promise: P, /** * Method to wrap an "options" object so that it will inherit from * some parent object, such as a resource definition. */ _: function _(parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new _errors['default'].IA('"options" must be an object!'); } forEach(toPromisify, function (name) { if (typeof options[name] === 'function' && options[name].toString().indexOf('for (var _len = arg') === -1) { options[name] = _this.promisify(options[name]); } }); // Dynamic constructor function var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; // Inherit from some parent object O.prototype = parent; // Give us a way to get the original options back. O.prototype.orig = function () { var orig = {}; forOwn(this, function (value, key) { orig[key] = value; }); return orig; }; return new O(options); }, _n: isNumber, _s: isString, _sn: isStringOrNumber, _snErr: isStringOrNumberErr, _o: isObject, _oErr: isObjectErr, _a: isArray, _aErr: isArrayErr, compute: function compute(fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(get(_this, dep)); }); // compute property set(_this, field, fn[fn.length - 1].apply(_this, args)); }, contains: contains, copy: copy, deepMixIn: deepMixIn, diffObjectFromOldObject: observe.diffObjectFromOldObject, BinaryHeap: BinaryHeap, equals: equals, Events: Events, filter: filter, fillIn: function fillIn(target, obj) { forOwn(obj, function (v, k) { if (!(k in target)) { target[k] = v; } }); return target; }, forEach: forEach, forOwn: forOwn, fromJson: function fromJson(json) { return isString(json) ? JSON.parse(json) : json; }, get: get, intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: pascalCase, pick: pick, // Turn the given node-style callback function into one that can return a promise. promisify: function promisify(fn, target) { var _this = this; if (!fn) { return; } else if (typeof fn !== 'function') { throw new Error('Can only promisify functions!'); } return function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return new _this.Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: remove, set: set, slice: slice, sort: sort, toJson: JSON.stringify, updateTimestamp: function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, upperCase: upperCase, /** * Return a copy of "object" with cycles removed. */ removeCircular: function removeCircular(object) { return (function rmCirc(value, context) { var i = undefined; var nu = undefined; if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { // check if current object points back to itself var current = context.current; var parent = context.context; while (parent) { if (parent.current === current) { return undefined; } parent = parent.context; } if (isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i], { context: context, current: value[i] }); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k], { context: context, current: value[k] }); }); } return nu; } return value; })(object, { context: null, current: object }); }, resolveItem: resolveItem, resolveId: resolveId, w: w, /** * This is where the magic of relations happens. */ applyRelationGettersToTarget: function applyRelationGettersToTarget(store, definition, target) { this.forEach(definition.relationList, function (def) { var relationName = def.relation; var enumerable = typeof def.enumerable === 'boolean' ? def.enumerable : !!definition.relationsEnumerable; if (typeof def.link === 'boolean' ? def.link : !!definition.linkRelations) { delete target[def.localField]; if (def.type === 'belongsTo') { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { return this[def.localKey] ? definition.getResource(relationName).get(this[def.localKey]) : undefined; }, set: function set() {} }); } else if (def.type === 'hasMany') { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { var params = {}; if (def.foreignKey) { params[def.foreignKey] = this[definition.idAttribute]; return definition.getResource(relationName).defaultFilter.call(store, store.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.localKeys) { params.where = _defineProperty({}, definition.getResource(relationName).idAttribute, { 'in': this[def.localKeys] }); return definition.getResource(relationName).defaultFilter.call(store, store.s[relationName].collection, relationName, params); } return undefined; }, set: function set() {} }); } else if (def.type === 'hasOne') { if (def.localKey) { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { return this[def.localKey] ? definition.getResource(relationName).get(this[def.localKey]) : undefined; }, set: function set() {} }); } else { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { var params = {}; params[def.foreignKey] = this[definition.idAttribute]; var items = params[def.foreignKey] ? definition.getResource(relationName).defaultFilter.call(store, store.s[relationName].collection, relationName, params, { allowSimpleWhere: true }) : []; if (items.length) { return items[0]; } return undefined; }, set: function set() {} }); } } } }); } }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; 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; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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) subClass.__proto__ = superClass; } /** * Thrown during a method call when an argument passed into the method is invalid. */ var IllegalArgumentError = (function (_Error) { function IllegalArgumentError(message) { _classCallCheck(this, IllegalArgumentError); _get(Object.getPrototypeOf(IllegalArgumentError.prototype), 'constructor', this).call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'Illegal Argument!'; } _inherits(IllegalArgumentError, _Error); return IllegalArgumentError; })(Error); /** * Thrown when an invariant is violated or unrecoverable error is encountered during execution. */ var RuntimeError = (function (_Error2) { function RuntimeError(message) { _classCallCheck(this, RuntimeError); _get(Object.getPrototypeOf(RuntimeError.prototype), 'constructor', this).call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'RuntimeError Error!'; } _inherits(RuntimeError, _Error2); return RuntimeError; })(Error); /** * Thrown when attempting to access or work with a non-existent resource. */ var NonexistentResourceError = (function (_Error3) { function NonexistentResourceError(resourceName) { _classCallCheck(this, NonexistentResourceError); _get(Object.getPrototypeOf(NonexistentResourceError.prototype), 'constructor', this).call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = '' + resourceName + ' is not a registered resource!'; } _inherits(NonexistentResourceError, _Error3); return NonexistentResourceError; })(Error); exports['default'] = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); var _defineResource = __webpack_require__(25); var _eject = __webpack_require__(26); var _ejectAll = __webpack_require__(27); var _filter = __webpack_require__(28); var _inject = __webpack_require__(29); var NER = _errors['default'].NER; var IA = _errors['default'].IA; var R = _errors['default'].R; function diffIsEmpty(diff) { return !(_utils['default'].isEmpty(diff.added) && _utils['default'].isEmpty(diff.removed) && _utils['default'].isEmpty(diff.changed)); } exports['default'] = { /** * Return the changes for the given item, if any. * * @param resourceName The name of the type of resource of the item whose changes are to be returned. * @param id The primary key of the item whose changes are to be returned. * @param options Optional configuration. * @param options.ignoredChanges Array of strings or regular expressions of fields, the changes of which are to be ignored. * @returns The changes of the given item, if any. */ changes: function changes(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } options = _utils['default']._(definition, options); var item = definition.get(id); if (item) { var _ret = (function () { if (_utils['default'].w) { // force observation handler to be fired for item if there are changes and `Object.observe` is not available _this.s[resourceName].observers[id].deliver(); } var ignoredChanges = options.ignoredChanges || []; // add linked relations to list of ignored changes _utils['default'].forEach(definition.relationFields, function (field) { if (!_utils['default'].contains(ignoredChanges, field)) { ignoredChanges.push(field); } }); // calculate changes var diff = _utils['default'].diffObjectFromOldObject(item, _this.s[resourceName].previousAttributes[id], _utils['default'].equals, ignoredChanges); // remove functions from diff _utils['default'].forOwn(diff, function (changeset, name) { var toKeep = []; _utils['default'].forOwn(changeset, function (value, field) { if (!_utils['default'].isFunction(value)) { toKeep.push(field); } }); diff[name] = _utils['default'].pick(diff[name], toKeep); }); // definitely ignore changes to linked relations _utils['default'].forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return { v: diff }; })(); if (typeof _ret === 'object') return _ret.v; } }, /** * Return the change history of the given item, if any. * * @param resourceName The name of the type of resource of the item whose change history is to be returned. * @param id The primary key of the item whose change history is to be returned. * @returns The change history of the given item, if any. */ changeHistory: function changeHistory(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (resourceName && !_this.defs[resourceName]) { throw new NER(resourceName); } else if (id && !_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } if (!definition.keepChangeHistory) { definition.errorFn('changeHistory is disabled for this resource!'); } else { if (resourceName) { var item = definition.get(id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } }, /** * Re-compute the computed properties of the given item. * * @param resourceName The name of the type of resource of the item whose computed properties are to be re-computed. * @param instance The instance whose computed properties are to be re-computed. * @returns The item whose computed properties were re-computed. */ compute: function compute(resourceName, instance) { var _this = this; var definition = _this.defs[resourceName]; instance = _utils['default'].resolveItem(_this.s[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R('Item not in the store!'); } else if (!_utils['default']._o(instance) && !_utils['default']._sn(instance)) { throw new IA('"instance" must be an object, string or number!'); } // re-compute all computed properties _utils['default'].forOwn(definition.computed, function (fn, field) { _utils['default'].compute.call(instance, fn, field); }); return instance; }, /** * Factory function to create an instance of the specified Resource. * * @param resourceName The name of the type of resource of which to create an instance. * @param attrs Hash of properties with which to initialize the instance. * @param options Optional configuration. * @param options.defaults Default values with which to initialize the instance. * @returns The new instance. */ createInstance: function createInstance(resourceName, attrs, options) { var definition = this.defs[resourceName]; var item = undefined; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !_utils['default'].isObject(attrs)) { throw new IA('"attrs" must be an object!'); } options = _utils['default']._(definition, options); // lifecycle options.beforeCreateInstance(options, attrs); // grab instance constructor function from Resource definition var Constructor = definition[definition['class']]; // create instance item = new Constructor(); // add default values if (options.defaultValues) { _utils['default'].deepMixIn(item, options.defaultValues); } _utils['default'].deepMixIn(item, attrs); // compute computed properties if (definition.computed) { definition.compute(item); } // lifecycle options.afterCreateInstance(options, item); return item; }, /** * Create a new collection of the specified Resource. * * @param resourceName The name of the type of resource of which to create a collection * @param arr Possibly empty array of data from which to create the collection. * @param params The criteria by which to filter items. Will be passed to `DS#findAll` if `fetch` is called. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @param options.notify Whether to call the beforeCreateCollection and afterCreateCollection lifecycle hooks.. * @returns The new collection. */ createCollection: function createCollection(resourceName, arr, params, options) { var _this = this; var definition = _this.defs[resourceName]; arr = arr || []; params = params || {}; if (!definition) { throw new NER(resourceName); } else if (arr && !_utils['default'].isArray(arr)) { throw new IA('"arr" must be an array!'); } options = _utils['default']._(definition, options); // lifecycle options.beforeCreateCollection(options, arr); // define the API for this collection Object.defineProperties(arr, { /** * Call DS#findAll with the params of this collection, filling the collection with the results. */ fetch: { value: function value(params, options) { var __this = this; __this.params = params || __this.params; return definition.findAll(__this.params, options).then(function (data) { if (data === __this) { return __this; } data.unshift(__this.length); data.unshift(0); __this.splice.apply(__this, data); data.shift(); data.shift(); if (data.$$injected) { _this.s[resourceName].queryData[_utils['default'].toJson(__this.params)] = __this; __this.$$injected = true; } return __this; }); } }, // params for this collection. See http://www.js-data.io/docs/query-syntax params: { value: params, writable: true }, // name of the resource type of this collection resourceName: { value: resourceName } }); // lifecycle options.afterCreateCollection(options, arr); return arr; }, defineResource: _defineResource['default'], digest: function digest() { this.observe.Platform.performMicrotaskCheckpoint(); }, eject: _eject['default'], ejectAll: _ejectAll['default'], filter: _filter['default'], /** * Return the item with the given primary key if its in the store. * * @param resourceName The name of the type of resource of the item to retrieve. * @param id The primary key of the item to retrieve. * @param options Optional configuration. * @returns The item with the given primary key if it's in the store. */ get: function get(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } options = _utils['default']._(definition, options); // return the item if it exists return _this.s[resourceName].index[id]; }, /** * Return the items in the store that have the given primary keys. * * @param resourceName The name of the type of resource of the items to retrieve. * @param ids The primary keys of the items to retrieve. * @returns The items with the given primary keys if they're in the store. */ getAll: function getAll(resourceName, ids) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var collection = []; if (!definition) { throw new NER(resourceName); } else if (ids && !_utils['default']._a(ids)) { throw _utils['default']._aErr('ids'); } if (_utils['default']._a(ids)) { // return just the items with the given primary keys var _length = ids.length; for (var i = 0; i < _length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { // most efficient of retrieving ALL items from the store collection = resource.collection.slice(); } return collection; }, /** * Return the whether the item with the given primary key has any changes. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns Whether the item with the given primary key has any changes. */ hasChanges: function hasChanges(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } return definition.get(id) ? diffIsEmpty(definition.changes(id)) : false; }, inject: _inject['default'], /** * Return the timestamp from the last time the item with the given primary key was changed. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns Timestamp from the last time the item was changed. */ lastModified: function lastModified(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; }, /** * Return the timestamp from the last time the item with the given primary key was saved via an adapter. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns Timestamp from the last time the item was saved. */ lastSaved: function lastSaved(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; }, /** * Return the previous attributes of the item with the given primary key before it was changed. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns The previous attributes of the item */ previous: function previous(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } // return resource from cache return resource.previousAttributes[id] ? _utils['default'].copy(resource.previousAttributes[id]) : undefined; } }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var _create = __webpack_require__(33); var _destroy = __webpack_require__(34); var _destroyAll = __webpack_require__(35); var _find = __webpack_require__(36); var _findAll = __webpack_require__(37); var _loadRelations = __webpack_require__(38); var _reap = __webpack_require__(39); var _save = __webpack_require__(40); var _update = __webpack_require__(41); var _updateAll = __webpack_require__(42); exports['default'] = { create: _create['default'], destroy: _destroy['default'], destroyAll: _destroyAll['default'], find: _find['default'], findAll: _findAll['default'], loadRelations: _loadRelations['default'], reap: _reap['default'], refresh: function refresh(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.defs[resourceName]; id = DSUtils.resolveId(_this.defs[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { options = DSUtils._(definition, options); options.bypassCache = true; resolve(_this.get(resourceName, id)); } }).then(function (item) { return item ? _this.find(resourceName, id, options) : item; }); }, save: _save['default'], update: _update['default'], updateAll: _updateAll['default'] }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // Modifications // Copyright 2014-2015 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { var testingExposeCycleCount = global.testingExposeCycleCount; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ return function(fn) { return Promise.resolve().then(fn); } })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, 'delete': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } // Export the observe-js object for **Node.js**, with backwards-compatibility // for the old `require()` API. Also ensure `exports` is not a DOM Element. // If we're in the browser, export as a global object. global.Observer = Observer; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.diffObjectFromOldObject = diffObjectFromOldObject; global.ObjectObserver = ObjectObserver; })(exports); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /*! * yabh * @version 1.0.1 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define("yabh", factory); else if(typeof exports === 'object') exports["BinaryHeap"] = factory(); else root["BinaryHeap"] = factory(); })(this, function() { 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__) { var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; 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; }; })(); Object.defineProperty(exports, '__esModule', { value: true }); /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var _parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(_parent)) { break; } else { heap[parentN] = element; heap[n] = _parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ var bubbleDown = function bubbleDown(heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } }; var BinaryHeap = (function () { function BinaryHeap(weightFunc, compareFunc) { _classCallCheck(this, BinaryHeap); if (!weightFunc) { weightFunc = function (x) { return x; }; } if (!compareFunc) { compareFunc = function (x, y) { return x === y; }; } if (typeof weightFunc !== 'function') { throw new Error('BinaryHeap([weightFunc][, compareFunc]): "weightFunc" must be a function!'); } if (typeof compareFunc !== 'function') { throw new Error('BinaryHeap([weightFunc][, compareFunc]): "compareFunc" must be a function!'); } this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } _createClass(BinaryHeap, [{ key: 'push', value: function push(node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); } }, { key: 'peek', value: function peek() { return this.heap[0]; } }, { key: 'pop', value: function pop() { var front = this.heap[0]; var end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; } }, { key: 'remove', value: function remove(node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; } }, { key: 'removeAll', value: function removeAll() { this.heap = []; } }, { key: 'size', value: function size() { return this.heap.length; } }]); return BinaryHeap; })(); exports['default'] = BinaryHeap; module.exports = exports['default']; /***/ } /******/ ]) }); ; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(20); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(20); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(21); var forIn = __webpack_require__(22); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var forOwn = __webpack_require__(13); var isPlainObject = __webpack_require__(23); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var slice = __webpack_require__(9); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var isPrimitive = __webpack_require__(24); /** * get "nested" object property */ function get(obj, prop){ var parts = prop.split('.'), last = parts.pop(); while (prop = parts.shift()) { obj = obj[prop]; if (obj == null) return; } return obj[last]; } module.exports = get; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var namespace = __webpack_require__(30); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(31); var camelCase = __webpack_require__(32); var upperCase = __webpack_require__(19); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(31); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(21); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the object is a primitive */ function isPrimitive(value) { // Using switch fallthrough because it's simple to read and is // generally fast: http://jsperf.com/testing-value-is-primitive/5 switch (typeof value) { case "string": case "number": case "boolean": return true; } return value == null; } module.exports = isPrimitive; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = defineResource; /*jshint evil:true, loopfunc:true*/ var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); /** * These are DS methods that will be proxied by instances. e.g. * * var store = new JSData.DS(); * var User = store.defineResource('user'); * var user = User.createInstance({ id: 1 }); * * store.update(resourceName, id, attrs[, options]) // DS method * User.update(id, attrs[, options]) // DS method proxied on a Resource * user.DSUpdate(attrs[, options]) // DS method proxied on an Instance */ var instanceMethods = ['compute', 'eject', 'refresh', 'save', 'update', 'destroy', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'previous']; function defineResource(definition) { var _this = this; var definitions = _this.defs; /** * This allows the name-only definition shorthand. * store.defineResource('user') is the same as store.defineResource({ name: 'user'}) */ if (_utils['default']._s(definition)) { definition = { name: definition.replace(/\s/gi, '') }; } if (!_utils['default']._o(definition)) { throw _utils['default']._oErr('definition'); } else if (!_utils['default']._s(definition.name)) { throw new _errors['default'].IA('"name" must be a string!'); } else if (definitions[definition.name]) { throw new _errors['default'].R('' + definition.name + ' is already registered!'); } /** * Dynamic Resource constructor function. * * A Resource inherits from the defaults of the data store that created it. */ function Resource(options) { this.defaultValues = {}; this.methods = {}; this.computed = {}; _utils['default'].deepMixIn(this, options); var parent = _this.defaults; if (definition['extends'] && definitions[definition['extends']]) { parent = definitions[definition['extends']]; } _utils['default'].fillIn(this.defaultValues, parent.defaultValues); _utils['default'].fillIn(this.methods, parent.methods); _utils['default'].fillIn(this.computed, parent.computed); this.endpoint = 'endpoint' in options ? options.endpoint : this.name; } try { var def; var _class; var _ret = (function () { // Resources can inherit from another resource instead of inheriting directly from the data store defaults. if (definition['extends'] && definitions[definition['extends']]) { // Inherit from another resource Resource.prototype = definitions[definition['extends']]; } else { // Inherit from global defaults Resource.prototype = _this.defaults; } definitions[definition.name] = new Resource(definition); def = definitions[definition.name]; if (!_utils['default']._s(def.idAttribute)) { throw new _errors['default'].IA('"idAttribute" must be a string!'); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; _utils['default'].forOwn(def.relations, function (relatedModels, type) { _utils['default'].forOwn(relatedModels, function (defs, relationName) { if (!_utils['default']._a(defs)) { relatedModels[relationName] = [defs]; } _utils['default'].forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.name; def.relationList.push(d); if (d.localField) { def.relationFields.push(d.localField); } }); }); }); if (def.relations.belongsTo) { _utils['default'].forOwn(def.relations.belongsTo, function (relatedModel, modelName) { _utils['default'].forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; def.parentField = relation.localField; } }); }); } if (typeof Object.freeze === 'function') { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getResource = function (resourceName) { return _this.defs[resourceName]; }; def.getEndpoint = function (id, options) { options = options || {}; options.params = options.params || {}; var item = undefined; var parentKey = def.parentKey; var endpoint = options.hasOwnProperty('endpoint') ? options.endpoint : def.endpoint; var parentField = def.parentField; var parentDef = definitions[def.parent]; var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (_utils['default']._sn(id)) { item = def.get(id); } else if (_utils['default']._o(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { var _ret2 = (function () { delete options.endpoint; var _options = {}; _utils['default'].forOwn(options, function (value, key) { _options[key] = value; }); return { v: _utils['default'].makePath(parentDef.getEndpoint(parentId, _utils['default']._(parentDef, _options)), parentId, endpoint) }; })(); if (typeof _ret2 === 'object') return _ret2.v; } else { return endpoint; } } }; // Create the wrapper class for the new resource _class = def['class'] = _utils['default'].pascalCase(def.name); try { if (typeof def.useClass === 'function') { eval('function ' + _class + '() { def.useClass.call(this); }'); def[_class] = eval(_class); def[_class].prototype = (function (proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval('function ' + _class + '() {}'); def[_class] = eval(_class); } } catch (e) { def[_class] = function () {}; } // Apply developer-defined instance methods _utils['default'].forOwn(def.methods, function (fn, m) { def[_class].prototype[m] = fn; }); /** * var user = User.createInstance({ id: 1 }); * user.set('foo', 'bar'); */ def[_class].prototype.set = function (key, value) { var _this2 = this; _utils['default'].set(this, key, value); def.compute(this); if (def.instanceEvents) { setTimeout(function () { _this2.emit('DS.change', def, _this2); }, 0); } def.handleChange(this); return this; }; /** * var user = User.createInstance({ id: 1 }); * user.get('id'); // 1 */ def[_class].prototype.get = function (key) { return _utils['default'].get(this, key); }; if (def.instanceEvents) { _utils['default'].Events(def[_class].prototype); } // Setup the relation links _utils['default'].applyRelationGettersToTarget(_this, def, def[_class].prototype); // Prepare for computed properties _utils['default'].forOwn(def.computed, function (fn, field) { if (_utils['default'].isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { def.errorFn('Computed property "' + field + '" conflicts with previously defined prototype method!'); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(','); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { def.errorFn('Use the computed property array syntax for compatibility with minified code!'); } } deps = fn.slice(0, fn.length - 1); _utils['default'].forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = _utils['default'].filter(deps, function (dep) { return !!dep; }); }); // add instance proxies of DS methods _utils['default'].forEach(instanceMethods, function (name) { def[_class].prototype['DS' + _utils['default'].pascalCase(name)] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this[def.idAttribute] || this); args.unshift(def.name); return _this[name].apply(_this, args); }; }); // manually add instance proxy for DS#create def[_class].prototype.DSCreate = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } args.unshift(this); args.unshift(def.name); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.s[def.name] = { collection: [], expiresHeap: new _utils['default'].BinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; var resource = _this.s[def.name]; // start the reaping if (def.reapInterval) { setInterval(function () { return def.reap(); }, def.reapInterval); } // proxy DS methods with shorthand ones var fns = ['registerAdapter', 'getAdapter', 'is']; for (key in _this) { if (typeof _this[key] === 'function') { fns.push(key); } } /** * Create the Resource shorthands that proxy DS methods. e.g. * * var store = new JSData.DS(); * var User = store.defineResource('user'); * * store.update(resourceName, id, attrs[, options]) // DS method * User.update(id, attrs[, options]) // DS method proxied on a Resource */ _utils['default'].forEach(fns, function (key) { var k = key; if (_this[k].shorthand !== false) { def[k] = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } args.unshift(def.name); return _this[k].apply(_this, args); }; def[k].before = function (fn) { var orig = def[k]; def[k] = function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return orig.apply(def, fn.apply(def, args) || args); }; }; } else { def[k] = function () { for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } return _this[k].apply(_this, args); }; } }); def.beforeValidate = _utils['default'].promisify(def.beforeValidate); def.validate = _utils['default'].promisify(def.validate); def.afterValidate = _utils['default'].promisify(def.afterValidate); def.beforeCreate = _utils['default'].promisify(def.beforeCreate); def.afterCreate = _utils['default'].promisify(def.afterCreate); def.beforeUpdate = _utils['default'].promisify(def.beforeUpdate); def.afterUpdate = _utils['default'].promisify(def.afterUpdate); def.beforeDestroy = _utils['default'].promisify(def.beforeDestroy); def.afterDestroy = _utils['default'].promisify(def.afterDestroy); var defaultAdapter = undefined; if (def.hasOwnProperty('defaultAdapter')) { defaultAdapter = def.defaultAdapter; } // setup "actions" _utils['default'].forOwn(def.actions, function (action, name) { if (def[name] && !def.actions[name]) { throw new Error('Cannot override existing method "' + name + '"!'); } action.request = action.request || function (config) { return config; }; action.response = action.response || function (response) { return response; }; action.responseError = action.responseError || function (err) { return _utils['default'].Promise.reject(err); }; def[name] = function (id, options) { if (_utils['default']._o(id)) { options = id; } options = options || {}; var adapter = def.getAdapter(action.adapter || defaultAdapter || 'http'); var config = _utils['default'].deepMixIn({}, action); if (!options.hasOwnProperty('endpoint') && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === 'function') { config.url = options.getEndpoint(def, options); } else { var args = [options.basePath || adapter.defaults.basePath || def.basePath, def.getEndpoint(_utils['default']._sn(id) ? id : null, options)]; if (_utils['default']._sn(id)) { args.push(id); } args.push(action.pathname || name); config.url = _utils['default'].makePath.apply(null, args); } config.method = config.method || 'GET'; _utils['default'].deepMixIn(config, options); return new _utils['default'].Promise(function (r) { return r(config); }).then(options.request || action.request).then(function (config) { return adapter.HTTP(config); }).then(options.response || action.response, options.responseError || action.responseError); }; }); // mix in events _utils['default'].Events(def); def.handleChange = function (data) { resource.collectionModified = _utils['default'].updateTimestamp(resource.collectionModified); if (def.notify) { setTimeout(function () { def.emit('DS.change', def, data); }, 0); } }; return { v: def }; })(); if (typeof _ret === 'object') return _ret.v; } catch (err) { delete definitions[definition.name]; delete _this.s[definition.name]; throw err; } } /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = eject; /** * Eject an item from the store, if it is currently in the store. * * @param resourceName The name of the resource type of the item eject. * @param id The primary key of the item to eject. * @param options Optional configuration. * @param options.notify Whether to emit the "DS.beforeEject" and "DS.afterEject" events * @param options.clearEmptyQueries Whether to remove cached findAll queries that become empty as a result of this method call. * @returns The ejected item if one was ejected. */ function eject(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } options = DSUtils._(definition, options); // find the item to eject for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { // jshint ignore:line item = resource.collection[i]; // remove its expiration timestamp resource.expiresHeap.remove(item); found = true; break; } } if (found) { var _ret = (function () { // lifecycle definition.beforeEject(options, item); if (options.notify) { definition.emit('DS.beforeEject', definition, item); } // find the item in any ($$injected) cached queries var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } // optionally remove any empty queries if (!items.length && options.clearEmptyQueries) { toRemove.push(queryHash); } }); // clean up DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); if (DSUtils.w) { // stop observation resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; // remove it from the store resource.collection.splice(i, 1); // collection has been modified definition.handleChange(item); // lifecycle definition.afterEject(options, item); if (options.notify) { definition.emit('DS.afterEject', definition, item); } return { v: item }; })(); if (typeof _ret === 'object') return _ret.v; } } /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = ejectAll; /** * Eject a collection of items from the store, if any items currently in the store match the given criteria. * * @param resourceName The name of the resource type of the items eject. * @param params The criteria by which to match items to eject. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @returns The collection of items that were ejected, if any. */ function ejectAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; params = params || {}; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._o(params)) { throw DSUtils._oErr('params'); } var resource = _this.s[resourceName]; var queryHash = DSUtils.toJson(params); // get items that match the criteria var items = definition.filter(params); var ids = []; if (DSUtils.isEmpty(params)) { // remove all completed queries if ejecting all items resource.completedQueries = {}; } else { // remove matching completed query, if any delete resource.completedQueries[queryHash]; } // prepare to remove matching items DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); // eject each matching item DSUtils.forEach(ids, function (id) { definition.eject(id, options); }); // collection has been modified definition.handleChange(items); return items; } /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = filter; /** * Return the subset of items currently in the store that match the given criteria. * * The actual filtering is delegated to DS#defaults.defaultFilter, which can be overridden by developers. * * @param resourceName The name of the resource type of the items to filter. * @param params The criteria by which to filter items. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @returns Matching items. */ function filter(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; if (!definition) { throw new _this.errors.NER(resourceName); } else if (params && !DSUtils._o(params)) { throw DSUtils._oErr('params'); } // Protect against null params = params || {}; options = DSUtils._(definition, options); // delegate filtering to DS#defaults.defaultFilter, which can be overridden by developers. return definition.defaultFilter.call(_this, _this.s[resourceName].collection, resourceName, params, options); } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = inject; var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); /** * This is a beast of a file, but it's where a significant portion of the magic happens. * * DS#inject makes up the core of how data gets into the store. */ /** * This factory function produces an observer handler function tailor-made for the current item being injected. * * The observer handler is what allows computed properties and change tracking to function. * * @param definition Resource definition produced by DS#defineResource * @param resource Resource data as internally stored by the data store * @returns {Function} Observer handler function * @private */ function makeObserverHandler(definition, resource) { var DS = this; // using "var" avoids a JSHint error var name = definition.name; /** * This will be called by observe-js when a new change record is available for the observed object * * @param added Change record for added properties * @param removed Change record for removed properties * @param changed Change record for changed properties * @param oldValueFn Function that can be used to get the previous value of a changed property * @param firstTime Whether this is the first time this function is being called for the given item. Will only be true once. */ return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item = undefined; // Get the previous primary key of the observed item, in-case some knucklehead changed it var innerId = oldValueFn && oldValueFn(definition.idAttribute) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; // Ignore changes to relation links _utils['default'].forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); // Detect whether there are actually any changes if (!_utils['default'].isEmpty(added) || !_utils['default'].isEmpty(removed) || !_utils['default'].isEmpty(changed) || firstTime) { item = DS.get(name, innerId); // update item and collection "modified" timestamps resource.modified[innerId] = _utils['default'].updateTimestamp(resource.modified[innerId]); if (item && definition.instanceEvents) { setTimeout(function () { item.emit('DS.change', definition, item); }, 0); } definition.handleChange(item); // Save a change record for the item if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } // Recompute computed properties if any computed properties depend on changed properties if (definition.computed) { item = item || DS.get(name, innerId); _utils['default'].forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed _utils['default'].forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { _utils['default'].compute.call(item, fn, field); } }); } if (definition.idAttribute in changed) { definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "' + name + '" resource is now in an undefined (probably broken) state.'); } }; } /** * A recursive function for injecting data into the store. * * @param definition Resource definition produced by DS#defineResource * @param resource Resource data as internally stored by the data store * @param attrs The data to be injected. Will be an object or an array of objects. * @param options Optional configuration. * @returns The injected data * @private */ function _inject(definition, resource, attrs, options) { var _this = this; var injected = undefined; if (_utils['default']._a(attrs)) { // have an array of objects, go ahead and inject each one individually and return the resulting array injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // create the observer handler for the data to be injected var _react = makeObserverHandler.call(_this, definition, resource); // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; // compute the primary key if necessary if (c && c[idA]) { (function () { var args = []; _utils['default'].forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); })(); } if (!(idA in attrs)) { // we cannot inject any object into the store that does not have a primary key! var error = new _errors['default'].R('' + definition.name + '.inject: "attrs" must contain the property specified by "idAttribute"!'); options.errorFn(error); throw error; } else { try { // when injecting object that contain their nested relations, this code // will recursively inject them into their proper places in the data store. // Magic! _utils['default'].forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.defs[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new _errors['default'].R('' + definition.name + ' relation is defined but the resource is not!'); } // handle injecting hasMany relations if (_utils['default']._a(toInject)) { (function () { var items = []; _utils['default'].forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.s[relationName].index[toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = relationDef.inject(toInjectItem, options.orig()); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } }); })(); } else { // handle injecting belongsTo and hasOne relations if (toInject !== _this.s[relationName].index[toInject[relationDef.idAttribute]]) { try { var _injected = relationDef.inject(attrs[def.localField], options.orig()); if (def.foreignKey) { _injected[def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } } } }); // primary key of item being injected var id = attrs[idA]; // item being injected var item = definition.get(id); // 0 if the item is new, otherwise the previous last modified timestamp of the item var initialLastModified = item ? resource.modified[id] : 0; // item is new if (!item) { if (attrs instanceof definition[definition['class']]) { item = attrs; } else { item = new definition[definition['class']](); } // remove relation properties from the item, since those relations have been injected by now _utils['default'].forEach(definition.relationList, function (def) { delete attrs[def.localField]; }); // copy remaining properties to the injected item _utils['default'].deepMixIn(item, attrs); // add item to collection resource.collection.push(item); resource.changeHistories[id] = []; // If we're in the browser, start observation if (_utils['default'].w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } // index item resource.index[id] = item; // fire observation handler for the first time _react.call(item, {}, {}, {}, null, true); // save "previous" attributes of the injected item, for change diffs later resource.previousAttributes[id] = _utils['default'].copy(item, null, null, null, definition.relationFields); } else { // item is being re-injected // new properties take precedence _utils['default'].deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { // clear change history for item resource.previousAttributes[id] = _utils['default'].copy(item, null, null, null, definition.relationFields); if (resource.changeHistories[id].length) { _utils['default'].forEach(resource.changeHistories[id], function (changeRecord) { _utils['default'].remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (_utils['default'].w) { // force observation callback to be fired if there are any changes to the item and `Object.observe` is not available resource.observers[id].deliver(); } } // update modified timestamp of item resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? _utils['default'].updateTimestamp(resource.modified[id]) : resource.modified[id]; // reset expiry tracking for item resource.expiresHeap.remove(item); var timestamp = new Date().getTime(); resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); // final injected item injected = item; } catch (err) { options.errorFn(err, attrs); } } } return injected; } /** * Inject the given object or array of objects into the data store. * * @param resourceName The name of the type of resource of the data to be injected. * @param attrs Object or array of objects. Objects must contain a primary key. * @param options Optional configuration. * @param options.notify Whether to emit the "DS.beforeInject" and "DS.afterInject" events. * @returns The injected data. */ function inject(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var injected = undefined; if (!definition) { throw new _errors['default'].NER(resourceName); } else if (!_utils['default']._o(attrs) && !_utils['default']._a(attrs)) { throw new _errors['default'].IA('' + resourceName + '.inject: "attrs" must be an object or an array!'); } options = _utils['default']._(definition, options); // lifecycle options.beforeInject(options, attrs); if (options.notify) { definition.emit('DS.beforeInject', definition, attrs); } // start the recursive injection of data injected = _inject.call(_this, definition, resource, attrs, options); // collection was modified definition.handleChange(injected); // lifecycle options.afterInject(options, injected); if (options.notify) { definition.emit('DS.afterInject', definition, injected); } return injected; } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var forEach = __webpack_require__(8); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(31); var replaceAccents = __webpack_require__(43); var removeNonWord = __webpack_require__(44); var upperCase = __webpack_require__(19); var lowerCase = __webpack_require__(45); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = create; /** * Using an adapter, create a new item. * * Generally a primary key will NOT be provided in the properties hash, * because the adapter's persistence layer should be generating one. * * @param resourceName The name of the type of resource of the new item. * @param attrs Hash of properties with which to create the new item. * @param options Optional configuration. * @param options.cacheResponse Whether the newly created item as returned by the adapter should be injected into the data store. * @param options.upsert If the properties hash contains a primary key, attempt to call DS#update instead. * @param options.notify Whether to emit the "DS.beforeCreate" and "DS.afterCreate" events. * @param options.beforeValidate Lifecycle hook. * @param options.validate Lifecycle hook. * @param options.afterValidate Lifecycle hook. * @param options.beforeCreate Lifecycle hook. * @param options.afterCreate Lifecycle hook. */ function create(resourceName, attrs, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; options = options || {}; attrs = attrs || {}; var rejectionError = undefined; if (!definition) { rejectionError = new _this.errors.NER(resourceName); } else if (!DSUtils._o(attrs)) { rejectionError = DSUtils._oErr('attrs'); } else { options = DSUtils._(definition, options); if (options.upsert && DSUtils._sn(attrs[definition.idAttribute])) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }) // start lifecycle .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.beforeCreate', definition, attrs); } return _this.getAdapter(options).create(definition, attrs, options); }).then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.afterCreate', definition, attrs); } if (options.cacheResponse) { // injected created intem into the store var created = _this.inject(definition.name, attrs, options.orig()); var id = created[definition.idAttribute]; // mark item's `find` query as completed, so a subsequent `find` call for this item will resolve immediately var resource = _this.s[resourceName]; resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return created; } else { // just return an un-injected instance return _this.createInstance(resourceName, attrs, options); } }); } /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = destroy; /** * Using an adapter, destroy an item. * * @param resourceName The name of the type of resource of the item to destroy. * @param id The primary key of the item to destroy. * @param options Optional configuration. * @param options.eagerEject Whether to eject the item from the store before the adapter operation completes, re-injecting if the adapter operation fails. * @param options.notify Whether to emit the "DS.beforeDestroy" and "DS.afterDestroy" events. * @param options.beforeDestroy Lifecycle hook. * @param options.afterDestroy Lifecycle hook. * @returns The primary key of the destroyed item. */ function destroy(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var item = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { // check if the item is in the store item = definition.get(id) || { id: id }; options = DSUtils._(definition, options); resolve(item); } }) // start lifecycle .then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.beforeDestroy', definition, attrs); } // don't wait for the adapter, remove the item from the store if (options.eagerEject) { definition.eject(id); } return definition.getAdapter(options).destroy(definition, id, options); }).then(function () { return options.afterDestroy.call(item, options, item); }).then(function (item) { if (options.notify) { definition.emit('DS.afterDestroy', definition, item); } // make sure the item is removed from the store definition.eject(id); return id; })['catch'](function (err) { // rollback by re-injecting the item into the store if (options && options.eagerEject && item) { definition.inject(item, { notify: false }); } return DSUtils.Promise.reject(err); }); } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = destroyAll; /** * Using an adapter, destroy an item. * * @param resourceName The name of the type of resource of the item to destroy. * @param params The criteria by which to filter items to destroy. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @param options.eagerEject Whether to eject the items from the store before the adapter operation completes, re-injecting if the adapter operation fails. * @param options.notify Whether to emit the "DS.beforeDestroy" and "DS.afterDestroy" events. * @param options.beforeDestroy Lifecycle hook. * @param options.afterDestroy Lifecycle hook. * @returns The ejected items, if any. */ function destroyAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var ejected = undefined, toEject = undefined; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr('attrs')); } else { options = DSUtils._(definition, options); resolve(); } }).then(function () { // find items that are to be ejected from the store toEject = definition.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit('DS.beforeDestroy', definition, toEject); } // don't wait for the adapter, remove the items from the store if (options.eagerEject) { ejected = definition.ejectAll(params); } return definition.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit('DS.afterDestroy', definition, toEject); } // make sure items are removed from the store return ejected || definition.ejectAll(params); })['catch'](function (err) { // rollback by re-injecting the items into the store if (options && options.eagerEject && ejected) { definition.inject(ejected, { notify: false }); } return DSUtils.Promise.reject(err); }); } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = find; /* jshint -W082 */ /** * Using an adapter, retrieve a single item. * * @param resourceName The of the type of resource of the item to retrieve. * @param id The primary key of the item to retrieve. * @param options Optional configuration. * @param options.bypassCache Whether to ignore any cached item and force the retrieval through the adapter. * @param options.cacheResponse Whether to inject the found item into the data store. * @param options.strictCache Whether to only consider items to be "cached" if they were injected into the store as the result of `find` or `findAll`. * @param options.strategy The retrieval strategy to use. * @param options.findStrategy The retrieval strategy to use. Overrides "strategy". * @param options.fallbackAdapters Array of names of adapters to use if using "fallback" strategy. * @param options.findFallbackAdapters Array of names of adapters to use if using "fallback" strategy. Overrides "fallbackAdapters". * @returns The item. */ function find(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { options = DSUtils._(definition, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if ((!options.findStrictCache || id in resource.completedQueries) && definition.get(id) && !options.bypassCache) { // resolve immediately with the cached item resolve(definition.get(id)); } else { // we're going to delegate to the adapter next delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise = undefined; var strategy = options.findStrategy || options.strategy; // try subsequent adapters if the preceeding one fails if (strategy === 'fallback') { (function () { var makeFallbackCall = function (index) { return definition.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { // just make a single attempt promise = definition.getAdapter(options).find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { // inject the item into the data store var injected = definition.inject(data, options.orig()); // mark the item as "cached" resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return injected; } else { // just return an un-injected instance return definition.createInstance(data, options.orig()); } }); } return resource.pendingQueries[id]; } else { // resolve immediately with the item return item; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[id]; } return DSUtils.Promise.reject(err); }); } /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = findAll; /* jshint -W082 */ function processResults(data, resourceName, queryHash, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var idAttribute = _this.defs[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Merge the new values into the cache var injected = definition.inject(data, options.orig()); // Make sure each object is added to completedQueries if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (item) { if (item) { var id = item[idAttribute]; if (id) { resource.completedQueries[id] = date; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); } } }); } else { options.errorFn('response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } /** * Using an adapter, retrieve a collection of items. * * @param resourceName The name of the type of resource of the items to retrieve. * @param params The criteria by which to filter items to retrieve. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @param options.bypassCache Whether to ignore any cached query for these items and force the retrieval through the adapter. * @param options.cacheResponse Whether to inject the found items into the data store. * @returns The items. */ function findAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var queryHash = undefined; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.defs[resourceName]) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr('params')); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); if (options.params) { options.params = DSUtils.copy(options.params); } // force a new request if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { // resolve immediately by filtering data from the data store resolve(definition.filter(params, options.orig())); } else { // resolve immediately by returning the cached array from the previously made query resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise = undefined; var strategy = options.findAllStrategy || options.strategy; // try subsequent adapters if the preceeding one fails if (strategy === 'fallback') { (function () { var makeFallbackCall = function (index) { return definition.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { // just make a single attempt promise = definition.getAdapter(options).findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { // inject the items into the data store resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options); resource.queryData[queryHash].$$injected = true; return resource.queryData[queryHash]; } else { DSUtils.forEach(data, function (item, i) { data[i] = definition.createInstance(item, options.orig()); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { // resolve immediately with the items return items; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } return DSUtils.Promise.reject(err); }); } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = loadRelations; function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } /** * Load the specified relations for the given instance. * * @param resourceName The name of the type of resource of the instance for which to load relations. * @param instance The instance or the primary key of the instance. * @param relations An array of the relations to load. * @param options Optional configuration. * @returns The instance, now with its relations loaded. */ function loadRelations(resourceName, instance, relations, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils._sn(instance)) { instance = definition.get(instance); } if (DSUtils._s(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(instance)) { reject(new DSErrors.IA('"instance(id)" must be a string, number or object!')); } else if (!DSUtils._a(relations)) { reject(new DSErrors.IA('"relations" must be a string or an array!')); } else { (function () { var _options = DSUtils._(definition, options); var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); // relations can be loaded based on resource name or field name if (DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) { var task = undefined; var params = {}; if (__options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { '==': instance[definition.idAttribute] }; } if (def.type === 'hasMany') { if (def.localKeys) { delete params[def.foreignKey]; params.where = _defineProperty({}, relationDef.idAttribute, { 'in': instance[def.localKeys] }); } task = relationDef.findAll(params, __options.orig()); } else if (def.type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = relationDef.find(instance[def.localKey], __options.orig()); } else if (def.foreignKey) { task = relationDef.findAll(params, __options.orig()).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = relationDef.find(instance[def.localKey], __options.orig()); } if (task) { tasks.push(task); } } }); resolve(tasks); })(); } }).then(function (tasks) { return DSUtils.Promise.all(tasks); }).then(function () { return instance; }); } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = reap; /** * Find expired items of the specified resource type and perform the configured action. * * @param resourceName The name of the type of resource of the items to reap. * @param options Optional configuration. * @returns The reaped items. */ function reap(resourceName, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty('notify')) { options.notify = false; } var items = []; var now = new Date().getTime(); var expiredItem = undefined; // find the expired items while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { // only hit lifecycle if there are items if (items.length) { definition.beforeReap(options, items); if (options.notify) { definition.emit('DS.beforeReap', definition, items); } } if (options.reapAction === 'inject') { (function () { var timestamp = new Date().getTime(); DSUtils.forEach(items, function (item) { resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); }); })(); } else if (options.reapAction === 'eject') { DSUtils.forEach(items, function (item) { definition.eject(item[definition.idAttribute]); }); } else if (options.reapAction === 'refresh') { var _ret2 = (function () { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(definition.refresh(item[definition.idAttribute])); }); return { v: DSUtils.Promise.all(tasks) }; })(); if (typeof _ret2 === 'object') return _ret2.v; } return items; }).then(function (items) { // only hit lifecycle if there are items if (items.length) { definition.afterReap(options, items); if (options.notify) { definition.emit('DS.afterReap', definition, items); } } return items; }); } /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = save; /** * Save a single item in its present state. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @param options Optional congifuration. * @returns The item, now saved. */ function save(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined; var noChanges = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else if (!definition.get(id)) { reject(new DSErrors.R('id "' + id + '" not found in cache!')); } else { item = definition.get(id); options = DSUtils._(definition, options); resolve(item); } }) // start lifecycle .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.beforeUpdate', definition, attrs); } // only send changed properties to the adapter if (options.changesOnly) { if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = definition.changes(id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); // no changes? no save if (DSUtils.isEmpty(changes)) { // no changes, return noChanges = true; return attrs; } else { attrs = changes; } } return definition.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit('DS.afterUpdate', definition, attrs); } if (noChanges) { // no changes, just return return attrs; } else if (options.cacheResponse) { // inject the reponse into the store, updating the item var injected = definition.inject(attrs, options.orig()); var _id = injected[definition.idAttribute]; // mark the item as "saved" resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields); } return injected; } else { // just return an instance return definition.createInstance(attrs, options.orig()); } }); } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = update; /** * Update a single item using the supplied properties hash. * * @param resourceName The name of the type of resource of the item to update. * @param id The primary key of the item to update. * @param attrs The attributes with which to update the item. * @param options Optional configuration. * @returns The item, now updated. */ function update(resourceName, id, attrs, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { options = DSUtils._(definition, options); resolve(attrs); } }) // start lifecycle .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.beforeUpdate', definition, attrs); } return definition.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit('DS.afterUpdate', definition, attrs); } if (options.cacheResponse) { // inject the updated item into the store var injected = definition.inject(attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; // mark the item as "saved" resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields); } return injected; } else { // just return an instance return definition.createInstance(attrs, options.orig()); } }); } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = updateAll; /** * Update a collection of items using the supplied properties hash. * * @param resourceName The name of the type of resource of the items to update. * @param attrs The attributes with which to update the item. * @param params The criteria by which to select items to update. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @returns The updated items. */ function updateAll(resourceName, attrs, params, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); resolve(attrs); } }) // start lifecycle .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.beforeUpdate', definition, attrs); } return definition.getAdapter(options).updateAll(definition, attrs, params, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (data) { if (options.notify) { definition.emit('DS.afterUpdate', definition, attrs); } var origOptions = options.orig(); if (options.cacheResponse) { var _ret = (function () { // inject the updated items into the store var injected = definition.inject(data, origOptions); var resource = _this.s[resourceName]; // mark the items as "saved" DSUtils.forEach(injected, function (i) { var id = i[definition.idAttribute]; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(i, null, null, null, definition.relationFields); } }); return { v: injected }; })(); if (typeof _ret === 'object') return _ret.v; } else { var _ret2 = (function () { // just return instances var instances = []; DSUtils.forEach(data, function (item) { instances.push(definition.createInstance(item, origOptions)); }); return { v: instances }; })(); if (typeof _ret2 === 'object') return _ret2.v; } }); } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(31); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(31); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(31); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; /***/ } /******/ ]) });
/*! jQuery v1.11.0 | (c) 2005, 2014 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="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,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=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.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},n.extend=n.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||n.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&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.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(l.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&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},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=s(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:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.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=s(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),n.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||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=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)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(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 mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(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 typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.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},z=b?function(a,b){if(a===b)return j=!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===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.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=db.selectors={cacheLength:50,createPseudo:fb,match:V,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(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===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]||db.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]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(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(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.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+" ").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(),t=!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&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&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]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)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&&(t&&((l[s]||(l[s]={}))[a]=[u,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()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(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),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?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===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.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 X.test(a.nodeName)},input:function(a){return W.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:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(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]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[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?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;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=[u,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[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(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 sb(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 tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(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?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.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]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(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}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(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&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.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){n.each(b,function(b,c){var d=n.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&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.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},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.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?n.extend(a,d):d}},e={};return d.pipe=d.then,n.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&&n.isFunction(a.promise)?e:0,g=1===f?a:n.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]&&n.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 I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.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()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.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=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.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 n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.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=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(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},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.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?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.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]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.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||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.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)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.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=((n.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?n(c,this).index(i)>=0:n.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[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),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||z,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!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.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]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._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 n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.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=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.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,n(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=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={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:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._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++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.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)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.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),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).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=xb(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=xb(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?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.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 n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(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,n.cleanData(vb(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,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.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+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.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 Mb(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=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.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%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.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 Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.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 Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(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+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.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=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.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=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,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||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):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):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.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,n.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 gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.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=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.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],bc.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]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.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 lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),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:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.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(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.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)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._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=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.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)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.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})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.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=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.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||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.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}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.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 n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={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}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.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||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.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=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.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(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.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(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._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(vc," ").indexOf(b)>=0)return!0;return!1}}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.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 wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.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||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.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 Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.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 Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(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 Qc(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}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.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=Dc.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||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.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]?", "+Kc+"; 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=Nc(Jc,k,b,v)){v.readyState=1,h&&m.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=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.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&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(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(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;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 Yc[g],b=void 0,f.onreadystatechange=n.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=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.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 ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.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,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.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,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(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"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.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?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@' ,{requires:['oop']});
/** * 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. * * @emails react-core */ 'use strict'; // TODO: All these warnings should become static errors using Flow instead // of dynamic errors when using JSX with Flow. var React; var ReactFragment; var ReactTestUtils; describe('ReactJSXElementValidator', function() { var Component; var RequiredPropComponent; beforeEach(function() { require('mock-modules').dumpCache(); React = require('React'); ReactFragment = require('ReactFragment'); ReactTestUtils = require('ReactTestUtils'); Component = class { render() { return <div />; } }; RequiredPropComponent = class { render() { return <span>{this.props.prop}</span>; } }; RequiredPropComponent.displayName = 'RequiredPropComponent'; RequiredPropComponent.propTypes = {prop: React.PropTypes.string.isRequired}; }); function frag(obj) { return ReactFragment.create(obj); } it('warns for keys for arrays of elements in children position', function() { spyOn(console, 'error'); void <Component>{[<Component />, <Component />]}</Component>; expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'Each child in an array or iterator should have a unique "key" prop.' ); }); it('warns for keys for arrays of elements with owner info', function() { spyOn(console, 'error'); class InnerComponent { render() { return <Component>{this.props.childSet}</Component>; } } class ComponentWrapper { render() { return ( <InnerComponent childSet={[<Component />, <Component />]} /> ); } } ReactTestUtils.renderIntoDocument(<ComponentWrapper />); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'Each child in an array or iterator should have a unique "key" prop. ' + 'Check the render method of InnerComponent. ' + 'It was passed a child from ComponentWrapper. ' ); }); it('warns for keys for iterables of elements in rest args', function() { spyOn(console, 'error'); var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return {value: done ? undefined : <Component />, done: done}; }, }; }, }; void <Component>{iterable}</Component>; expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'Each child in an array or iterator should have a unique "key" prop.' ); }); it('does not warns for arrays of elements with keys', function() { spyOn(console, 'error'); void <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>; expect(console.error.argsForCall.length).toBe(0); }); it('does not warns for iterable elements with keys', function() { spyOn(console, 'error'); var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return { value: done ? undefined : <Component key={'#' + i} />, done: done, }; }, }; }, }; void <Component>{iterable}</Component>; expect(console.error.argsForCall.length).toBe(0); }); it('warns for numeric keys on objects as children', function() { spyOn(console, 'error'); void <Component>{frag({1: <Component />, 2: <Component />})}</Component>; expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'Child objects should have non-numeric keys so ordering is preserved.' ); }); it('does not warn for numeric keys in entry iterable as a child', function() { spyOn(console, 'error'); var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return {value: done ? undefined : [i, <Component />], done: done}; }, }; }, }; iterable.entries = iterable['@@iterator']; void <Component>{iterable}</Component>; expect(console.error.argsForCall.length).toBe(0); }); it('does not warn when the element is directly as children', function() { spyOn(console, 'error'); void <Component><Component /><Component /></Component>; expect(console.error.argsForCall.length).toBe(0); }); it('does not warn when the child array contains non-elements', function() { spyOn(console, 'error'); void <Component>{[ {}, {} ]}</Component>; expect(console.error.argsForCall.length).toBe(0); }); // TODO: These warnings currently come from the composite component, but // they should be moved into the ReactElementValidator. it('should give context for PropType errors in nested components.', () => { // In this test, we're making sure that if a proptype error is found in a // component, we give a small hint as to which parent instantiated that // component as per warnings about key usage in ReactElementValidator. spyOn(console, 'error'); class MyComp { render() { return <div>My color is {this.color}</div>; } } MyComp.propTypes = { color: React.PropTypes.string, }; class ParentComp { render() { return <MyComp color={123} />; } } ReactTestUtils.renderIntoDocument(<ParentComp />); expect(console.error.calls[0].args[0]).toBe( 'Warning: Failed propType: ' + 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + 'expected `string`. Check the render method of `ParentComp`.' ); }); it('gives a helpful error when passing null, undefined, or boolean', () => { var Undefined = undefined; var Null = null; var True = true; var Num = 123; var Div = 'div'; spyOn(console, 'error'); void <Undefined />; void <Null />; void <True />; void <Num />; expect(console.error.calls.length).toBe(4); expect(console.error.calls[0].args[0]).toContain( 'type should not be null, undefined, boolean, or number. It should be ' + 'a string (for DOM elements) or a ReactClass (for composite components).' ); expect(console.error.calls[1].args[0]).toContain( 'type should not be null, undefined, boolean, or number. It should be ' + 'a string (for DOM elements) or a ReactClass (for composite components).' ); expect(console.error.calls[2].args[0]).toContain( 'type should not be null, undefined, boolean, or number. It should be ' + 'a string (for DOM elements) or a ReactClass (for composite components).' ); expect(console.error.calls[3].args[0]).toContain( 'type should not be null, undefined, boolean, or number. It should be ' + 'a string (for DOM elements) or a ReactClass (for composite components).' ); void <Div />; expect(console.error.calls.length).toBe(4); }); it('should check default prop values', function() { spyOn(console, 'error'); RequiredPropComponent.defaultProps = {prop: null}; ReactTestUtils.renderIntoDocument(<RequiredPropComponent />); expect(console.error.calls.length).toBe(1); expect(console.error.calls[0].args[0]).toBe( 'Warning: Failed propType: ' + 'Required prop `prop` was not specified in `RequiredPropComponent`.' ); }); it('should not check the default for explicit null', function() { spyOn(console, 'error'); ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={null} />); expect(console.error.calls.length).toBe(1); expect(console.error.calls[0].args[0]).toBe( 'Warning: Failed propType: ' + 'Required prop `prop` was not specified in `RequiredPropComponent`.' ); }); it('should check declared prop types', function() { spyOn(console, 'error'); ReactTestUtils.renderIntoDocument(<RequiredPropComponent />); ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={42} />); expect(console.error.calls.length).toBe(2); expect(console.error.calls[0].args[0]).toBe( 'Warning: Failed propType: ' + 'Required prop `prop` was not specified in `RequiredPropComponent`.' ); expect(console.error.calls[1].args[0]).toBe( 'Warning: Failed propType: ' + 'Invalid prop `prop` of type `number` supplied to ' + '`RequiredPropComponent`, expected `string`.' ); ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop="string" />); // Should not error for strings expect(console.error.calls.length).toBe(2); }); it('should warn on invalid prop types', function() { // Since there is no prevalidation step for ES6 classes, there is no hook // for us to issue a warning earlier than element creation when the error // actually occurs. Since this step is skipped in production, we should just // warn instead of throwing for this case. spyOn(console, 'error'); class NullPropTypeComponent { render() { return <span>{this.props.prop}</span>; } } NullPropTypeComponent.propTypes = { prop: null, }; ReactTestUtils.renderIntoDocument(<NullPropTypeComponent />); expect(console.error.calls.length).toBe(1); expect(console.error.calls[0].args[0]).toContain( 'Invariant Violation: NullPropTypeComponent: prop type `prop` is ' + 'invalid; it must be a function, usually from React.PropTypes.' ); }); it('should warn on invalid context types', function() { spyOn(console, 'error'); class NullContextTypeComponent { render() { return <span>{this.props.prop}</span>; } } NullContextTypeComponent.contextTypes = { prop: null, }; ReactTestUtils.renderIntoDocument(<NullContextTypeComponent />); expect(console.error.calls.length).toBe(1); expect(console.error.calls[0].args[0]).toContain( 'Invariant Violation: NullContextTypeComponent: context type `prop` is ' + 'invalid; it must be a function, usually from React.PropTypes.' ); }); it('should warn if getDefaultProps is specificed on the class', function() { spyOn(console, 'error'); class GetDefaultPropsComponent { render() { return <span>{this.props.prop}</span>; } } GetDefaultPropsComponent.getDefaultProps = () => ({ prop: 'foo', }); ReactTestUtils.renderIntoDocument(<GetDefaultPropsComponent />); expect(console.error.calls.length).toBe(1); expect(console.error.calls[0].args[0]).toContain( 'getDefaultProps is only used on classic React.createClass definitions.' + ' Use a static property named `defaultProps` instead.' ); }); });
/*! jQuery v1.11.0 | (c) 2005, 2014 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="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,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=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.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},n.extend=n.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||n.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&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.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(l.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&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},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=s(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:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.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=s(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),n.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||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=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)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(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 mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(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 typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.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},z=b?function(a,b){if(a===b)return j=!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===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.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=db.selectors={cacheLength:50,createPseudo:fb,match:V,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(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===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]||db.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]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(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(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.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+" ").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(),t=!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&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&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]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)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&&(t&&((l[s]||(l[s]={}))[a]=[u,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()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(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),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?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===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.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 X.test(a.nodeName)},input:function(a){return W.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:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(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]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[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?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;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=[u,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[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(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 sb(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 tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(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?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.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]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(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}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(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&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.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){n.each(b,function(b,c){var d=n.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&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.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},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.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?n.extend(a,d):d}},e={};return d.pipe=d.then,n.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&&n.isFunction(a.promise)?e:0,g=1===f?a:n.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]&&n.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 I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.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()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.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=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.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 n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.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=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(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},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.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?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.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]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.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||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.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)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.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=((n.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?n(c,this).index(i)>=0:n.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[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),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||z,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!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.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]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._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 n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.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=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.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,n(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=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={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:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._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++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.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)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.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),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).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=xb(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=xb(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?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.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 n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(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,n.cleanData(vb(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,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.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+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.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 Mb(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=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.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%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.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 Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.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 Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(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+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.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=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.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=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,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||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):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):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.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,n.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 gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.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=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.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],bc.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]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.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 lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),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:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.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(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.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)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._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=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.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)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.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})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.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=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.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||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.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}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.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 n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={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}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.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||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.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=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.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(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.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(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._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(vc," ").indexOf(b)>=0)return!0;return!1}}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.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 wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.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||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.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 Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.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 Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(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 Qc(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}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.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=Dc.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||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.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]?", "+Kc+"; 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=Nc(Jc,k,b,v)){v.readyState=1,h&&m.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=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.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&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(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(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;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 Yc[g],b=void 0,f.onreadystatechange=n.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=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.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 ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.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,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.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,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(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"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.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?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
import React, { PropTypes } from 'react' const PasswordPrompt = ({password, error, unlocking, actions}) => { const onPasswordChange = (e) => actions.handlePasswordChange(e.target.value) const onUnlockClick = () => actions.unlockWallet(password) if (unlocking) { return ( <span className="unlock-status"> Unlocking your wallet, this may take a while (up to several minutes)... </span> ) } return ( <div className="password-prompt"> <h2> Wallet Locked </h2> <span> Enter your wallet password to unlock the wallet. </span> <i className="fa fa-lock fa-4x" /> <input type="password" value={password} className="password-input" onChange={onPasswordChange} /> <button className="unlock-button" onClick={onUnlockClick}>Unlock</button> <div className="password-prompt-error">{error}</div> </div> ) } PasswordPrompt.propTypes = { password: PropTypes.string.isRequired, error: PropTypes.string, } export default PasswordPrompt
// TODO: This module should be ElementChildren, and should use named exports. import React from 'react'; /** * Iterates through children that are typically specified as `props.children`, * but only maps over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @return {object} Object containing the ordered map of results. */ function map(children, func, context) { var index = 0; return React.Children.map(children, function (child) { if (!React.isValidElement(child)) { return child; } return func.call(context, child, index++); }); } /** * Iterates through children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for context. */ function forEach(children, func, context) { var index = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } func.call(context, child, index++); }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function count(children) { var result = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } ++result; }); return result; } /** * Finds children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @returns {array} of children that meet the func return statement */ function filter(children, func, context) { var index = 0; var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result.push(child); } }); return result; } function find(children, func, context) { var index = 0; var result = undefined; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = child; } }); return result; } function every(children, func, context) { var index = 0; var result = true; React.Children.forEach(children, function (child) { if (!result) { return; } if (!React.isValidElement(child)) { return; } if (!func.call(context, child, index++)) { result = false; } }); return result; } function some(children, func, context) { var index = 0; var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = true; } }); return result; } function toArray(children) { var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } result.push(child); }); return result; } export default { map: map, forEach: forEach, count: count, find: find, filter: filter, every: every, some: some, toArray: toArray };
/* Copyright 2014 The Camlistore Authors. 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. */ goog.provide('cam.reactUtil'); goog.require('goog.string'); cam.reactUtil.mapOf = function(validator) { var validator = function(props, propName, componentName) { if (!props[propName]) { return; } React.PropTypes.isObject(props, propName, componentName); for (var child in props[propName]) { var childName = goog.string.subs('%s[%s]', componentName, child); validator(props[propName], child, childName); } }; validator.isRequired = React.PropTypes.object.isRequired; return validator; }; // Returns the appropriate vendor prefixed style property name. This is figured out by testing the presence of various property names on an actual DOM style object. // The returned property is of the form 'fooBar' (if no prefix is needed), or 'WebkitFooBar' if a prefix is needed, which is the form React expects. // @param {string} prop The property name to find. // @param {CSSStyleDeclaration=} style A style object to test on. This can be any DOM style object, e.g., document.body.style. // @return {?string} The appropriate property name to use, or null if the property is not supported in this environment. cam.reactUtil.getVendorProp = function(prop, opt_testStyle) { if (!goog.isDef(opt_testStyle)) { opt_testStyle = document.body.style; } if (goog.isDef(opt_testStyle[prop])) { return prop; } var prefixes = ['webkit', 'moz', 'ie']; for (var i = 0, p; p = prefixes[i]; i++) { var candidate = p + goog.string.toTitleCase(prop); if (goog.isDef(opt_testStyle[candidate])) { // React expects vendor prefixed property names to be TitleCase. return goog.string.toTitleCase(candidate); } } return null; }; // Returns a copy of an object with all properties vendor-prefixed as required by the current ua. // @param {object} o The object to fix. // @param {CSSStyleDeclaration=} style A style object to test on. This can be any DOM style object, e.g., document.body.style. // @return {object} A copy of o with all properties vendor-prefixed as appropriate. cam.reactUtil.getVendorProps = function(o, opt_testStyle) { var n = {}; for (var p in o) { n[cam.reactUtil.getVendorProp(p, opt_testStyle)] = o[p]; } return n; }; // Like cam.object.extend(), except that special care is taken to also merge together some known child properties that are part of React specifications. // @param Object parentSpec // @param Object childSpec // @return Object merged spec cam.reactUtil.extend = function(parentSpec, childSpec) { var result = cam.object.extend(parentSpec, childSpec); if (childSpec.propTypes) { result.propTypes = cam.object.extend(parentSpec.propTypes, childSpec.propTypes); } return result; }
'use strict'; import React from 'react'; import utility from './utility'; const mixin = { propTypes: { className: React.PropTypes.string, utilities: React.PropTypes.string }, getClassName: utility }; export default mixin;
// 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 }, 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 = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), 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; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // 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 = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `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 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } 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)); var isObject = Rx.internals.isObject = function(value) { 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 = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[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'; } var isArguments = function(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; }; } 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; var 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 hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; 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)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); 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) { +index || (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]; this.items[this.length] = undefined; 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 () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.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 len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @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 }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (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; if (!shouldDispose) { var 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 () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * 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 && !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 && !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; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; 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 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[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(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[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](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([state, 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([state, 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([state, 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) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); 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; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var taskId = 0, tasks = new Array(1000); 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, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); var onGlobalPostMessage = function (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(); tasks[handleId] = undefined; } } 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(); channel.port1.onmessage = function (event) { var id = event.data, action = tasks[id]; action(); tasks[id] = undefined; }; scheduleMethod = function (action) { var id = taskId++; tasks[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 localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler.default = (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 = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * 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 self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { 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) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * 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 (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * 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 () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); 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 (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.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( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, 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 enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(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. * @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)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @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, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * 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. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @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. * @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 (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); 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 (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; 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)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @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} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * 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) { 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 NotSupportedError('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; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * 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, parent) { return new AnonymousObservable(subscribe, parent); }; /** * 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 FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } 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; } /** * 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. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @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 FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @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 new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * 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; }); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @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 RangeObservable(start, count, scheduler); }; /** * 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. * @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.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { //deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * 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 'throwError' for browsers <IE9. * @param {Mixed} error 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.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * 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.catchError = 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. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.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); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).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.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * 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) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * 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.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * 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 (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * 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 isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * 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 (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([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.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } 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, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; 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) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * 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 args. * * @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 args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); 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 = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var 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; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } 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); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * 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 (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * 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 (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * 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; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * 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. * @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.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in 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. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon 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. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful 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. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @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.ensure = 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(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(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 (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * 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(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @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).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * 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 (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * 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) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @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) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return 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 {Function} 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 (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); /*try { var result = this.selector(x, this.i++, this.source); } catch (e) { return this.observer.onError(e); } this.observer.onNext(result);*/ }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * 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 {Function} 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 (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * 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 ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * 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, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * 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 ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * 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. * @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 source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @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.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @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 a single element with the final accumulator value. */ observableProto.aggregate = function () { var hasSeed = false, accumulator, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * 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 () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return new AnonymousObservable(function (observer) { function handler() { var results = arguments; if (selector) { try { results = selector(results); } catch (e) { return observer.onError(e); } 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = new Array(len - 1); for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector(results); } catch (e) { return observer.onError(e); } 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 fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation) { event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch (event.type) { case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } 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; /** * 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) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.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) { return observer.onError(err); } } 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) { return observer.onError(err); } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * 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); } 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, source); } 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 (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { o.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } if (isDone && values[1]) { o.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { 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) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { o.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { o.onNext(q.shift()); } o.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { o.onNext(q.shift()); } o.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, source); } 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); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { __super__.call(this, subscribe, source); 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 = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue) { 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; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) this.subject.onCompleted(); else this.queue.push(Rx.Notification.createOnCompleted()); }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) this.subject.onError(error); else this.queue.push(Rx.Notification.createOnError(error)); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value)); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while ((this.queue.length >= numberOfItems && numberOfItems > 0) || (this.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') numberOfItems--; else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } //TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function //if (this.hasFailed) { // this.subject.onError(this.error); //} else if (this.hasCompleted) { // this.subject.onCompleted(); //} return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); var 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; } }); return ControlledSubject; }(Observable)); /** * 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 StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * 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()); }, source) : 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 && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * 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. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().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 && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * 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. * @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 windowSize [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, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * 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, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; 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 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(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * 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.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * 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(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * 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(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), 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__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); 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 ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : 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.prototype, { /** * 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; }, _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) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[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) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); 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, function (o) { return subject.subscribe(o); }); } 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)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if ((candidate & 1) === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new ArgumentOutOfRangeError(); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }, left); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeAll().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; 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 d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, 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. * @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 (isScheduler(periodOrScheduler)) { 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); }, source); } 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. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * 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) ); }, source); } /** * 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 = observableProto.throttleLatest = 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. * @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 == null || typeof other === 'string') && (other = observableThrow(new Error(other || '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); function createTimer() { 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); }, source); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * 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(start, observer.onError.bind(observer), start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @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; 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; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { 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(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, source); }; observableProto.throttleWithSelector = function () { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector.apply(this, arguments); }; /** * 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 (o) { 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) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * 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. * @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 (o) { 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(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @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 containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { 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(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * 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 (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * 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))); }, source); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @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 until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; /* * 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; }, this); }; /* * 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, selectorFunc = bindCallback(selector, thisArg, 3); 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 = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @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). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); 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) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); 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 result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * 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(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * 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(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * 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(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), 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(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); 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.hasValue = false; this.observers = []; this.hasError = false; } 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(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 i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * 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(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 subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); 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; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Elemental = f()}})(function(){var define,module,exports;return (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(require,module,exports){ 'use strict'; exports.Alert = require('./components/Alert'); exports.BlankState = require('./components/BlankState'); exports.Button = require('./components/Button'); exports.ButtonGroup = require('./components/ButtonGroup'); exports.Checkbox = require('./components/Checkbox'); exports.Card = require('./components/Card'); exports.Col = require('./components/Col'); exports.Container = require('./components/Container'); exports.Dropdown = require('./components/Dropdown'); exports.EmailInputGroup = require('./components/EmailInputGroup'); exports.FileDragAndDrop = require('./components/FileDragAndDrop'); exports.FileUpload = require('./components/FileUpload'); exports.Form = require('./components/Form'); exports.FormField = require('./components/FormField'); exports.FormIcon = require('./components/FormIcon'); exports.FormIconField = require('./components/FormIconField'); exports.FormInput = require('./components/FormInput'); exports.FormLabel = require('./components/FormLabel'); exports.FormNote = require('./components/FormNote'); exports.FormRow = require('./components/FormRow'); exports.FormSelect = require('./components/FormSelect'); exports.Glyph = require('./components/Glyph'); exports.InputGroup = require('./components/InputGroup'); exports.InputGroupSection = require('./components/InputGroupSection'); exports.Modal = require('./components/Modal'); exports.ModalBody = require('./components/ModalBody'); exports.ModalFooter = require('./components/ModalFooter'); exports.ModalHeader = require('./components/ModalHeader'); exports.Pagination = require('./components/Pagination'); exports.PasswordInputGroup = require('./components/PasswordInputGroup'); exports.Pill = require('./components/Pill'); exports.Radio = require('./components/Radio'); exports.ResponsiveText = require('./components/ResponsiveText'); exports.Row = require('./components/Row'); exports.RadioGroup = require('./components/RadioGroup'); exports.SegmentedControl = require('./components/SegmentedControl'); exports.Spinner = require('./components/Spinner'); exports.Table = require('./components/Table'); },{"./components/Alert":3,"./components/BlankState":4,"./components/Button":5,"./components/ButtonGroup":6,"./components/Card":7,"./components/Checkbox":8,"./components/Col":9,"./components/Container":10,"./components/Dropdown":11,"./components/EmailInputGroup":12,"./components/FileDragAndDrop":13,"./components/FileUpload":14,"./components/Form":15,"./components/FormField":16,"./components/FormIcon":17,"./components/FormIconField":18,"./components/FormInput":19,"./components/FormLabel":20,"./components/FormNote":21,"./components/FormRow":22,"./components/FormSelect":23,"./components/Glyph":24,"./components/InputGroup":25,"./components/InputGroupSection":26,"./components/Modal":27,"./components/ModalBody":28,"./components/ModalFooter":29,"./components/ModalHeader":30,"./components/Pagination":31,"./components/PasswordInputGroup":32,"./components/Pill":33,"./components/Radio":34,"./components/RadioGroup":35,"./components/ResponsiveText":36,"./components/Row":37,"./components/SegmentedControl":38,"./components/Spinner":39,"./components/Table":40}],2:[function(require,module,exports){ 'use strict'; var list = [{ label: 'Alert', value: 'alert', className: 'octicon octicon-alert' }, { label: 'Arrow Down', value: 'arrow-down', className: 'octicon octicon-arrow-down' }, { label: 'Arrow Left', value: 'arrow-left', className: 'octicon octicon-arrow-left' }, { label: 'Arrow Right', value: 'arrow-right', className: 'octicon octicon-arrow-right' }, { label: 'Arrow Small-down', value: 'arrow-small-down', className: 'octicon octicon-arrow-small-down' }, { label: 'Arrow Small-left', value: 'arrow-small-left', className: 'octicon octicon-arrow-small-left' }, { label: 'Arrow Small-right', value: 'arrow-small-right', className: 'octicon octicon-arrow-small-right' }, { label: 'Arrow Small-up', value: 'arrow-small-up', className: 'octicon octicon-arrow-small-up' }, { label: 'Arrow Up', value: 'arrow-up', className: 'octicon octicon-arrow-up' }, { label: 'Microscope', value: 'microscope', className: 'octicon octicon-microscope' }, { label: 'Beaker', value: 'beaker', className: 'octicon octicon-beaker' }, { label: 'Bell', value: 'bell', className: 'octicon octicon-bell' }, { label: 'Book', value: 'book', className: 'octicon octicon-book' }, { label: 'Bookmark', value: 'bookmark', className: 'octicon octicon-bookmark' }, { label: 'Briefcase', value: 'briefcase', className: 'octicon octicon-briefcase' }, { label: 'Broadcast', value: 'broadcast', className: 'octicon octicon-broadcast' }, { label: 'Browser', value: 'browser', className: 'octicon octicon-browser' }, { label: 'Bug', value: 'bug', className: 'octicon octicon-bug' }, { label: 'Calendar', value: 'calendar', className: 'octicon octicon-calendar' }, { label: 'Check', value: 'check', className: 'octicon octicon-check' }, { label: 'Checklist', value: 'checklist', className: 'octicon octicon-checklist' }, { label: 'Chevron Down', value: 'chevron-down', className: 'octicon octicon-chevron-down' }, { label: 'Chevron Left', value: 'chevron-left', className: 'octicon octicon-chevron-left' }, { label: 'Chevron Right', value: 'chevron-right', className: 'octicon octicon-chevron-right' }, { label: 'Chevron Up', value: 'chevron-up', className: 'octicon octicon-chevron-up' }, { label: 'Circle Slash', value: 'circle-slash', className: 'octicon octicon-circle-slash' }, { label: 'Circuit Board', value: 'circuit-board', className: 'octicon octicon-circuit-board' }, { label: 'Clippy', value: 'clippy', className: 'octicon octicon-clippy' }, { label: 'Clock', value: 'clock', className: 'octicon octicon-clock' }, { label: 'Cloud Download', value: 'cloud-download', className: 'octicon octicon-cloud-download' }, { label: 'Cloud Upload', value: 'cloud-upload', className: 'octicon octicon-cloud-upload' }, { label: 'Code', value: 'code', className: 'octicon octicon-code' }, { label: 'Color Mode', value: 'color-mode', className: 'octicon octicon-color-mode' }, { label: 'Comment Add', value: 'comment-add', className: 'octicon octicon-comment-add' }, { label: 'Comment', value: 'comment', className: 'octicon octicon-comment' }, { label: 'Comment Discussion', value: 'comment-discussion', className: 'octicon octicon-comment-discussion' }, { label: 'Credit Card', value: 'credit-card', className: 'octicon octicon-credit-card' }, { label: 'Dash', value: 'dash', className: 'octicon octicon-dash' }, { label: 'Dashboard', value: 'dashboard', className: 'octicon octicon-dashboard' }, { label: 'Database', value: 'database', className: 'octicon octicon-database' }, { label: 'Clone', value: 'clone', className: 'octicon octicon-clone' }, { label: 'Desktop Download', value: 'desktop-download', className: 'octicon octicon-desktop-download' }, { label: 'Device Camera', value: 'device-camera', className: 'octicon octicon-device-camera' }, { label: 'Device Camera-video', value: 'device-camera-video', className: 'octicon octicon-device-camera-video' }, { label: 'Device Desktop', value: 'device-desktop', className: 'octicon octicon-device-desktop' }, { label: 'Device Mobile', value: 'device-mobile', className: 'octicon octicon-device-mobile' }, { label: 'Diff', value: 'diff', className: 'octicon octicon-diff' }, { label: 'Diff Added', value: 'diff-added', className: 'octicon octicon-diff-added' }, { label: 'Diff Ignored', value: 'diff-ignored', className: 'octicon octicon-diff-ignored' }, { label: 'Diff Modified', value: 'diff-modified', className: 'octicon octicon-diff-modified' }, { label: 'Diff Removed', value: 'diff-removed', className: 'octicon octicon-diff-removed' }, { label: 'Diff Renamed', value: 'diff-renamed', className: 'octicon octicon-diff-renamed' }, { label: 'Ellipsis', value: 'ellipsis', className: 'octicon octicon-ellipsis' }, { label: 'Eye Unwatch', value: 'eye-unwatch', className: 'octicon octicon-eye-unwatch' }, { label: 'Eye Watch', value: 'eye-watch', className: 'octicon octicon-eye-watch' }, { label: 'Eye', value: 'eye', className: 'octicon octicon-eye' }, { label: 'File Binary', value: 'file-binary', className: 'octicon octicon-file-binary' }, { label: 'File Code', value: 'file-code', className: 'octicon octicon-file-code' }, { label: 'File Directory', value: 'file-directory', className: 'octicon octicon-file-directory' }, { label: 'File Media', value: 'file-media', className: 'octicon octicon-file-media' }, { label: 'File Pdf', value: 'file-pdf', className: 'octicon octicon-file-pdf' }, { label: 'File Submodule', value: 'file-submodule', className: 'octicon octicon-file-submodule' }, { label: 'File Symlink-directory', value: 'file-symlink-directory', className: 'octicon octicon-file-symlink-directory' }, { label: 'File Symlink-file', value: 'file-symlink-file', className: 'octicon octicon-file-symlink-file' }, { label: 'File Text', value: 'file-text', className: 'octicon octicon-file-text' }, { label: 'File Zip', value: 'file-zip', className: 'octicon octicon-file-zip' }, { label: 'Flame', value: 'flame', className: 'octicon octicon-flame' }, { label: 'Fold', value: 'fold', className: 'octicon octicon-fold' }, { label: 'Gear', value: 'gear', className: 'octicon octicon-gear' }, { label: 'Gift', value: 'gift', className: 'octicon octicon-gift' }, { label: 'Gist', value: 'gist', className: 'octicon octicon-gist' }, { label: 'Gist Secret', value: 'gist-secret', className: 'octicon octicon-gist-secret' }, { label: 'Git Branch-create', value: 'git-branch-create', className: 'octicon octicon-git-branch-create' }, { label: 'Git Branch-delete', value: 'git-branch-delete', className: 'octicon octicon-git-branch-delete' }, { label: 'Git Branch', value: 'git-branch', className: 'octicon octicon-git-branch' }, { label: 'Git Commit', value: 'git-commit', className: 'octicon octicon-git-commit' }, { label: 'Git Compare', value: 'git-compare', className: 'octicon octicon-git-compare' }, { label: 'Git Merge', value: 'git-merge', className: 'octicon octicon-git-merge' }, { label: 'Git Pull-request-abandoned', value: 'git-pull-request-abandoned', className: 'octicon octicon-git-pull-request-abandoned' }, { label: 'Git Pull-request', value: 'git-pull-request', className: 'octicon octicon-git-pull-request' }, { label: 'Globe', value: 'globe', className: 'octicon octicon-globe' }, { label: 'Graph', value: 'graph', className: 'octicon octicon-graph' }, { label: 'Heart', value: 'heart', className: 'octicon octicon-heart' }, { label: 'History', value: 'history', className: 'octicon octicon-history' }, { label: 'Home', value: 'home', className: 'octicon octicon-home' }, { label: 'Horizontal Rule', value: 'horizontal-rule', className: 'octicon octicon-horizontal-rule' }, { label: 'Hubot', value: 'hubot', className: 'octicon octicon-hubot' }, { label: 'Inbox', value: 'inbox', className: 'octicon octicon-inbox' }, { label: 'Info', value: 'info', className: 'octicon octicon-info' }, { label: 'Issue Closed', value: 'issue-closed', className: 'octicon octicon-issue-closed' }, { label: 'Issue Opened', value: 'issue-opened', className: 'octicon octicon-issue-opened' }, { label: 'Issue Reopened', value: 'issue-reopened', className: 'octicon octicon-issue-reopened' }, { label: 'Jersey', value: 'jersey', className: 'octicon octicon-jersey' }, { label: 'Key', value: 'key', className: 'octicon octicon-key' }, { label: 'Keyboard', value: 'keyboard', className: 'octicon octicon-keyboard' }, { label: 'Law', value: 'law', className: 'octicon octicon-law' }, { label: 'Light Bulb', value: 'light-bulb', className: 'octicon octicon-light-bulb' }, { label: 'Link', value: 'link', className: 'octicon octicon-link' }, { label: 'Link External', value: 'link-external', className: 'octicon octicon-link-external' }, { label: 'List Ordered', value: 'list-ordered', className: 'octicon octicon-list-ordered' }, { label: 'List Unordered', value: 'list-unordered', className: 'octicon octicon-list-unordered' }, { label: 'Location', value: 'location', className: 'octicon octicon-location' }, { label: 'Gist Private', value: 'gist-private', className: 'octicon octicon-gist-private' }, { label: 'Mirror Private', value: 'mirror-private', className: 'octicon octicon-mirror-private' }, { label: 'Git Fork-private', value: 'git-fork-private', className: 'octicon octicon-git-fork-private' }, { label: 'Lock', value: 'lock', className: 'octicon octicon-lock' }, { label: 'Logo Github', value: 'logo-github', className: 'octicon octicon-logo-github' }, { label: 'Mail', value: 'mail', className: 'octicon octicon-mail' }, { label: 'Mail Read', value: 'mail-read', className: 'octicon octicon-mail-read' }, { label: 'Mail Reply', value: 'mail-reply', className: 'octicon octicon-mail-reply' }, { label: 'Mark Github', value: 'mark-github', className: 'octicon octicon-mark-github' }, { label: 'Markdown', value: 'markdown', className: 'octicon octicon-markdown' }, { label: 'Megaphone', value: 'megaphone', className: 'octicon octicon-megaphone' }, { label: 'Mention', value: 'mention', className: 'octicon octicon-mention' }, { label: 'Milestone', value: 'milestone', className: 'octicon octicon-milestone' }, { label: 'Mirror Public', value: 'mirror-public', className: 'octicon octicon-mirror-public' }, { label: 'Mirror', value: 'mirror', className: 'octicon octicon-mirror' }, { label: 'Mortar Board', value: 'mortar-board', className: 'octicon octicon-mortar-board' }, { label: 'Mute', value: 'mute', className: 'octicon octicon-mute' }, { label: 'No Newline', value: 'no-newline', className: 'octicon octicon-no-newline' }, { label: 'Octoface', value: 'octoface', className: 'octicon octicon-octoface' }, { label: 'Organization', value: 'organization', className: 'octicon octicon-organization' }, { label: 'Package', value: 'package', className: 'octicon octicon-package' }, { label: 'Paintcan', value: 'paintcan', className: 'octicon octicon-paintcan' }, { label: 'Pencil', value: 'pencil', className: 'octicon octicon-pencil' }, { label: 'Person Add', value: 'person-add', className: 'octicon octicon-person-add' }, { label: 'Person Follow', value: 'person-follow', className: 'octicon octicon-person-follow' }, { label: 'Person', value: 'person', className: 'octicon octicon-person' }, { label: 'Pin', value: 'pin', className: 'octicon octicon-pin' }, { label: 'Plug', value: 'plug', className: 'octicon octicon-plug' }, { label: 'Repo Create', value: 'repo-create', className: 'octicon octicon-repo-create' }, { label: 'Gist New', value: 'gist-new', className: 'octicon octicon-gist-new' }, { label: 'File Directory-create', value: 'file-directory-create', className: 'octicon octicon-file-directory-create' }, { label: 'File Add', value: 'file-add', className: 'octicon octicon-file-add' }, { label: 'Plus', value: 'plus', className: 'octicon octicon-plus' }, { label: 'Primitive Dot', value: 'primitive-dot', className: 'octicon octicon-primitive-dot' }, { label: 'Primitive Square', value: 'primitive-square', className: 'octicon octicon-primitive-square' }, { label: 'Pulse', value: 'pulse', className: 'octicon octicon-pulse' }, { label: 'Question', value: 'question', className: 'octicon octicon-question' }, { label: 'Quote', value: 'quote', className: 'octicon octicon-quote' }, { label: 'Radio Tower', value: 'radio-tower', className: 'octicon octicon-radio-tower' }, { label: 'Repo Delete', value: 'repo-delete', className: 'octicon octicon-repo-delete' }, { label: 'Repo', value: 'repo', className: 'octicon octicon-repo' }, { label: 'Repo Clone', value: 'repo-clone', className: 'octicon octicon-repo-clone' }, { label: 'Repo Force-push', value: 'repo-force-push', className: 'octicon octicon-repo-force-push' }, { label: 'Gist Fork', value: 'gist-fork', className: 'octicon octicon-gist-fork' }, { label: 'Repo Forked', value: 'repo-forked', className: 'octicon octicon-repo-forked' }, { label: 'Repo Pull', value: 'repo-pull', className: 'octicon octicon-repo-pull' }, { label: 'Repo Push', value: 'repo-push', className: 'octicon octicon-repo-push' }, { label: 'Rocket', value: 'rocket', className: 'octicon octicon-rocket' }, { label: 'Rss', value: 'rss', className: 'octicon octicon-rss' }, { label: 'Ruby', value: 'ruby', className: 'octicon octicon-ruby' }, { label: 'Screen Full', value: 'screen-full', className: 'octicon octicon-screen-full' }, { label: 'Screen Normal', value: 'screen-normal', className: 'octicon octicon-screen-normal' }, { label: 'Search Save', value: 'search-save', className: 'octicon octicon-search-save' }, { label: 'Search', value: 'search', className: 'octicon octicon-search' }, { label: 'Server', value: 'server', className: 'octicon octicon-server' }, { label: 'Settings', value: 'settings', className: 'octicon octicon-settings' }, { label: 'Shield', value: 'shield', className: 'octicon octicon-shield' }, { label: 'Log In', value: 'log-in', className: 'octicon octicon-log-in' }, { label: 'Sign In', value: 'sign-in', className: 'octicon octicon-sign-in' }, { label: 'Log Out', value: 'log-out', className: 'octicon octicon-log-out' }, { label: 'Sign Out', value: 'sign-out', className: 'octicon octicon-sign-out' }, { label: 'Squirrel', value: 'squirrel', className: 'octicon octicon-squirrel' }, { label: 'Star Add', value: 'star-add', className: 'octicon octicon-star-add' }, { label: 'Star Delete', value: 'star-delete', className: 'octicon octicon-star-delete' }, { label: 'Star', value: 'star', className: 'octicon octicon-star' }, { label: 'Stop', value: 'stop', className: 'octicon octicon-stop' }, { label: 'Repo Sync', value: 'repo-sync', className: 'octicon octicon-repo-sync' }, { label: 'Sync', value: 'sync', className: 'octicon octicon-sync' }, { label: 'Tag Remove', value: 'tag-remove', className: 'octicon octicon-tag-remove' }, { label: 'Tag Add', value: 'tag-add', className: 'octicon octicon-tag-add' }, { label: 'Tag', value: 'tag', className: 'octicon octicon-tag' }, { label: 'Telescope', value: 'telescope', className: 'octicon octicon-telescope' }, { label: 'Terminal', value: 'terminal', className: 'octicon octicon-terminal' }, { label: 'Three Bars', value: 'three-bars', className: 'octicon octicon-three-bars' }, { label: 'Thumbsdown', value: 'thumbsdown', className: 'octicon octicon-thumbsdown' }, { label: 'Thumbsup', value: 'thumbsup', className: 'octicon octicon-thumbsup' }, { label: 'Tools', value: 'tools', className: 'octicon octicon-tools' }, { label: 'Trashcan', value: 'trashcan', className: 'octicon octicon-trashcan' }, { label: 'Triangle Down', value: 'triangle-down', className: 'octicon octicon-triangle-down' }, { label: 'Triangle Left', value: 'triangle-left', className: 'octicon octicon-triangle-left' }, { label: 'Triangle Right', value: 'triangle-right', className: 'octicon octicon-triangle-right' }, { label: 'Triangle Up', value: 'triangle-up', className: 'octicon octicon-triangle-up' }, { label: 'Unfold', value: 'unfold', className: 'octicon octicon-unfold' }, { label: 'Unmute', value: 'unmute', className: 'octicon octicon-unmute' }, { label: 'Versions', value: 'versions', className: 'octicon octicon-versions' }, { label: 'Watch', value: 'watch', className: 'octicon octicon-watch' }, { label: 'Remove Close', value: 'remove-close', className: 'octicon octicon-remove-close' }, { label: 'X', value: 'x', className: 'octicon octicon-x' }, { label: 'Zap', value: 'zap', className: 'octicon octicon-zap' }]; var map = {}; list.forEach(function (icon) { map[icon.value] = icon; }); function pluck(arr, key) { return arr.map(function (obj) { return obj[key]; }); } module.exports = { list: list, keys: pluck(list, 'value'), map: map }; },{}],3:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); var ALERT_TYPES = ['danger', 'error', // alias for danger 'info', 'primary', 'success', 'warning']; module.exports = React.createClass({ displayName: 'ElementalAlert', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, type: React.PropTypes.oneOf(ALERT_TYPES).isRequired }, render: function render() { var componentClass = classNames('Alert', 'Alert--' + this.props.type, this.props.className); return React.createElement( 'div', { className: componentClass }, this.props.children ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],4:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); module.exports = React.createClass({ displayName: 'BlankState', propTypes: { children: React.PropTypes.node.isRequired }, render: function render() { return React.createElement('div', _extends({ className: 'BlankState' }, this.props)); } }); module.exports.Heading = React.createClass({ displayName: 'BlankStateHeading', propTypes: { children: React.PropTypes.node.isRequired }, render: function render() { return React.createElement('h2', _extends({ className: 'BlankState__heading' }, this.props)); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],5:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); var blacklist = require('blacklist'); var BUTTON_SIZES = ['lg', 'sm', 'xs']; var BUTTON_TYPES = ['default', 'default-primary', 'default-success', 'default-warning', 'default-danger', 'hollow-primary', 'hollow-success', 'hollow-warning', 'hollow-danger', 'primary', 'success', 'warning', 'danger', 'link', 'link-text', 'link-cancel', 'link-delete']; module.exports = React.createClass({ displayName: 'Button', propTypes: { block: React.PropTypes.bool, className: React.PropTypes.string, href: React.PropTypes.string, isActive: React.PropTypes.bool, size: React.PropTypes.oneOf(BUTTON_SIZES), submit: React.PropTypes.bool, type: React.PropTypes.oneOf(BUTTON_TYPES) }, getDefaultProps: function getDefaultProps() { return { type: 'default' }; }, render: function render() { // classes var componentClass = classNames('Button', 'Button--' + this.props.type, this.props.size ? 'Button--' + this.props.size : null, { 'Button--block': this.props.block, 'is-active': this.props.isActive }, this.props.className); // props var props = blacklist(this.props, 'type', 'size', 'className'); props.className = componentClass; var tag = 'button'; props.type = this.props.submit ? 'submit' : 'button'; if (props.href) { tag = 'a'; props.type = null; } return React.createElement(tag, props, this.props.children); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],6:[function(require,module,exports){ (function (global){ '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 classnames = require('classnames'); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); module.exports = React.createClass({ displayName: 'ButtonGroup', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string }, render: function render() { var className = classnames('ButtonGroup', this.props.className); return React.createElement('div', _extends({}, this.props, { className: className })); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],7:[function(require,module,exports){ (function (global){ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _constants = require('../constants'); var _constants2 = _interopRequireDefault(_constants); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); module.exports = React.createClass({ displayName: 'Card', propTypes: { children: React.PropTypes.node.isRequired, style: React.PropTypes.object }, render: function render() { var style = { backgroundColor: 'white', borderRadius: _constants2['default'].borderRadius.sm, boxShadow: '0 2px 3px rgba(0, 0, 0, 0.075), 0 0 0 1px rgba(0,0,0,0.1)', marginBottom: _constants2['default'].spacing.md, padding: _constants2['default'].spacing.md }; return React.createElement('div', _extends({}, this.props, { style: _extends(style, this.props.style) })); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../constants":41}],8:[function(require,module,exports){ (function (global){ '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 blacklist = require('blacklist'); var classNames = require('classnames'); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var Checkbox = React.createClass({ displayName: 'Checkbox', propTypes: { className: React.PropTypes.string, disabled: React.PropTypes.bool, focusOnMount: React.PropTypes.bool, indeterminate: React.PropTypes.bool, inline: React.PropTypes.bool, label: React.PropTypes.string, style: React.PropTypes.object, title: React.PropTypes.string }, componentDidMount: function componentDidMount() { if (this.props.focusOnMount) { this.refs.target.focus(); } this.setIndeterminate(this.props.indeterminate); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setIndeterminate(nextProps.indeterminate); }, setIndeterminate: function setIndeterminate(value) { this.refs.target.indeterminate = value; }, render: function render() { var componentClass = classNames('Checkbox', { 'Checkbox--disabled': this.props.disabled, 'Checkbox--inline': this.props.inline }, this.props.className); var props = blacklist(this.props, 'className', 'label', 'style', 'title'); return React.createElement( 'label', { className: componentClass, style: this.props.style, title: this.props.title }, React.createElement('input', _extends({ ref: 'target', type: 'checkbox', className: 'Checkbox__input' }, props)), this.props.label && React.createElement( 'span', { className: 'Checkbox__label' }, this.props.label ) ); } }); module.exports = Checkbox; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],9:[function(require,module,exports){ (function (global){ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _constants = require('../constants'); var _constants2 = _interopRequireDefault(_constants); module.exports = _react2['default'].createClass({ displayName: 'Col', propTypes: { /* eslint-disable react/jsx-sort-prop-types */ basis: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, // allow pixels _react2['default'].PropTypes.string]), // allow percentage children: _react2['default'].PropTypes.node, gutter: _react2['default'].PropTypes.number, style: _react2['default'].PropTypes.object, lg: _react2['default'].PropTypes.string, // width as a percentage or fraction md: _react2['default'].PropTypes.string, // width as a percentage or fraction sm: _react2['default'].PropTypes.string, // width as a percentage or fraction xs: _react2['default'].PropTypes.string }, // width as a percentage or fraction /* eslint-enable */ getDefaultProps: function getDefaultProps() { return { gutter: _constants2['default'].width.gutter }; }, getInitialState: function getInitialState() { return { windowWidth: window.innerWidth }; }, componentDidMount: function componentDidMount() { window.addEventListener('resize', this.handleResize); }, componentWillUnmount: function componentWillUnmount() { window.removeEventListener('resize', this.handleResize); }, handleResize: function handleResize() { this.setState({ windowWidth: window.innerWidth }); }, render: function render() { var _props = this.props; var basis = _props.basis; var gutter = _props.gutter; var xs = _props.xs; var sm = _props.sm; var md = _props.md; var lg = _props.lg; var windowWidth = this.state.windowWidth; var columnStyle = { minHeight: 1, paddingLeft: gutter / 2, paddingRight: gutter / 2 }; // if no width control is provided fill available space if (!basis && !xs && !sm && !md && !lg) { columnStyle.flex = '1 1 auto'; columnStyle.msFlex = '1 1 auto'; columnStyle.WebkitFlex = '1 1 auto'; } // set widths / flex-basis if (basis) { columnStyle.flex = '1 0 ' + basis; columnStyle.msFlex = '1 0 ' + basis; columnStyle.WebkitFlex = '1 0 ' + basis; } else if (windowWidth < _constants2['default'].breakpoint.xs) { columnStyle.width = xs; } else if (windowWidth < _constants2['default'].breakpoint.sm) { columnStyle.width = sm || xs; } else if (windowWidth < _constants2['default'].breakpoint.md) { columnStyle.width = md || sm || xs; } else { columnStyle.width = lg || md || sm || xs; } if (!columnStyle.width) { columnStyle.width = '100%'; } if (columnStyle.width in _constants2['default'].fractions) { columnStyle.width = _constants2['default'].fractions[columnStyle.width]; } var props = (0, _blacklist2['default'])(this.props, 'basis', 'gutter', 'style', 'xs', 'sm', 'md', 'lg'); return _react2['default'].createElement('div', _extends({ style: _extends(columnStyle, this.props.style) }, props)); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../constants":41,"blacklist":undefined}],10:[function(require,module,exports){ (function (global){ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _constants = require('../constants'); var _constants2 = _interopRequireDefault(_constants); module.exports = _react2['default'].createClass({ displayName: 'Container', propTypes: { children: _react2['default'].PropTypes.node.isRequired, clearfix: _react2['default'].PropTypes.bool, gutter: _react2['default'].PropTypes.number, maxWidth: _react2['default'].PropTypes.number, style: _react2['default'].PropTypes.object }, getDefaultProps: function getDefaultProps() { return { gutter: _constants2['default'].width.gutter, maxWidth: _constants2['default'].width.container }; }, render: function render() { var _props = this.props; var gutter = _props.gutter; var maxWidth = _props.maxWidth; var containerStyle = { marginLeft: 'auto', marginRight: 'auto', paddingLeft: gutter, paddingRight: gutter, maxWidth: maxWidth }; var clearfixStyle = { clear: 'both', display: 'table' }; var props = (0, _blacklist2['default'])(this.props, 'gutter', 'maxWidth', 'style'); return this.props.clearfix ? _react2['default'].createElement( 'div', _extends({ style: _extends(containerStyle, this.props.style) }, props), _react2['default'].createElement('span', { style: clearfixStyle }), this.props.children, _react2['default'].createElement('span', { style: clearfixStyle }) ) : _react2['default'].createElement('div', _extends({ style: _extends(containerStyle, this.props.style) }, props)); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../constants":41,"blacklist":undefined}],11:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var Transition = require('react-addons-css-transition-group'); var blacklist = require('blacklist'); var classNames = require('classnames'); var Button = require('./Button'); var ESC_KEYCODE = 27; module.exports = React.createClass({ displayName: 'Dropdown', propTypes: { alignRight: React.PropTypes.bool, buttonHasDisclosureArrow: React.PropTypes.bool, buttonLabel: React.PropTypes.string, buttonType: React.PropTypes.string, children: React.PropTypes.element, className: React.PropTypes.string, isOpen: React.PropTypes.bool, items: React.PropTypes.array.isRequired, onSelect: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { buttonHasDisclosureArrow: true, onSelect: function onSelect() {} }; }, getInitialState: function getInitialState() { return { isOpen: this.props.isOpen || false }; }, openDropdown: function openDropdown() { this.setState({ isOpen: true }); }, closeDropdown: function closeDropdown() { this.setState({ isOpen: false }); }, componentWillUpdate: function componentWillUpdate(nextProps, nextState) { if (nextState.isOpen) { window.addEventListener('keydown', this.handleKeyDown); } else { window.removeEventListener('keydown', this.handleKeyDown); } }, handleKeyDown: function handleKeyDown(e) { if (e.keyCode === ESC_KEYCODE) { this.closeDropdown(); } }, renderChildren: function renderChildren() { var _this = this; return React.Children.map(this.props.children, function (child) { return React.cloneElement(child, { onClick: _this.state.isOpen ? _this.closeDropdown : _this.openDropdown, className: classNames(child.props.className, 'Dropdown-toggle') }); }); }, renderButton: function renderButton() { var disclosureArrow = this.props.buttonHasDisclosureArrow ? React.createElement('span', { className: 'disclosure-arrow' }) : null; return React.createElement( Button, { type: this.props.buttonType, onClick: this.state.isOpen ? this.closeDropdown : this.openDropdown, className: 'Dropdown-toggle' }, this.props.buttonLabel, disclosureArrow ); }, onClick: function onClick(selectedItem) { this.setState({ isOpen: !this.state.isOpen }); this.props.onSelect(selectedItem); }, renderDropdownMenu: function renderDropdownMenu() { var self = this; if (!this.state.isOpen) return null; var dropdownMenuItems = this.props.items.map(function (item, i) { var menuItem; if (item.type === 'header') { menuItem = React.createElement( 'li', { key: 'item-' + i, className: 'Dropdown-menu__header' }, item.label ); } else if (item.type === 'divider') { menuItem = React.createElement('li', { key: 'item-' + i, className: 'Dropdown-menu__divider' }); } else { menuItem = React.createElement( 'li', { key: 'item-' + i, className: 'Dropdown-menu__item' }, React.createElement( 'span', { className: 'Dropdown-menu__action', onClick: self.onClick.bind(self, item.value) }, item.label ) ); } return menuItem; }); return React.createElement( 'ul', { key: 'Dropdown-menu', className: 'Dropdown-menu', role: 'menu' }, dropdownMenuItems ); }, renderDropdownMenuBackground: function renderDropdownMenuBackground() { if (!this.state.isOpen) return null; return React.createElement('div', { className: 'Dropdown-menu-backdrop', onClick: this.closeDropdown }); }, render: function render() { // classes var dropdownClass = classNames('Dropdown', { 'is-open': this.state.isOpen, 'align-right': this.props.alignRight }, this.props.className); // props var props = blacklist(this.props, 'alignRight', 'buttonHasDisclosureArrow', 'buttonLabel', 'buttonType', 'className', 'isOpen', 'items'); return React.createElement( 'span', _extends({ className: dropdownClass }, props), React.Children.count(this.props.children) ? this.renderChildren() : this.renderButton(), React.createElement( Transition, { transitionName: 'Dropdown-menu', transitionEnterTimeout: 100, transitionLeaveTimeout: 100 }, this.renderDropdownMenu() ), this.renderDropdownMenuBackground() ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./Button":5,"blacklist":undefined,"classnames":undefined,"react-addons-css-transition-group":undefined}],12:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); var REGEXP_EMAIL = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; function validateEmail(value) { return REGEXP_EMAIL.test(value); } module.exports = React.createClass({ displayName: 'EmailInputGroup', propTypes: { alwaysValidate: React.PropTypes.bool, className: React.PropTypes.string, invalidMessage: React.PropTypes.string, label: React.PropTypes.string, onChange: React.PropTypes.func, required: React.PropTypes.bool, requiredMessage: React.PropTypes.string, value: React.PropTypes.string }, getDefaultProps: function getDefaultProps() { return { requiredMessage: 'Email address is required', invalidMessage: 'Please enter a valid email address' }; }, getInitialState: function getInitialState() { return { isValid: true, validationIsActive: this.props.alwaysValidate }; }, componentDidMount: function componentDidMount() { if (this.state.validationIsActive) { this.validateInput(this.props.value); } }, componentWillReceiveProps: function componentWillReceiveProps(newProps) { if (this.state.validationIsActive) { if (newProps.value !== this.props.value && newProps.value !== this._lastChangeValue && !newProps.alwaysValidate) { // reset validation state if the value was changed outside the component return this.setState({ isValid: true, validationIsActive: false }); } this.validateInput(newProps.value); } }, handleChange: function handleChange(e) { this._lastChangeValue = e.target.value; if (this.props.onChange) this.props.onChange(e); }, handleBlur: function handleBlur() { if (!this.props.alwaysValidate) { this.setState({ validationIsActive: false }); } this.validateInput(this.props.value); }, validateInput: function validateInput(value) { var newState = { isValid: true }; if (value.length && !validateEmail(value) || !value.length && this.props.required) { newState.isValid = false; } if (!newState.isValid) { newState.validationIsActive = true; } this.setState(newState); }, render: function render() { var validationMessage; if (!this.state.isValid) { validationMessage = React.createElement( 'div', { className: 'form-validation is-invalid' }, this.props.value.length ? this.props.invalidMessage : this.props.requiredMessage ); } var formGroupClass = classNames('FormField', { 'is-invalid': !this.state.isValid }, this.props.className); var componentLabel = this.props.label ? React.createElement( 'label', { className: 'FormLabel', htmlFor: 'inputEmail' }, this.props.label ) : null; return React.createElement( 'div', { className: formGroupClass }, componentLabel, React.createElement('input', { onChange: this.handleChange, onBlur: this.handleBlur, value: this.props.value, type: 'email', className: 'FormInput', placeholder: 'Enter email', id: 'inputEmail' }), validationMessage ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],13:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); /* Based on: https://github.com/paramaggarwal/react-dropzone */ var Dropzone = React.createClass({ displayName: 'Dropzone', propTypes: { className: React.PropTypes.string, label: React.PropTypes.string, labelActive: React.PropTypes.string, onDrop: React.PropTypes.func.isRequired }, getDefaultProps: function getDefaultProps() { return { label: 'Drag Files Here', labelActive: 'Drop to Upload' }; }, getInitialState: function getInitialState() { return { isDragActive: false }; }, onDragLeave: function onDragLeave() { this.setState({ isDragActive: false }); }, onDragOver: function onDragOver(e) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; this.setState({ isDragActive: true }); }, onDrop: function onDrop(e) { e.preventDefault(); this.setState({ isDragActive: false }); var files; if (e.dataTransfer) { files = e.dataTransfer.files; } else if (e.target) { files = e.target.files; } if (this.props.onDrop) { files = Array.prototype.slice.call(files); this.props.onDrop(files); } }, onClick: function onClick() { this.refs.fileInput.click(); }, render: function render() { var className = classNames('FileDragAndDrop', { 'active': this.state.isDragActive }, this.props.className); return React.createElement( 'button', { className: className, onClick: this.onClick, onDragLeave: this.onDragLeave, onDragOver: this.onDragOver, onDrop: this.onDrop }, React.createElement('input', { style: { display: 'none' }, type: 'file', multiple: true, ref: 'fileInput', onChange: this.onDrop }), React.createElement( 'div', { className: 'FileDragAndDrop__label' }, this.state.isDragActive ? this.props.labelActive : this.props.label ), this.props.children ); } }); module.exports = Dropzone; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],14:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var Button = require('./Button'); var Spinner = require('./Spinner'); module.exports = React.createClass({ displayName: 'FileUpload', propTypes: { buttonLabelChange: React.PropTypes.string, buttonLabelInitial: React.PropTypes.string, disabled: React.PropTypes.bool, file: React.PropTypes.object, // https://developer.mozilla.org/en/docs/Using_files_from_web_applications onChange: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { buttonLabelInitial: 'Upload File', buttonLabelChange: 'Change File' }; }, getInitialState: function getInitialState() { return { file: {}, loading: false }; }, componentDidMount: function componentDidMount() { this.refs.fileInput.addEventListener('click', function () { this.value = ''; }, false); }, triggerFileBrowser: function triggerFileBrowser() { this.refs.fileInput.click(); }, handleChange: function handleChange(e) { var self = this; var reader = new FileReader(); var file = e.target.files[0]; reader.readAsDataURL(file); reader.onloadstart = function () { console.time('onLoad'); self.setState({ loading: true }); }; reader.onloadend = function (upload) { console.timeEnd('onLoad'); self.setState({ loading: false, file: file, dataURI: upload.target.result }); }; }, cancelUpload: function cancelUpload() { this.setState({ dataURI: false, file: {} }); }, render: function render() { var _state = this.state; var dataURI = _state.dataURI; var file = _state.file; // props var props = blacklist(this.props, 'buttonClassChange', 'buttonClassInitial', 'buttonLabelChange', 'buttonLabelInitial', 'disabled', 'file', 'onChange'); // elements var component = React.createElement( Button, { onClick: this.triggerFileBrowser, disabled: this.props.disabled || this.state.loading }, this.state.loading && React.createElement(Spinner, null), this.props.buttonLabelInitial ); if (dataURI) { component = React.createElement( 'div', { className: 'FileUpload' }, React.createElement( 'div', { className: 'FileUpload__image' }, React.createElement('img', { className: 'FileUpload__image-src', src: dataURI }) ), React.createElement( 'div', { className: 'FileUpload__content' }, React.createElement( 'div', { className: 'FileUpload__message' }, file.name, ' (', Math.round(file.size / 1024), 'Kb)' ), React.createElement( 'div', { className: 'FileUpload__buttons' }, React.createElement( Button, { onClick: this.triggerFileBrowser, disabled: this.state.loading }, this.state.loading && React.createElement(Spinner, null), this.props.buttonLabelChange ), React.createElement( Button, { onClick: this.cancelUpload, type: 'link-cancel', disabled: this.state.loading }, 'Cancel' ) ) ) ); } return React.createElement( 'div', null, component, React.createElement('input', _extends({ style: { display: 'none' }, type: 'file', ref: 'fileInput', onChange: this.handleChange }, props)) ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./Button":5,"./Spinner":39,"blacklist":undefined}],15:[function(require,module,exports){ (function (global){ 'use strict'; var blacklist = require('blacklist'); var classnames = require('classnames'); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); module.exports = React.createClass({ displayName: 'Form', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, component: React.PropTypes.oneOfType([React.PropTypes.element, React.PropTypes.string]), type: React.PropTypes.oneOf(['basic', 'horizontal', 'inline']) }, getDefaultProps: function getDefaultProps() { return { component: 'form', type: 'basic' }; }, render: function render() { var props = blacklist(this.props, 'children', 'type'); props.className = classnames('Form', 'Form--' + this.props.type, this.props.className); return React.createElement(this.props.component, props, this.props.children); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],16:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'FormField', propTypes: { className: React.PropTypes.string, htmlFor: React.PropTypes.string, id: React.PropTypes.string, label: React.PropTypes.string, offsetAbsentLabel: React.PropTypes.bool, width: React.PropTypes.oneOf(['one-half', 'two-quarters', 'three-sixths', 'one-quarter', 'three-quarters', 'one-third', 'two-sixths', 'two-thirds', 'four-sixths', 'one-fifth', 'two-fifths', 'three-fifths', 'four-fifths', 'one-sixth', 'five-sixths']) }, render: function render() { // classes var componentClass = classNames('FormField', { 'offset-absent-label': this.props.offsetAbsentLabel }, this.props.width, this.props.className); // props var props = blacklist(this.props, 'className', 'label', 'offsetAbsentLabel', 'width'); // elements var componentLabel = this.props.label ? React.createElement( 'label', { className: 'FormLabel', htmlFor: this.props.id || this.props.htmlFor }, this.props.label ) : null; return React.createElement( 'div', _extends({ className: componentClass }, props), componentLabel, this.props.children ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],17:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); var Spinner = require('./Spinner'); var icons = require('../Octicons').map; module.exports = React.createClass({ displayName: 'FormIcon', propTypes: { className: React.PropTypes.string, color: React.PropTypes.oneOf(['danger', 'default', 'muted', 'primary', 'success', 'warning']), fill: React.PropTypes.oneOf(['danger', 'default', 'muted', 'primary', 'success', 'warning']), icon: React.PropTypes.string, isLoading: React.PropTypes.bool, type: React.PropTypes.string }, render: function render() { // classes var className = classNames('IconField__icon', icons[this.props.icon].className, this.props.fill ? 'IconField__icon-fill--' + this.props.fill : null, this.props.type ? 'IconField__icon-color--' + this.props.type : null, this.props.className); var component = this.props.isLoading ? React.createElement(Spinner, { size: 'sm' }) : React.createElement('div', { className: className }); return component; } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../Octicons":2,"./Spinner":39,"classnames":undefined}],18:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var classNames = require('classnames'); var FormField = require('./FormField'); var Spinner = require('./Spinner'); var ICON_MAP = require('../Octicons').map; var ICON_KEYS = require('../Octicons').keys; var COLOR_VARIANTS = ['danger', 'default', 'primary', 'success', 'warning']; module.exports = React.createClass({ displayName: 'FormIconField', propTypes: { className: React.PropTypes.string, iconColor: React.PropTypes.oneOf(COLOR_VARIANTS), iconFill: React.PropTypes.oneOf(COLOR_VARIANTS), iconIsLoading: React.PropTypes.bool, iconKey: React.PropTypes.oneOf(ICON_KEYS).isRequired, iconPosition: React.PropTypes.oneOf(['left', 'right']) }, getDefaultProps: function getDefaultProps() { return { iconPosition: 'left' }; }, render: function render() { // props var props = blacklist(this.props, 'children', 'iconPosition', 'iconKey', 'iconFill', 'iconColor', 'iconIsLoading'); // classes var fieldClass = classNames('IconField', { 'has-fill-icon': this.props.iconFill, 'is-loading-icon': this.props.iconIsLoading }, this.props.iconFill ? 'field-context-' + this.props.iconFill : null, this.props.iconColor ? 'field-context-' + this.props.iconColor : null, this.props.iconPosition); var iconClass = classNames('IconField__icon', this.props.iconFill ? 'IconField__icon-fill--' + this.props.iconFill : null, this.props.iconColor ? 'IconField__icon-color--' + this.props.iconColor : null, ICON_MAP[this.props.iconKey].className); var icon = this.props.iconIsLoading ? React.createElement(Spinner, { size: 'sm' }) : React.createElement('span', { className: iconClass }); return React.createElement( FormField, props, React.createElement( 'div', { className: fieldClass }, this.props.children, icon ) ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../Octicons":2,"./FormField":16,"./Spinner":39,"blacklist":undefined,"classnames":undefined}],19:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'FormInput', propTypes: { className: React.PropTypes.string, disabled: React.PropTypes.bool, focusOnMount: React.PropTypes.bool, href: React.PropTypes.string, id: React.PropTypes.string, multiline: React.PropTypes.bool, name: React.PropTypes.string, noedit: React.PropTypes.bool, onChange: React.PropTypes.func, size: React.PropTypes.oneOf(['lg', 'sm', 'xs']), type: React.PropTypes.string, value: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]) }, getDefaultProps: function getDefaultProps() { return { type: 'text' }; }, componentDidMount: function componentDidMount() { // if (this.props.focusOnMount) { // setTimeout(() => { // this.focus(); // }, 10); // } }, focus: function focus() { // If used in the future, will need to import ReactDOM from 'react-dom' to use findDOMNode(). // React.findDOMNode(this.refs.target).focus(); }, render: function render() { // classes var className = classNames({ 'FormInput-noedit': this.props.noedit, 'FormInput-noedit--multiline': this.props.noedit && this.props.multiline, 'FormInput': !this.props.noedit }, this.props.size ? 'FormInput--' + this.props.size : null, this.props.className); var props = _extends(blacklist(this.props, 'className'), { className: className, id: this.props.id || this.props.name }); // element var componentElement = 'input'; if (this.props.noedit && this.props.href) { componentElement = 'a'; props.type = null; props.children = props.children || props.value; } else if (this.props.noedit) { componentElement = 'div'; props.type = null; props.children = props.children || props.value; } else if (this.props.multiline) { componentElement = 'textarea'; } return React.createElement(componentElement, props); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],20:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'FormLabel', propTypes: { className: React.PropTypes.string, htmlFor: React.PropTypes.string, id: React.PropTypes.string, style: React.PropTypes.object, verticalAlign: React.PropTypes.oneOf(['baseline', 'bottom', 'inherit', 'initial', 'middle', 'sub', 'super', 'text-bottom', 'text-top', 'top']) }, render: function render() { // classes var className = classNames('FormLabel', this.props.className); // props var props = blacklist(this.props, 'htmlFor', 'id', 'className', 'style'); // style var style; if (this.props.verticalAlign) { style = { verticalAlign: this.props.verticalAlign }; } return React.createElement( 'label', _extends({ className: className, htmlFor: this.props.htmlFor || this.props.id, style: style || this.props.style }, props), this.props.children ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],21:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var classNames = require('classnames'); var NOTE_TYPES = ['default', 'primary', 'success', 'warning', 'danger']; module.exports = React.createClass({ displayName: 'FormNote', propTypes: { className: React.PropTypes.string, note: React.PropTypes.string, type: React.PropTypes.oneOf(NOTE_TYPES) }, getDefaultProps: function getDefaultProps() { return { type: 'default' }; }, render: function render() { // classes var componentClass = classNames('FormNote', this.props.type ? 'FormNote--' + this.props.type : null, this.props.className); // props var props = blacklist(this.props, 'className', 'note', 'type'); // allow users to pass through the note as an attribute or as children return React.createElement( 'div', _extends({ className: componentClass, dangerouslySetInnerHTML: this.props.note ? { __html: this.props.note } : null }, props), this.props.children ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],22:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'FormRow', propTypes: { className: React.PropTypes.string }, render: function render() { var className = classNames('FormRow', this.props.className); return React.createElement( 'div', { className: className }, this.props.children ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],23:[function(require,module,exports){ (function (global){ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); var _icons = require('../icons'); var _icons2 = _interopRequireDefault(_icons); module.exports = _react2['default'].createClass({ displayName: 'FormSelect', propTypes: { alwaysValidate: _react2['default'].PropTypes.bool, className: _react2['default'].PropTypes.string, disabled: _react2['default'].PropTypes.bool, firstOption: _react2['default'].PropTypes.string, htmlFor: _react2['default'].PropTypes.string, id: _react2['default'].PropTypes.string, label: _react2['default'].PropTypes.string, onChange: _react2['default'].PropTypes.func.isRequired, options: _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.shape({ label: _react2['default'].PropTypes.string, value: _react2['default'].PropTypes.string })).isRequired, prependEmptyOption: _react2['default'].PropTypes.bool, required: _react2['default'].PropTypes.bool, requiredMessage: _react2['default'].PropTypes.string, value: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { requiredMessage: 'This field is required' }; }, getInitialState: function getInitialState() { return { isValid: true, validationIsActive: this.props.alwaysValidate }; }, componentDidMount: function componentDidMount() { if (this.state.validationIsActive) { this.validateInput(this.props.value); } }, componentWillReceiveProps: function componentWillReceiveProps(newProps) { if (this.state.validationIsActive) { if (newProps.value !== this.props.value && newProps.value !== this._lastChangeValue && !newProps.alwaysValidate) { // reset validation state if the value was changed outside the component return this.setState({ isValid: true, validationIsActive: false }); } this.validateInput(newProps.value); } }, handleChange: function handleChange(e) { this._lastChangeValue = e.target.value; if (this.props.onChange) this.props.onChange(e.target.value); }, handleBlur: function handleBlur() { if (!this.props.alwaysValidate) { this.setState({ validationIsActive: false }); } this.validateInput(this.props.value); }, validateInput: function validateInput(value) { var newState = { isValid: true }; if (this.props.required && (!value || value && !value.length)) { newState.isValid = false; } if (!newState.isValid) { newState.validationIsActive = true; } this.setState(newState); }, renderIcon: function renderIcon(icon) { var iconClassname = (0, _classnames2['default'])('FormSelect__arrows', { 'FormSelect__arrows--disabled': this.props.disabled }); return _react2['default'].createElement('span', { dangerouslySetInnerHTML: { __html: icon }, className: iconClassname }); }, render: function render() { // props var props = (0, _blacklist2['default'])(this.props, 'prependEmptyOption', 'firstOption', 'alwaysValidate', 'htmlFor', 'id', 'label', 'onChange', 'options', 'required', 'requiredMessage', 'className'); // classes var componentClass = (0, _classnames2['default'])('FormField', { 'is-invalid': !this.state.isValid }, this.props.className); // validation message var validationMessage = undefined; if (!this.state.isValid) { validationMessage = _react2['default'].createElement( 'div', { className: 'form-validation is-invalid' }, this.props.requiredMessage ); } // dynamic elements var forAndID = this.props.htmlFor || this.props.id; var componentLabel = this.props.label ? _react2['default'].createElement( 'label', { className: 'FormLabel', htmlFor: forAndID }, this.props.label ) : null; // options var options = this.props.options.map(function (opt, i) { return _react2['default'].createElement( 'option', { key: 'option-' + i, value: opt.value }, opt.label ); }); if (this.props.prependEmptyOption || this.props.firstOption) { options.unshift(_react2['default'].createElement( 'option', { key: 'option-blank', value: '' }, this.props.firstOption ? this.props.firstOption : 'Select...' )); } return _react2['default'].createElement( 'div', { className: componentClass }, componentLabel, _react2['default'].createElement( 'select', _extends({ className: 'FormInput FormSelect', id: forAndID, onChange: this.handleChange, onBlur: this.handleBlur }, props), options ), this.renderIcon(_icons2['default'].selectArrows), validationMessage ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../icons":42,"blacklist":undefined,"classnames":undefined}],24:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); var icons = require('../Octicons').map; var validNames = require('../Octicons').keys; var Glyph = React.createClass({ displayName: 'Glyph', propTypes: { className: React.PropTypes.string, icon: React.PropTypes.oneOf(validNames), type: React.PropTypes.oneOf(['danger', 'default', 'muted', 'primary', 'success', 'warning']) }, render: function render() { // classes var className = classNames('Glyph__icon', icons[this.props.icon].className, this.props.type ? 'IconField__icon-color--' + this.props.type : null, this.props.className); return React.createElement('i', { className: className }); } }); module.exports = Glyph; module.exports.names = validNames; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../Octicons":2,"classnames":undefined}],25:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'InputGroup', propTypes: { className: React.PropTypes.string, contiguous: React.PropTypes.bool }, render: function render() { // classes var className = classNames('InputGroup', { 'InputGroup--contiguous': this.props.contiguous }, this.props.className); return React.createElement('div', _extends({}, this.props, { className: className })); } }); // expose the child to the top level export module.exports.Section = require('./InputGroupSection'); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./InputGroupSection":26,"classnames":undefined}],26:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'InputGroupSection', propTypes: { className: React.PropTypes.string, grow: React.PropTypes.bool }, render: function render() { // classes var className = classNames('InputGroup_section', { 'InputGroup_section--grow': this.props.grow }, this.props.className); return React.createElement('div', _extends({}, this.props, { className: className })); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],27:[function(require,module,exports){ (function (global){ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactAddonsCssTransitionGroup = require('react-addons-css-transition-group'); var _reactAddonsCssTransitionGroup2 = _interopRequireDefault(_reactAddonsCssTransitionGroup); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var TransitionPortal = _react2['default'].createClass({ displayName: 'TransitionPortal', portalElement: null, render: function render() { return null; }, componentDidMount: function componentDidMount() { var p = document.createElement('div'); document.body.appendChild(p); this.portalElement = p; this.componentDidUpdate(); }, componentWillUnmount: function componentWillUnmount() { document.body.removeChild(this.portalElement); }, componentDidUpdate: function componentDidUpdate() { _reactDom2['default'].render(_react2['default'].createElement( _reactAddonsCssTransitionGroup2['default'], this.props, this.props.children ), this.portalElement); } }); module.exports = _react2['default'].createClass({ displayName: 'Modal', propTypes: { backdropClosesModal: _react2['default'].PropTypes.bool, className: _react2['default'].PropTypes.string, isOpen: _react2['default'].PropTypes.bool, onCancel: _react2['default'].PropTypes.func }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.isOpen) { window.addEventListener('keydown', this.handleKeyDown); document.body.style.overflow = 'hidden'; } else { window.removeEventListener('keydown', this.handleKeyDown); document.body.style.overflow = null; } }, handleKeyDown: function handleKeyDown(event) { if (event.keyCode === 27) { this.props.onCancel(); } }, handleModalClick: function handleModalClick(event) { if (event.target.dataset.modal) this.props.onCancel(); }, renderDialog: function renderDialog() { if (!this.props.isOpen) return; return _react2['default'].createElement( 'div', { className: 'Modal-dialog' }, _react2['default'].createElement( 'div', { className: 'Modal-content' }, this.props.children ) ); }, renderBackdrop: function renderBackdrop() { if (!this.props.isOpen) return; return _react2['default'].createElement('div', { className: 'Modal-backdrop', onClick: this.props.backdropClosesModal ? this.props.onCancel : null }); }, render: function render() { var className = (0, _classnames2['default'])('Modal', { 'is-open': this.props.isOpen }, this.props.className); var props = (0, _blacklist2['default'])(this.props, 'backdropClosesModal', 'className', 'isOpen', 'onCancel'); return _react2['default'].createElement( 'div', null, _react2['default'].createElement( TransitionPortal, _extends({}, props, { 'data-modal': 'true', className: className, onClick: this.handleModalClick, transitionName: 'Modal-dialog', transitionEnterTimeout: 260, transitionLeaveTimeout: 140, component: 'div' }), this.renderDialog() ), _react2['default'].createElement( TransitionPortal, { transitionName: 'Modal-background', transitionEnterTimeout: 140, transitionLeaveTimeout: 240, component: 'div' }, this.renderBackdrop() ) ); } }); // expose the children to the top level export module.exports.Body = require('./ModalBody'); module.exports.Footer = require('./ModalFooter'); module.exports.Header = require('./ModalHeader'); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./ModalBody":28,"./ModalFooter":29,"./ModalHeader":30,"blacklist":undefined,"classnames":undefined,"react-addons-css-transition-group":undefined,"react-dom":undefined}],28:[function(require,module,exports){ (function (global){ '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 classnames = require('classnames'); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); module.exports = React.createClass({ displayName: 'ModalBody', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string }, render: function render() { var className = classnames('Modal__body', this.props.className); return React.createElement('div', _extends({}, this.props, { className: className })); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],29:[function(require,module,exports){ (function (global){ '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 classnames = require('classnames'); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); module.exports = React.createClass({ displayName: 'ModalFooter', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string }, render: function render() { var className = classnames('Modal__footer', this.props.className); return React.createElement('div', _extends({}, this.props, { className: className })); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],30:[function(require,module,exports){ (function (global){ '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 classnames = require('classnames'); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); module.exports = React.createClass({ displayName: 'ModalHeader', propTypes: { children: React.PropTypes.node, className: React.PropTypes.string, onClose: React.PropTypes.func, showCloseButton: React.PropTypes.bool, text: React.PropTypes.string }, render: function render() { // elements var className = classnames('Modal__header', this.props.className); var close = this.props.showCloseButton ? React.createElement('button', { type: 'button', onClick: this.props.onClose, className: 'Modal__header__close' }) : null; var text = this.props.text ? React.createElement( 'h4', { className: 'Modal__header__text' }, this.props.text ) : null; return React.createElement( 'div', _extends({}, this.props, { className: className }), close, text, this.props.children ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],31:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'Pagination', propTypes: { className: React.PropTypes.string, currentPage: React.PropTypes.number.isRequired, onPageSelect: React.PropTypes.func, pageSize: React.PropTypes.number.isRequired, plural: React.PropTypes.string, singular: React.PropTypes.string, style: React.PropTypes.object, total: React.PropTypes.number.isRequired, limit: React.PropTypes.number }, renderCount: function renderCount() { var count = ''; var _props = this.props; var currentPage = _props.currentPage; var pageSize = _props.pageSize; var plural = _props.plural; var singular = _props.singular; var total = _props.total; if (!total) { count = 'No ' + (plural || 'records'); } else if (total > pageSize) { var start = pageSize * (currentPage - 1) + 1; var end = Math.min(start + pageSize - 1, total); count = 'Showing ' + start + ' to ' + end + ' of ' + total; } else { count = 'Showing ' + total; if (total > 1 && plural) { count += ' ' + plural; } else if (total === 1 && singular) { count += ' ' + singular; } } return React.createElement( 'div', { className: 'Pagination__count' }, count ); }, onPageSelect: function onPageSelect(i) { if (!this.props.onPageSelect) return; this.props.onPageSelect(i); }, renderPages: function renderPages() { var _this = this; if (this.props.total <= this.props.pageSize) return null; var pages = []; var _props2 = this.props; var currentPage = _props2.currentPage; var pageSize = _props2.pageSize; var total = _props2.total; var limit = _props2.limit; var totalPages = Math.ceil(total / pageSize); var minPage = 0; var maxPage = totalPages; if (limit && limit < totalPages) { limit = Math.floor(limit / 2); minPage = currentPage - limit - 1; maxPage = currentPage + limit; if (minPage < 0) { maxPage = maxPage - minPage; minPage = 0; } if (maxPage > totalPages) { minPage = totalPages - 2 * limit - 1; maxPage = totalPages; } } if (minPage > 0) { pages.push(React.createElement( 'button', { key: 'page_start', className: 'Pagination__list__item', onClick: function () { return _this.onPageSelect(1); } }, '...' )); } var _loop = function (i) { var page = i + 1; var current = page === currentPage; var className = classNames('Pagination__list__item', { 'is-selected': current }); /* eslint-disable no-loop-func */ pages.push(React.createElement( 'button', { key: 'page_' + page, className: className, onClick: function () { return _this.onPageSelect(page); } }, page )); /* eslint-enable */ }; for (var i = minPage; i < maxPage; i++) { _loop(i); } if (maxPage < totalPages) { pages.push(React.createElement( 'button', { key: 'page_end', className: 'Pagination__list__item', onClick: function () { return _this.onPageSelect(totalPages); } }, '...' )); } return React.createElement( 'div', { className: 'Pagination__list' }, pages ); }, render: function render() { var className = classNames('Pagination', this.props.className); return React.createElement( 'div', { className: className, style: this.props.style }, this.renderCount(), this.renderPages() ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],32:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); function validatePassword(value) { return value.length >= 8; } module.exports = React.createClass({ displayName: 'PasswordInputGroup', propTypes: { alwaysValidate: React.PropTypes.bool, className: React.PropTypes.string, validatePassword: React.PropTypes.func, invalidMessage: React.PropTypes.string, label: React.PropTypes.string, onChange: React.PropTypes.func, required: React.PropTypes.bool, requiredMessage: React.PropTypes.string, value: React.PropTypes.string }, getDefaultProps: function getDefaultProps() { return { validatePassword: validatePassword, requiredMessage: 'Password is required', invalidMessage: 'Password must be at least 8 characters in length' }; }, getInitialState: function getInitialState() { return { isValid: true, validationIsActive: this.props.alwaysValidate }; }, componentDidMount: function componentDidMount() { if (this.state.validationIsActive) { this.validateInput(this.props.value); } }, componentWillReceiveProps: function componentWillReceiveProps(newProps) { if (this.state.validationIsActive) { if (newProps.value !== this.props.value && newProps.value !== this._lastChangeValue && !newProps.alwaysValidate) { // reset validation state if the value was changed outside the component return this.setState({ isValid: true, validationIsActive: false }); } this.validateInput(newProps.value); } }, handleChange: function handleChange(e) { this._lastChangeValue = e.target.value; if (this.props.onChange) this.props.onChange(e); }, handleBlur: function handleBlur() { if (!this.props.alwaysValidate) { this.setState({ validationIsActive: false }); } this.validateInput(this.props.value); }, validateInput: function validateInput(value) { var newState = { isValid: true }; if (value.length && !this.props.validatePassword(value) || !value.length && this.props.required) { newState.isValid = false; } if (!newState.isValid) { newState.validationIsActive = true; } this.setState(newState); }, render: function render() { var validationMessage; if (!this.state.isValid) { validationMessage = React.createElement( 'div', { className: 'form-validation is-invalid' }, this.props.value.length ? this.props.invalidMessage : this.props.requiredMessage ); } var formGroupClass = classNames('FormField', { 'is-invalid': !this.state.isValid }, this.props.className); var componentLabel = this.props.label ? React.createElement( 'label', { className: 'FormLabel', htmlFor: 'inputPassword' }, this.props.label ) : null; return React.createElement( 'div', { className: formGroupClass }, componentLabel, React.createElement('input', { onChange: this.handleChange, onBlur: this.handleBlur, value: this.props.value, type: 'password', className: 'FormInput', placeholder: 'Enter password', id: 'inputPassword' }), validationMessage ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],33:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var classNames = require('classnames'); var ALERT_TYPES = ['danger', 'default', 'info', 'primary', 'success', 'warning', 'danger-inverted', 'default-inverted', 'info-inverted', 'primary-inverted', 'success-inverted', 'warning-inverted']; module.exports = React.createClass({ displayName: 'Pill', propTypes: { className: React.PropTypes.string, label: React.PropTypes.string.isRequired, onClear: React.PropTypes.func, onClick: React.PropTypes.func, type: React.PropTypes.oneOf(ALERT_TYPES) }, getDefaultProps: function getDefaultProps() { return { type: 'default' }; }, renderClearButton: function renderClearButton() { if (!this.props.onClear) return null; return React.createElement( 'button', { type: 'button', onClick: this.props.onClear, className: 'Pill__clear' }, '×' ); }, render: function render() { var componentClass = classNames('Pill', 'Pill--' + this.props.type, this.props.className); var props = blacklist(this.props, 'className', 'label', 'onClear', 'onClick', 'type'); props.className = componentClass; return React.createElement( 'div', props, React.createElement( 'button', { type: 'button', onClick: this.props.onClick, className: 'Pill__label' }, this.props.label ), this.renderClearButton() ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],34:[function(require,module,exports){ (function (global){ '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 blacklist = require('blacklist'); var classNames = require('classnames'); var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var Radio = React.createClass({ displayName: 'Radio', propTypes: { className: React.PropTypes.string, disabled: React.PropTypes.bool, inline: React.PropTypes.bool, label: React.PropTypes.string }, render: function render() { var componentClass = classNames('Radio', { 'Radio--disabled': this.props.disabled, 'Radio--inline': this.props.inline }, this.props.className); var props = blacklist(this.props, 'className', 'label'); return React.createElement( 'label', { className: componentClass }, React.createElement('input', _extends({ type: 'radio', className: 'Radio__input' }, props)), this.props.label && React.createElement( 'span', { className: 'Radio__label' }, this.props.label ) ); } }); module.exports = Radio; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],35:[function(require,module,exports){ (function (global){ '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 = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var blacklist = require('blacklist'); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'RadioGroup', propTypes: { alwaysValidate: React.PropTypes.bool, className: React.PropTypes.string, inline: React.PropTypes.bool, label: React.PropTypes.string, onChange: React.PropTypes.func.isRequired, options: React.PropTypes.array.isRequired, required: React.PropTypes.bool, requiredMessage: React.PropTypes.string, value: React.PropTypes.string }, getDefaultProps: function getDefaultProps() { return { requiredMessage: 'This field is required' }; }, getInitialState: function getInitialState() { return { isValid: true, validationIsActive: this.props.alwaysValidate }; }, componentDidMount: function componentDidMount() { if (this.state.validationIsActive) { this.validateInput(this.props.value); } }, componentWillReceiveProps: function componentWillReceiveProps(newProps) { if (this.state.validationIsActive) { if (newProps.value !== this.props.value && newProps.value !== this._lastChangeValue && !newProps.alwaysValidate) { // reset validation state if the value was changed outside the component return this.setState({ isValid: true, validationIsActive: false }); } this.validateInput(newProps.value); } }, handleChange: function handleChange(e) { this._lastChangeValue = e.target.value; if (this.props.onChange) this.props.onChange(e.target.value); }, handleBlur: function handleBlur() { if (!this.props.alwaysValidate) { this.setState({ validationIsActive: false }); } this.validateInput(this.props.value); }, validateInput: function validateInput(value) { var newState = { isValid: true }; if (this.props.required && (!value || value && !value.length)) { newState.isValid = false; } if (!newState.isValid) { newState.validationIsActive = true; } this.setState(newState); }, render: function render() { var self = this; // props var props = blacklist(this.props, 'alwaysValidate', 'label', 'onChange', 'options', 'required', 'requiredMessage', 'value'); // classes var componentClass = classNames('FormField', { 'is-invalid': !this.state.isValid }, this.props.className); // validation message var validationMessage; if (!this.state.isValid) { validationMessage = React.createElement( 'div', { className: 'form-validation is-invalid' }, this.props.requiredMessage ); } // dynamic elements var componentLabel = this.props.label ? React.createElement( 'label', { className: 'FormLabel' }, this.props.label ) : null; // options var radios = this.props.options.map(function (radio, i) { return React.createElement( 'label', { key: 'radio-' + i, className: 'Radio' }, React.createElement('input', { value: radio.value, type: 'radio', onChange: self.handleChange, onBlur: self.handleBlur, name: self.props.name, className: 'Radio__input' }), React.createElement( 'span', { className: 'Radio__label' }, radio.label ) ); }); if (this.props.inline) { radios = React.createElement( 'div', { className: 'inline-controls' }, radios ); } return React.createElement( 'div', _extends({ className: componentClass }, props), componentLabel, radios, validationMessage ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"blacklist":undefined,"classnames":undefined}],36:[function(require,module,exports){ (function (global){ 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _constants = require('../constants'); var _constants2 = _interopRequireDefault(_constants); module.exports = _react2['default'].createClass({ displayName: 'ResponsiveText', propTypes: { hiddenLG: _react2['default'].PropTypes.string, hiddenMD: _react2['default'].PropTypes.string, hiddenSM: _react2['default'].PropTypes.string, hiddenXS: _react2['default'].PropTypes.string, visibleLG: _react2['default'].PropTypes.string, visibleMD: _react2['default'].PropTypes.string, visibleSM: _react2['default'].PropTypes.string, visibleXS: _react2['default'].PropTypes.string }, getInitialState: function getInitialState() { return { windowWidth: window.innerWidth }; }, componentDidMount: function componentDidMount() { window.addEventListener('resize', this.handleResize); }, componentWillUnmount: function componentWillUnmount() { window.removeEventListener('resize', this.handleResize); }, handleResize: function handleResize() { this.setState({ windowWidth: window.innerWidth }); }, render: function render() { var _props = this.props; var hiddenXS = _props.hiddenXS; var hiddenSM = _props.hiddenSM; var hiddenMD = _props.hiddenMD; var hiddenLG = _props.hiddenLG; var visibleXS = _props.visibleXS; var visibleSM = _props.visibleSM; var visibleMD = _props.visibleMD; var visibleLG = _props.visibleLG; var windowWidth = this.state.windowWidth; var text = undefined; // set widths / flex-basis if (windowWidth < _constants2['default'].breakpoint.xs) { text = visibleXS || hiddenSM || hiddenMD || hiddenLG; } else if (windowWidth < _constants2['default'].breakpoint.sm) { text = hiddenXS || visibleSM || hiddenMD || hiddenLG; } else if (windowWidth < _constants2['default'].breakpoint.md) { text = hiddenXS || hiddenSM || visibleMD || hiddenLG; } else { text = hiddenXS || hiddenSM || hiddenMD || visibleLG; } var props = (0, _blacklist2['default'])(this.props, { 'hiddenXS': true, 'hiddenSM': true, 'hiddenMD': true, 'hiddenLG': true, 'visibleXS': true, 'visibleSM': true, 'visibleMD': true, 'visibleLG': true }); return _react2['default'].createElement( 'span', props, text ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../constants":41,"blacklist":undefined}],37:[function(require,module,exports){ (function (global){ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _constants = require('../constants'); var _constants2 = _interopRequireDefault(_constants); module.exports = _react2['default'].createClass({ displayName: 'Row', propTypes: { children: _react2['default'].PropTypes.node.isRequired, className: _react2['default'].PropTypes.string, gutter: _react2['default'].PropTypes.number, style: _react2['default'].PropTypes.object }, getDefaultProps: function getDefaultProps() { return { gutter: _constants2['default'].width.gutter }; }, render: function render() { var gutter = this.props.gutter; var rowStyle = { display: 'flex', flexWrap: 'wrap', msFlexWrap: 'wrap', WebkitFlexWrap: 'wrap', marginLeft: gutter / -2, marginRight: gutter / -2 }; var className = (0, _classnames2['default'])('Row', this.props.className); var props = (0, _blacklist2['default'])(this.props, 'className', 'gutter', 'style'); return _react2['default'].createElement('div', _extends({}, props, { style: _extends(rowStyle, this.props.style), className: className })); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../constants":41,"blacklist":undefined,"classnames":undefined}],38:[function(require,module,exports){ (function (global){ 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); module.exports = _react2['default'].createClass({ displayName: 'SegmentedControl', propTypes: { className: _react2['default'].PropTypes.string, equalWidthSegments: _react2['default'].PropTypes.bool, onChange: _react2['default'].PropTypes.func.isRequired, options: _react2['default'].PropTypes.array.isRequired, type: _react2['default'].PropTypes.oneOf(['default', 'muted', 'danger', 'info', 'primary', 'success', 'warning']), value: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { type: 'default' }; }, onChange: function onChange(value) { this.props.onChange(value); }, render: function render() { var _this = this; var componentClassName = (0, _classnames2['default'])('SegmentedControl', 'SegmentedControl--' + this.props.type, { 'SegmentedControl--equal-widths': this.props.equalWidthSegments }, this.props.className); var options = this.props.options.map(function (op) { var buttonClassName = (0, _classnames2['default'])('SegmentedControl__button', { 'is-selected': op.value === _this.props.value }); return _react2['default'].createElement( 'span', { key: 'option-' + op.value, className: 'SegmentedControl__item' }, _react2['default'].createElement( 'button', { type: 'button', onClick: _this.onChange.bind(_this, op.value), className: buttonClassName }, op.label ) ); }); return _react2['default'].createElement( 'div', { className: componentClassName }, options ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],39:[function(require,module,exports){ (function (global){ 'use strict'; var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'Spinner', propTypes: { className: React.PropTypes.string, size: React.PropTypes.oneOf(['sm', 'md', 'lg']), type: React.PropTypes.oneOf(['default', 'primary', 'inverted']) }, getDefaultProps: function getDefaultProps() { return { type: 'default', size: 'sm' }; }, render: function render() { var componentClass = classNames('Spinner', 'Spinner--' + this.props.type, 'Spinner--' + this.props.size, this.props.className); return React.createElement( 'div', { className: componentClass }, React.createElement('span', { className: 'Spinner_dot Spinner_dot--first' }), React.createElement('span', { className: 'Spinner_dot Spinner_dot--second' }), React.createElement('span', { className: 'Spinner_dot Spinner_dot--third' }) ); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],40:[function(require,module,exports){ (function (global){ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); var _react2 = _interopRequireDefault(_react); module.exports = _react2['default'].createClass({ displayName: 'Table', propTypes: { children: _react2['default'].PropTypes.any, className: _react2['default'].PropTypes.string }, render: function render() { // classes var className = (0, _classnames2['default'])('Table', this.props.className); // render table element return _react2['default'].createElement('table', _extends({ className: className }, this.props)); } }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"classnames":undefined}],41:[function(require,module,exports){ // breakpoints 'use strict'; exports.breakpoint = { xs: 480, sm: 768, md: 992, lg: 1200 }; // border radii exports.borderRadius = { xs: 2, sm: 4, md: 8, lg: 16, xl: 32 }; // color exports.color = { appDanger: '#d64242', appInfo: '#56cdfc', appPrimary: '#1385e5', appSuccess: '#34c240', appWarning: '#fa9f47', brandPrimary: '#31adb8' }; // spacing exports.spacing = { xs: 5, sm: 10, md: 20, lg: 40, xl: 80 }; // widths exports.width = { container: 1170, gutter: 20 }; // fractions (for col widths) function perc(n) { return n * 100 + '%'; } function denominators(n) { for (var d = 2; d <= 20; d++) { if (n < d) { exports.fractions[n + '/' + d] = perc(n / d); } } } exports.fractions = {}; for (var numerator = 1; numerator <= 19; numerator++) { denominators(numerator); } },{}],42:[function(require,module,exports){ 'use strict'; module.exports = { selectArrows: require('./selectArrows') }; },{"./selectArrows":43}],43:[function(require,module,exports){ 'use strict'; module.exports = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' + '<svg width="7px" height="11px" viewBox="0 0 7 11" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' + '<path d="M3.5,0 L7,4 L0,4 L3.5,0 Z M3.5,11 L7,7 L0,7 L3.5,11 Z" />' + '</svg>'; },{}]},{},[1])(1) });